text
stringlengths
28
935k
meta
stringlengths
137
139
red_pajama_subset
stringclasses
1 value
\section{Conclusion} In this paper, we presented a new framework for solving nonconvex-nonconcave minimax optimization problems based on the assumption that the $\min$ player has knowledge of the \emph{smooth} algorithms being used by $\max$ player, proposed new efficient algorithms under this framework and verified the efficacy of these algorithms in practice on small-scale generative adversarial network and adversarial training problems. There are several interesting directions for future work such as understanding the efficacy of these algorithms on large scale problems, developing new techniques to deal with nonsmooth algorithms such as projected gradient ascent and extending this framework to more general settings such as nonzero sum games. \subsection{Computing stochastic subgradients of $g(x)$}\label{sec:subgrad} In this section, we give a characterization of subgradients of $g(x)$ and show how to compute stochastic subgradients efficiently under the following assumption. \begin{assumption}\label{ass:smoothalgo} Algorithms $\mathcal{A}_i$ in \eqref{eqn:minimax-mod} are $G'$-Lipschitz and $L'$-gradient Lipschitz as per Definition~\ref{def:smooth}. \end{assumption} Under Assumptions~\ref{ass:func-smooth} and~\ref{ass:smoothalgo}, Lemma~\ref{lem:smooth-func} tells us that $g_{z,i}(x)$ is a $G(1+G')$-Lipschitz and $L(1+G')^2 + GL'$-gradient Lipschitz function for every $i \in [k]$ with \begin{align}\label{eqn:grad-form} \nabla g_{z,i}(x) = \nabla_x f(x,\mathcal{A}_i(x,z_i)) + D\mathcal{A}_i(x,z_i) \cdot \nabla_y f(x,\mathcal{A}_i(x,z_i)), \end{align} where we recall that $D\mathcal{A}_i(x,z_i) \in \mathbb{R}^{d_1 \times d_2}$ is the Jacobian matrix of $\mathcal{A}_i(\cdot,z_i): \mathbb{R}^{d_1} \rightarrow \mathbb{R}^{d_2}$ at $x$ and $\nabla_x f(x,\mathcal{A}_i(x,z_i))$ denotes the partial derivative of $f$ with respect to the first variable at $(x,\mathcal{A}_i(x,z_i))$. While there is no known general recipe for computing $D\mathcal{A}_i(x,z_i)$ for an arbitrary algorithm $\mathcal{A}_i$, most algorithms used in practice such as stochastic gradient ascent (SGA), stochastic Nesterov accelerated gradient (SNAG), ADAM, admit efficient ways of computing these derivatives e.g., \emph{higher} package in PyTorch~\cite{grefenstette2019generalized}. For concreteness, we obtain expression for gradients of SGA and SNAG in Section~\ref{sec:smoothness} but the principle behind the derivation holds much more broadly and can be extended to most algorithms used in practice~\cite{grefenstette2019generalized}. In practice, the cost of computing $\nabla g_{z,i}(x)$ in~\eqref{eqn:grad-form} is at most twice the cost of evaluating $g_{z,i}(x)$---it consists a forward pass for evaluating $g_{z,i}(x)$ and a backward pass for evaluating its gradient~\cite{grefenstette2019generalized}. Lemma~\ref{lem:argmax-weakconvex} shows that $g(x) \mathrel{\mathop:}= \mathbb{E}_{z}\left[\max_{i\in[k]} g_{z,i}(x)\right]$ is a weakly convex function and a stochastic subgradient of $g(\cdot)$ can be computed by generating a random sample of $z_1,\cdots,z_k$ as: \begin{equation}\label{eqn:stoch-subgrad} \widehat{\nabla} g(x) = \sum_{j \in S(x)} \lambda_j \nabla g_{z,i}(x) \text{~for any~} \lambda \in \Delta_k, \text{~where~} S(x) \mathrel{\mathop:}= \mathop{\mathrm{argmax}}_{i \in [k]} g_{z,i}(x) \end{equation} Here $\Delta_k$ is the $k$-dimensional probability simplex. It can be seen that $\mathbb{E}_{z}[\hat{\nabla} g(x)] \in \partial g(x)$. Furthermore, if all $\mathcal{A}_i$ are deterministic algorithms, then the above is indeed a subgradient of $g$. \subsection{Convergence rate of SGD}\label{sec:conv-sgd} \begin{algorithm}[t] \DontPrintSemicolon \KwIn{initial point $x_0$, step size $\eta$} \For{$s = 0, 1, \ldots, S$}{ Sample $z_1,\cdots,z_k$ and compute $\widehat{\nabla} g(x_s)$ according to eq. \eqref{eqn:stoch-subgrad}. $x_{s+1} \leftarrow x_s - \eta \widehat{\nabla} g(x_s)$. } \textbf{return} $\bar{x} \leftarrow x_s$, where $s$ is uniformly sampled from $\{0,\cdots,S\}$. \caption{Stochastic subgradient descent (SGD)} \label{algo:sgd} \end{algorithm} The SGD algorithm to solve~\eqref{eqn:minimax-mod} is given in Algorithm~\ref{algo:sgd}. The following theorem shows that Algorithm~\ref{algo:sgd} finds an $\epsilon$-FOSP of $g(\cdot)$ in $S=\order{\epsilon^{-4}}$ iterations. Since each iteration of Algorithm~\ref{algo:sgd} requires computing the gradient of $g_{z,i}(x)$ for each $i\in[k]$ at a single point $x_s$, this leads to a total of $S=\order{\epsilon^{-4}}$ gradient computations for each $g_{z,i}(x)$. \begin{theorem}\label{thm:main-sgd} Under Assumptions~\ref{ass:func-smooth} and~\ref{ass:smoothalgo}, if $S \geq 16 B \widehat{L} \widehat{G}^2 \epsilon^{-4}$ and learning rate $\eta = (2B/[\widehat{L} \widehat{G}^2 ({S+1})])^{1/2}$ then output of Algorithm~\ref{algo:sgd} satisfies $\mathbb{E}[\norm{\nabla g_{1/2\widehat{L}}(\bar{x})}^2] \leq \epsilon^2$, where $\widehat{L} \mathrel{\mathop:}= L(1+G')^2 + GL'$ and $\widehat{G}\mathrel{\mathop:}= G (1+G')$. \end{theorem} Theorem~\ref{thm:main-sgd} claims that the expected norm squared of the Moreau envelope gradient of the output point satisfies the condition for being an $\epsilon$-FOSP. This, together with Markov's inequality, implies that at least half of $x_0,\cdots,x_S$ are $2\epsilon$-FOSPs, so that the probability of outputting a $2\epsilon$-FOSP is at least $0.5$. Proposition~\ref{prop:postproc} in Appendix~\ref{app:sgd} shows how to use an efficient postprocessing mechanism to output a $2\epsilon$-FOSP with high probability. Theorem~\ref{thm:main-sgd} essentially follows from the results of~\cite{davis2018stochastic}, where the key insight is that, in expectation, the SGD procedure in Algorithm~\ref{algo:sgd} almost monotonically decreases the Moreau envelope evaluated at $x_s$ i.e., $\mathbb{E} \left[g_{1/2\widehat{L}}(x_s)\right]$ is almost monotonically decreasing. This shows that Algorithm~\ref{algo:sgd} makes (almost) monotonic progress in a precise sense and hence does not have limit cycles. In contrast, none of the other existing algorithms for nonconvex-nonconcave minimax optimization enjoy such a guarantee. \subsection{Proximal algorithm with faster convergence for deterministic algorithms}\label{sec:prox} \begin{algorithm}[t] \DontPrintSemicolon \KwIn{initial point $x_0$, target accuracy $\epsilon$, smoothness parameter $\widehat{L}$} $\widehat{\epsilon} \leftarrow \epsilon^2/(64\widehat{L})$\; \For{$t = 0, 1, \ldots, S$} { Find $x_{s+1}$ such that $\max_{i \in [k]} g_i(x_{s+1}) + \widehat{L} \norm{x_s - x_{s+1}}^2 \leq \left(\min_x \max_{i \in [k]} g_i(x) + \widehat{L} \norm{x_s - x}^2\right) + \widehat{\epsilon}/4$\label{step:3} \If{$\max_{i \in [k]} g_i(x_{s+1}) + \widehat{L} \norm{x_s - x_{s+1}}^2 \geq \max_{i \in [k]} g_i(x_s) - 3\widehat{\epsilon}/4$} { \KwRet{$x_{s}$} } } \caption{Proximal algorithm} \label{algo:prox} \end{algorithm} While the rate achieved by SGD is the best known for weakly-convex optimization with a stochastic subgradient oracle, faster algorithms exist for functions which can be written as \emph{maximum over a finite number of smooth functions} with \emph{access to exact subgradients of these component functions}. These conditions are satisfied when $\mathcal{A}_i$ are all deterministic and satisfy Assumption~\ref{ass:smoothalgo}. A pseudocode of such a fast proximal algorithm, inspired by~\cite[Algorithm 3]{thekumparampil2019efficient}, is presented in Algorithm~\ref{algo:prox}. However, in contrast to the results of~\cite{thekumparampil2019efficient}, the following theorem provides two alternate ways of implementing Step $3$ of Algorithm~\ref{algo:prox}, resulting in two different (and incomparable) convergence rates. \begin{theorem}\label{thm:prox} Under Assumptions~\ref{ass:func-smooth} and~\ref{ass:smoothalgo}, if $\widehat{L} \mathrel{\mathop:}= L(1+G')^2 + GL' + k G(1+G')$ and $S \geq 200 \widehat{L} B \epsilon^{-2}$ then Algorithm~\ref{algo:prox} returns $x_s$ satisfying $\norm{\nabla g_{1/2 \widehat{L}}(x_s)} \leq \epsilon$. Depending on whether we use~\cite[Algorithm 1]{thekumparampil2019efficient} or cutting plane method~\cite{lee2015faster} for solving Step $3$ of Algorithm~\ref{algo:prox}, the total number of gradient computations of each $g_i$ is $\otilde{\frac{\widehat{L}^2 B}{\epsilon^3}}$ or $\order{\frac{\widehat{L} B}{\epsilon^2} \cdot \mathrm{poly}(k)\log \frac{\widehat{L}}{\epsilon}}$ respectively. \end{theorem} Ignoring the parameters $L,G,L'$ and $G'$, the above theorem tells us that Algorithm~\ref{algo:prox} outputs an $\epsilon$-FOSP using $\order{k\epsilon^{-3}}$ or $\order{\mathrm{poly}(k) \epsilon^{-2} \log \frac{1}{\epsilon}}$ gradient queries to each $g_i$ depending on whether \cite[Algorithm 3]{thekumparampil2019efficient} or cutting plane method~\cite{lee2015faster} was used for implementing Step $3$. While the proximal algorithm itself works even when $\mathcal{A}_i$ are randomized algorithms, there are no known algorithms that can implement Step (3) with fewer than $\order{\epsilon^{-2}}$ stochastic gradient queries. Hence, this does not improve upon the $\order{\epsilon^{-4}}$ guarantee for Algorithm~\ref{algo:sgd} when $\mathcal{A}_i$ are randomized algorithms. The proof of Theorem~\ref{thm:prox} shows that the iterates $x_s$ monotonically decrease the value $g(x_s)$, guaranteeing that there are no limit cycles for Algorithm~\ref{algo:prox} as well. \section{Additional Experiments and Details} \label{app:experiments} In this appendix section, we provide additional experimental results and details. \textbf{Dirac-GAN.} In the results presented in Section~\ref{sec:empirical} for this problem, the discriminator sampled its initialization uniformly from the interval $[-0.1, 0.1]$ and performed $T=10$ steps of gradient ascent. For the results given in Figure~\ref{fig:dirac_app}, we allow the discriminator to sample uniformly from the interval $[-0.5, 1]$ and consider the discriminator performing $T=100$ (Figure~\ref{fig:dirac_app_a}) and $T=1000$ (Figure~\ref{fig:dirac_app_b}) gradient ascent steps. The rest of the experimental setup is equivalent to that described in Section~\ref{sec:empirical}. For the result presented in Figure~\ref{fig:dirac_app_a}, we see that with this distribution of initializations for the discriminator and $T=100$ gradient ascent steps, the generator is not able to converge to the optimal parameter of $\theta^{\ast}=0$ to recreate the underlying data distribution using our algorithm which descends $\nabla f(\theta, \mathcal{A}(\theta))$ or the algorithm that descends $\nabla_\theta f(\theta, \mathcal{A}(\theta))$. However, we see that our algorithm converges significantly closer to the optimal parameter configuration. Furthermore, we still observe stability and convergence from our training method, whereas standard training methods using simultaneous or alternating gradient descent-ascent always cycle. This example highlights that the optimization through the algorithm of the adversary is important not only for the rate of convergence, but it also influences what the training method converges to and gives improved results in this regard. Finally, in the result presented in Figure~\ref{fig:dirac_app_a}, we see that with this distribution of initializations for the discriminator and $T=1000$ gradient ascent steps, the generator is able to converge to the optimal parameter of $\theta^{\ast}=0$ to recreate the underlying data distribution using our algorithm which descends $\nabla f(\theta, \mathcal{A}(\theta))$ or the algorithm that descends $\nabla_\theta f(\theta, \mathcal{A}(\theta))$. Thus, while with $T=100$ we did not observe convergence to the optimal generator parameter, with a stronger adversary we do see convergence to the optimal generator parameter. This behavior can be explained by the fact that when the discriminator is able to perform enough gradient ascent steps to nearly converge, the gradients $\nabla f(\theta, \mathcal{A}(\theta))$ and $\nabla_\theta f(\theta, \mathcal{A}(\theta))$ are nearly equivalent. We remark that we repeated the experiments 5 times with different random seeds and show the mean generator parameters during the training with a window around the mean of a standard deviation. The results were very similar between runs so the window around the mean is not visible. \begin{figure}[t!] \centering \subfloat{\includegraphics[width=.35\textwidth]{Figs/dirac_legend2.png}} \subfloat[][]{\includegraphics[width=.35\textwidth]{Figs/param_sets1.png}\label{fig:dirac_app_a}} \subfloat[][]{\includegraphics[width=.35\textwidth]{Figs/param_sets2.png}\label{fig:dirac_app_b}} \caption{\textbf{Dirac-GAN}: Generator parameters while training using our framework with and without optimizing through the discriminator where between each generator update the discriminator samples an initial parameter choice uniformly at random from the interval $[-0.5, 1]$ and then performs $T=100$ (Figure~\ref{fig:dirac_app_a}) and $T=1000$ (Figure~\ref{fig:dirac_app_b}) steps of gradient ascent.} \label{fig:dirac_app} \end{figure} \begin{figure}[t!] \centering \begin{minipage}{.9\textwidth} \begin{minipage}{.2\textwidth} \subfloat[][Real Data]{\includegraphics[width=.9\textwidth]{Figs/samples_real_gaussian.png}\label{fig:gan_real_app}} \end{minipage}% \begin{minipage}{.8\textwidth} \subfloat[][]{\includegraphics[width=.19\textwidth]{Figs/higher_gan/final_seeds/samples_final_1.png}\label{fig:samples_final1}} \subfloat[][]{\includegraphics[width=.19\textwidth]{Figs/higher_gan/final_seeds/samples_final_2.png}\label{fig:samples_final2}} \subfloat[][]{\includegraphics[width=.19\textwidth]{Figs/higher_gan/final_seeds/samples_final_3.png}\label{fig:samples_final3}} \subfloat[][]{\includegraphics[width=.19\textwidth]{Figs/higher_gan/final_seeds/samples_final_4.png}\label{fig:samples_final4}} \subfloat[][]{\includegraphics[width=.19\textwidth]{Figs/higher_gan/final_seeds/samples_final_5.png}\label{fig:samples_final5}} \subfloat[][]{\includegraphics[width=.19\textwidth]{Figs/higher_gan/final_seeds/samples_final_6.png}\label{fig:samples_final6}} \subfloat[][]{\includegraphics[width=.19\textwidth]{Figs/higher_gan/final_seeds/samples_final_7.png}\label{fig:samples_final7}} \subfloat[][]{\includegraphics[width=.19\textwidth]{Figs/higher_gan/final_seeds/samples_final_8.png}\label{fig:samples_final8}} \subfloat[][]{\includegraphics[width=.19\textwidth]{Figs/higher_gan/final_seeds/samples_final_9.png}\label{fig:samples_final9}} \subfloat[][]{\includegraphics[width=.19\textwidth]{Figs/higher_gan/final_seeds/samples_final_10.png}\label{fig:samples_final10}} \end{minipage} \end{minipage} \caption{\textbf{Mixture of Gaussians}: Figure~\ref{fig:gan_real_app} shows the real data distribution and Figures~\ref{fig:samples_final1}--\ref{fig:samples_final10} show the final generated distributions after 150k generator updates from 10 separate runs of the training procedure described in Section~\ref{sec:empirical} using gradient ascent for the discriminator. Each run recovers a generator distribution closely resembling the underlying data distribution.} \label{fig:gan_final_samples} \end{figure} \textbf{Mixture of Gaussians.} We noted in Section~\ref{sec:empirical} that we repeated our experiment training a generative adversarial network to learn a mixture of Gaussians 10 times and observed that for each run of the experiment our training algorithm recovered all modes of the distribution. We now show those results in Figure~\ref{fig:gan_final_samples}. In particular, in Figure~\ref{fig:gan_real_app} we show the real data distribution and in Figures~\ref{fig:samples_final1}--\ref{fig:samples_final10} we show the final generated distribution from 10 separate runs of the training procedure after 150k generator updates. Notably, we observe that each run of the training algorithm is able to generate a distribution that closely resembles the underlying data distribution, showing the stability and robustness of our training method. We also performed an experiment on the mixture of Gaussian problem in which the discriminator algorithm was the Adam optimization procedure with parameters $(\beta_1, \beta_2)=(0.99, 0.999)$ and learning rate $\eta_2=0.004$ and the generator learning rate was $\eta_1=0.05$. The rest of the experimental setup remained the same. We ran this experiment 10 times and observed that for 7 out of the 10 runs of the final generated distribution was reasonably close to the real data distribution, while for 3 out of the 10 runs the generator did not learn the proper distribution. This is to say that we found the training algorithm was not as stable when the discriminator used Adam versus normal gradient ascent. The final generated distribution from the 7 of 10 runs with reasonable distributions are shown in Figure~\ref{fig:adam_gan_final_samples}. \begin{figure}[t!] \centering \begin{minipage}{.9\textwidth} \centering \begin{minipage}{.2\textwidth} \subfloat[][Real Data]{\includegraphics[width=.9\textwidth]{Figs/samples_real_gaussian.png}\label{fig:adam_gan_real_app}} \end{minipage}% \begin{minipage}{.45\textwidth} \subfloat[][]{\includegraphics[width=.33\textwidth]{Figs/adam_higher_gan/final_seeds/samples_final_1.png}\label{fig:adam_samples_final1}} \subfloat[][]{\includegraphics[width=.33\textwidth]{Figs/adam_higher_gan/final_seeds/samples_final_4.png}\label{fig:adam_samples_final4}} \subfloat[][]{\includegraphics[width=.33\textwidth]{Figs/adam_higher_gan/final_seeds/samples_final_6.png}\label{fig:adam_samples_final6}} \subfloat[][]{\includegraphics[width=.33\textwidth]{Figs/adam_higher_gan/final_seeds/samples_final_7.png}\label{fig:adam_samples_final7}} \subfloat[][]{\includegraphics[width=.33\textwidth]{Figs/adam_higher_gan/final_seeds/samples_final_8.png}\label{fig:adam_samples_final8}} \subfloat[][]{\includegraphics[width=.33\textwidth]{Figs/adam_higher_gan/final_seeds/samples_final_9.png}\label{fig:adam_samples_final9}} \end{minipage}% \begin{minipage}{.155\textwidth} \subfloat[][]{\includegraphics[width=\textwidth]{Figs/adam_higher_gan/final_seeds/samples_final_10.png}\label{fig:adam_samples_final10}} \end{minipage} \end{minipage} \caption{\textbf{Mixture of Gaussians}: Figure~\ref{fig:adam_gan_real_app} shows the real data distribution and Figures~\ref{fig:adam_samples_final1}--\ref{fig:adam_samples_final10} show the final generated distributions after 150k generator updates from the 7 out of 10 separate runs of the training procedure using Adam optimization for the discriminator that produced reasonable distributions.} \label{fig:adam_gan_final_samples} \end{figure} \textbf{Adversarial Training.} We now provide some further background on the adversarial training experiment and additional results. It is now well-documented that the effectiveness of deep learning classification models can be vulnerable to adversarial attacks that perturb the input data (see, e.g., \cite{biggio2013evasion, szegedy2013intriguing, kurakin2017adversarial, madry2017towards}). A common approach toward remedying this vulnerability is by training the classification model against adversarial perturbations. Recall from Section~\ref{sec:empirical} that given a data distribution $\mathcal{D}$ over pairs of examples $x\in \mathbb{R}^d$ and labels $y\in [k]$, parameters $\theta$ of a neural network, a set $\mathcal{S}\subset \mathbb{R}^d$ of allowable adversarial perturbations, and a loss function $\ell(\cdot, \cdot, \cdot)$ dependent on the network parameters and the data, adversarial training amounts to considering a minmax optimization problem of the form $\min_{\theta}\mathbb{E}_{(x, y)\sim \mathcal{D}}[\max_{\delta\in \mathcal{S}}\ell(\theta, x+\delta, y)]$. \begin{figure}[t!] \centering \includegraphics[width=.9\textwidth]{Figs/attack_results_all.png} \includegraphics[width=.55\textwidth]{Figs/adversarial_legend.png} \caption{\textbf{Adversarial Training}: Test accuracy during the course of training against gradient ascent attacks with a fixed learning rate of $\eta_2=4$ and the number of steps $T\in \{5, 10, 20, 40\}$.} \label{fig:attack1_app} \end{figure} \begin{figure}[t!] \centering \includegraphics[width=.9\textwidth]{Figs/budget_attack_results_all.png} \includegraphics[width=.55\textwidth]{Figs/adversarial_legend.png} \caption{\textbf{Adversarial Training}: Test accuracy during the course of training against gradient ascent attacks with a fixed attack budget of $T\eta_2 = 40$ where $T$ is the number of attack steps and $\eta_2$ is the learning rate (LR).} \label{fig:attack_app} \end{figure} \begin{figure}[t!] \centering \includegraphics[width=.9\textwidth]{Figs/adam_budget_attack_results_all.png} \includegraphics[width=.55\textwidth]{Figs/adversarial_legend.png} \caption{\textbf{Adversarial Training}: Test accuracy during the course of training against Adam optimization attacks with a fixed attack budget of $T\eta_2 = 0.04$ where $T$ is the number of attack steps and $\eta_2$ is the learning rate (LR).} \label{fig:attack_app_adam} \end{figure} A typical approach to solving this problem is an alternating optimization approach~\cite{madry2017towards}. In particular, each time a batch of data is drawn from the distribution, $T$-steps of projected gradient ascent are performed by ascending along the sign of the gradient of the loss function with respect to the data and projecting back onto the set of allowable perturbations, then the parameters of the neural network are updated by descending along the gradient of the loss function with the perturbed examples. The experimental setup we consider is analogous but the inner maximization loop performs $T$-steps of regular gradient ascent (not using the sign of the gradient and without projections). \begin{figure}[t!] \centering \subfloat[][]{\includegraphics[width=.4\textwidth]{Figs/grad_norm_small.png}\label{fig:grad_norm1}} \subfloat[][]{\includegraphics[width=.4\textwidth]{Figs/grad_norm_small_2.png}\label{fig:grad_norm2}} \caption{\textbf{Adversarial Training}: $\|\nabla f(\theta, \mathcal{A}(\theta))\|$ as a function of the number of steps $T$ taken by the gradient ascent algorithm $\mathcal{A}$ evaluated at multiple points in the training procedure. Figure~\ref{fig:grad_norm1} corresponds to using $\eta_2=4$ in the gradient ascent procedure and Figure~\ref{fig:grad_norm2} corresponds to using $\eta_2=1$ in the gradient ascent procedure.} \label{fig:grad_norm_app} \end{figure} \begin{table}[t!] \begin{center} \begin{tabular}{|c c|} \hline Layer Type & Shape \\ \hline\hline Convolution + ReLU & $5\times 5\times 20$ \\ \hline Max Pooling & $2\times 2$ \\ \hline Convolution + ReLU & $5\times 5\times 20$ \\ \hline Max Pooling & $2\times 2$ \\ \hline Fully Connected + ReLU & $800$ \\ \hline Fully Connected + ReLU& $500$ \\ \hline Softmax & $10$ \\ \hline \end{tabular} \end{center} \caption{Convolutional neural network model for the adversarial training experiments.} \label{table:cnn} \end{table} For the adversarial training experiment considered in Section~\ref{sec:empirical}, we also evaluated the trained models against various other attacks. Recall that the models were training using $T=10$ steps of gradient ascent in the inner optimization loop with a learning rate of $\eta_2 =4$. To begin, we evaluated the trained models against gradient ascent attacks with a fixed learning rate of $\eta_2=4$ and a number of steps $T\in \{5, 10, 20, 40\}$. We also evaluated the trained models against gradient ascent attacks with a fixed budget of $T\eta_2=40$ and various choices of $T$ and $\eta_2$. These results are presented in Figure~\ref{fig:attack_app}. Finally, we evaluated the trained models against attacks using the Adam optimization method with a fixed budget of $T\eta_2=0.04$ and various choices of $T$ and $\eta_2$. These results are presented in Figure~\ref{fig:attack_app_adam}. Notably, we see that our algorithm outperforms the baselines and similar conclusions can be drawn as from the experiments for adversarial training presented in Section~\ref{sec:empirical}. The additional experiments highlight that our method of adversarial training is robust against attacks that the algorithm did not use in training when of comparable computational power and also that it improves robustness against attacks of greater computational power than used during training. In Section~\ref{sec:empirical}, we showed the results of evaluating the gradient norms $\|\nabla f(\theta, \mathcal{A}(\theta))\|$ as a function of the number of gradient ascent steps $T$ in the adversary algorithm $\mathcal{A}$ and observed that it grows much slower than exponentially. Here we provide more details on the setup. We took a run of our algorithm trained with the setup described in Section~\ref{sec:empirical} and retrieved the models that were saved after 25, 50, 75, and 100 training epochs. For each model, we then sampled 100 minibatches of data and for each minibatch performed $T\in \{20,30,40,50,60,70,80,90, 100\}$ steps of gradient ascent with learning rate $\eta_2=4$ (the learning rate from training) and then computed the norm of the gradient $\nabla f(\theta, \mathcal{A}(\theta))$ where $\mathcal{A}$ corresponds to the gradient ascent procedure with the given number of steps and learning rate. In Figure~\ref{fig:grad_norm}, which is reproduced here in Figure~\ref{fig:grad_norm1}, the mean of the norm of the gradients over the sampled minibatches are shown with the shaded window indicating a standard deviation around the mean. We also repeated this procedure using $\eta_2=1$ and show the results in Figure~\ref{fig:grad_norm2} from which similar conclusions can be drawn. Finally, we provide details on the convolutional neural network model for the adversarial training experiments. In particular, this model is exactly the same as considered in~\cite{nouiehed2019solving} and we reproduce it in Table~\ref{table:cnn}. \textbf{Experimental Details.} For the experiments with neural network models we used two Nvidia GeForce GTX 1080 Ti GPU and the PyTorch higher library\cite{deleu2019torchmeta} to compute $\nabla f(\theta, \mathcal{A}(\theta))$. In total, running all the experiments in the paper takes about half of a day with this computational setup. The code for the experiments is available at \url{https://github.com/fiezt/minmax-opt-smooth-adversary}. \section{Proofs of Results in Section~\ref{sec:conv-sgd}} \label{app:sgd} In order to prove convergence of this algorithm, we first recall the following result from~\cite{davis2018stochastic}. \begin{theorem}[Corollary 2.2 from~\cite{davis2018stochastic}]\label{thm:sgd-dima} Suppose $g(\cdot)$ is $L$-weakly convex, and $\mathbb{E}_{z_1,\cdots,z_k}\left[\norm{\widehat{\nabla} g(x)}^2\right] \leq G^2$. Then, the output $\bar{x}$ of Algorithm~\ref{algo:sgd} with stepsize $\eta = \frac{\gamma}{\sqrt{S+1}}$ satisfies: \begin{align*} \mathbb{E}\left[\norm{\nabla g_{\frac{1}{2L}}(\bar{x})}^2\right] \leq 2 \cdot \frac{\left(g_{\frac{1}{2L}}(x_0)-\min_x g(x)\right) + L G^2 \gamma^2}{\gamma \sqrt{S+1}}. \end{align*} \end{theorem} \begin{proof}[Proof of Theorem~\ref{thm:main-sgd}] Lemmas~\ref{lem:smooth-func} and~\ref{lem:argmax-weakconvex} tell us that $g(x)$ is $\widehat{L}$-weakly convex and for any choice of $z$, the stochastic subgradient $\widehat{\nabla} g(x)$ is bounded in norm by $\widehat{G}$. Consequently, Theorem~\ref{thm:sgd-dima} with the stated choice of $S$ proves Theorem~\ref{thm:main-sgd}. \end{proof} \begin{algorithm}[t] \DontPrintSemicolon \KwIn{point $x$, stochastic subgradient oracle for function $g$, error $\epsilon$, failure probability $\delta$} Find $\vect{\widetilde{x}}$ such that $g(\vect{\widetilde{x}}) + {L}{} \norm{x-\vect{\widetilde{x}}}^2 \leq \left(\min_{x'} g(x') + L \norm{x-x'}^2\right) + \frac{\epsilon^2}{4L}$ using \cite[Algorithm 1]{harvey2019simple}. \textbf{return} $2L{\left(x-\vect{\widetilde{x}}\right)}{}$. \caption{Estimating Moreau envelope's gradient for postprocessing} \label{algo:postprocessing} \end{algorithm} \begin{proposition}\label{prop:postproc} Given a point $x$, an $L$-weakly convex function $g$ and a $G$-norm bounded and a stochastic subgradient oracle to $g$ (i.e., given any point $x'$, which returns a stochastic vector $u$ such that $\mathbb{E}[u] \in \partial g(x')$ and $\norm{u} \leq G$), with probability at least $1-\delta$, Algorithm~\ref{algo:postprocessing} returns a vector $u$ satisfying $\norm{u - \nabla g_{\lambda}(x)} \leq \epsilon$ with at most $\order{\frac{G^2 \log \frac{1}{\delta}}{\epsilon^2}}$ queries to the stochastic subgradient oracle of $g$. \end{proposition} \begin{proof}[Proof of Proposition~\ref{prop:postproc}] Let $\Phi_{\frac{1}{2L}}(x',x) \mathrel{\mathop:}= g(x') + L \norm{x-x'}^2$. Recall the notation of Lemma~\ref{lem:moreau-properties} $\widehat{x}_{\frac{1}{2L}}(x) \mathrel{\mathop:}= \mathop{\mathrm{argmin}}_{x'} \Phi_{\frac{1}{2L}}(x',x)$ and $g_{\lambda}(x) = \min_{x'} \Phi_{\frac{1}{2L}}(x',x)$. The proof of Lemma~\ref{lem:moreau-properties} tells us that $\nabla g_{\frac{1}{2L}}(x) = \frac{x-\widehat{x}_{\frac{1}{2L}}(x)}{\lambda}$ and also that $\norm{\widehat{x}_{\frac{1}{2L}}(x)-x} \leq \frac{G}{2L}$. Since $\Phi_{\frac{1}{2L}}(\cdot,x)$ is a $L$-strongly convex and $G$ Lipschitz function in the domain $\set{x': \norm{\widehat{x}_{\frac{1}{2L}}(x)-x} \leq \frac{G}{2L}}$,~\cite[Theorem 3.1]{harvey2019simple} tells us that we can use SGD with $\order{\frac{G^2 \log\frac{1}{\delta}}{L \widetilde{\epsilon}}}$ stochastic gradient oracle queries to implement Step 1 of Algorithm~\ref{algo:postprocessing} with success probability at least $1-\delta$, where $\widetilde{\epsilon} \mathrel{\mathop:}= \frac{\epsilon^2}{4L}$. Simplifying this expression gives us a stochastic gradient oracle complexity of $\order{\frac{G^2 \log \frac{1}{\delta}}{\epsilon^2}}$. \end{proof} \section{Proofs of Results in Section~\ref{sec:prox}} \label{app:prox} \begin{proof}[Proof of Theorem~\ref{thm:prox}] Letting $h(x,\lambda) \mathrel{\mathop:}= \sum_{i\in[k]} \lambda_i g_i(x)$, we note that $\norm{\nabla_{xx} h(x,\lambda)} = \norm{\sum_{i\in[k]} \lambda_i \nabla^2 g_i(x)} \leq L(1+G')^2 + GL'$, where we used Lemma~\ref{lem:smooth-func} and the fact that $\sum_i \abs{\lambda_i} \leq 1$. On the other hand, again from Lemma~\ref{lem:smooth-func}, $\norm{\nabla_{x\lambda} h(x,\lambda) = \norm{\sum_{i\in[k]} \nabla g_i(x)}} \leq k G(1+G')$. Since $\nabla_{\lambda \lambda} h(x,\lambda)=0$, we can conclude that $h$ is an $\widehat{L}$-gradient Lipschitz function with $\widehat{L} \mathrel{\mathop:}= L(1+G')^2 + GL' + k G(1+G')$. Consequently, $g(x) = \max_{{\lambda \in S}}h(x,\lambda)$, where $S \mathrel{\mathop:}= \set{\lambda \in \mathbb{R}^k : \lambda_i \geq 0, \sum_{i\in[k]} \lambda_i = 1}$, is $\widehat{L}$-weakly convex and the Moreau envelope $g_{\frac{1}{2\widehat{L}}}$ is well defined. Denote $\widehat{g}_(x,x_s) \mathrel{\mathop:}= \max_{i\in[k]} g_i(x) + \widehat{L} \norm{x-x_s}^2$. We now divide the analysis of each of iteration of Algorithm~\ref{algo:prox} into two cases. \textbf{Case I, $\widehat{g}_(x_{s+1},x_s) \leq \max_{i \in [k]} g_i(x_s) - 3 \widehat{\epsilon}/4$}: Since $\max_{i \in [k]} g_i(x_{s+1}) \leq \widehat{g}_(x_{s+1},x_s) \leq \max_{i \in [k]} g_i(x_s) - 3 \widehat{\epsilon}/4$, we see that in this case $g(x_s)$ decreases monotonically by at least $3\widehat{\epsilon}/4$ in each iteration. Since by Assumption~\ref{ass:func-smooth}, $g$ is bounded by $B$ in magnitude, and the termination condition in Step $4$ guarantees monotonic decrease in every iteration, there can only be at most $2B/(3\widehat{\epsilon}/4)=8B/\widehat{\epsilon}$ such iterations in Case I. \textbf{Case II, $\widehat{g}_(x_{s+1},x_s) \geq \max_{i \in [k]} g_i(x_s) - 3 \widehat{\epsilon}/4$}: In this case, we claim that $x_s$ is an $\epsilon$-FOSP of $g = \max_{i\in[k]} g_i(x)$. To see this, we first note that \begin{align}\label{eq:less-decrease-smooth} g(x_s) - 3\widehat{\epsilon}/4 \leq \widehat{g}_(x_{s+1},x_s) \leq (\min_x g(x) + \widehat{L} \norm{x-x_s}^2) + \widehat{\epsilon}/4 \;\; \implies \;\; g(x_s) < \min_x \widehat{g}_(x; x_s) + {\widehat{\epsilon}}. \end{align} Let $x^*_s \mathrel{\mathop:}= \arg\min_x \widehat{g}_(x; x_k)$. Since $g$ is $\widehat{L}$-gradient Lipschitz, we note that $\widehat{g}_(\cdot; x_s)$ is $\widehat{L}$-strongly convex. We now use this to prove that $x_s$ is close to $x_s^*$:{\small \begin{align} \widehat{g}_(x^*_s;x_s) + \frac{\widehat{L}}2 \|x_s-x^*_s\|^2 \; \leq \; \widehat{g}_(x_{s};x_s) \; =\; f(x_s) \; \overset{(a)}< \; \widehat{g}_(x^*_{k};x_s) + \widehat{\epsilon} \implies\|x_s-x^*_s\| < \sqrt{\frac{2\widehat{\epsilon}}{\widehat{L}}} \label{eq:moreau-ball-ub-smooth} \end{align}} where $(a)$ uses \eqref{eq:less-decrease-smooth}. Now consider any $\widehat{x}$, such that $4\sqrt{\widehat{\epsilon}/L} \leq \| \widehat{x} - x_s\|$. Then, \begin{align} g(\widehat{x}) + L \|\widehat{x} - x_s\|^2 &= \max_{i \in [k]} g_i(\widehat{x}) + L \|\widehat{x} - x_s\|^2 = \widehat{g}_(\widehat{x}; x_s) \overset{(a)}= \widehat{g}_(x_s^*; x_s) + \frac{L}2 \|\widehat{x} - x^*_s\|^2 \nonumber \\ &\overset{(b)}\geq f(x_s) - \widehat{\epsilon} + \frac{\widehat{L}}2 (\|\widehat{x} - x_s\| - \|x_s - x^*_s\|)^2 \overset{(c)}\geq f(x_s) + \widehat{\epsilon}, \label{eq:moreau-ball-lb-smooth} \end{align} where $(a)$ uses uses $\widehat{L}$-strong convexity of $\widehat{g}_(\cdot; x_s)$ at its minimizer $x^*_s$, $(b)$ uses \eqref{eq:less-decrease-smooth}, and $(b)$ and $(c)$ use triangle inequality, \eqref{eq:moreau-ball-ub-smooth} and $4\sqrt{\widehat{\epsilon}/\widehat{L}} \leq \| \widehat{x} - x_s\|$. Now consider the Moreau envelope, $g_{\frac1{2\widehat{L}}}(x) = \min_{x' } \phi_{\frac1{2\widehat{L}}, x}(x')$ where $\phi_{\frac{1}{2\widehat{L}},x}(x') = g(x') + L \|x - x'\|^2$. Then, we can see that $\phi_{\frac1{2\widehat{L}}, x_s}(x')$ achieves its minimum in the ball $\{x' \,|\, \|x' - x_s\| \leq 4\sqrt{\widehat{\epsilon}/\widehat{L}} \}$ by \eqref{eq:moreau-ball-lb-smooth} and Lemma \ref{lem:moreau-properties}(a). Then, with Lemma \ref{lem:moreau-properties}(b,c) and $\widehat{\epsilon} = \frac{\varepsilon^2}{64\,\widehat{L}}$, we get that, \begin{align} \| \nabla g_{\frac1{2\widehat{L}}}(x_s) \| \leq (2\widehat{L}) \| x_s - \hat{x}_{\frac1{2\widehat{L}}}(x_s) \| = 8 \sqrt{\widehat{L} \widehat{\epsilon}} = \varepsilon, \end{align} i.e., $x_s$ is an $\varepsilon$-FOSP of $g$. By combining the above two cases, we establish that ${\frac{8B}{3\widehat{\epsilon}}}$ ``outer'' iterations ensure convergence to a $\varepsilon$-FOSP. We now compute the gradient call complexity of each of these ``outer" iterations, where we have two options for implementing Step $3$ of Algorithm~\ref{algo:prox}. Note that this step corresponds to solving $\min_x \max_{\lambda \in S} h(x,\lambda)$ up to an accuracy of $\widehat{\epsilon}/4$. \textbf{Option I},~\cite[Algorithm 2]{thekumparampil2019efficient}: Since the minimax optimization problem here is $\widehat{L}$-strongly-convex--concave and $2\widehat{L}$-gradient Lipschitz,~\cite[Theorem 1]{thekumparampil2019efficient} tells us that this requires at most $m$ gradient calls for each $g_i$ where, \begin{align} \frac{6(2\widehat{L})^2 }{L m^2} \leq \frac{\widehat{\epsilon}}{4} = \frac{\varepsilon^2}{2^8 \widehat{L}} \;\implies\; O\bigg(\frac{\widehat{L} }{\varepsilon}\bigg) \leq m \end{align} Therefore the number of gradient computations required for each iteration of inner problem is $ O\Big(\frac{\widehat{L} }{\epsilon} \log^2 \Big(\frac{1}{\varepsilon} \Big) \Big)$. \textbf{Option II, Cutting plane method}~\cite{lee2015faster}: Let us consider $u(\lambda) \mathrel{\mathop:}= \min_x h(x,\lambda) + \widehat{L} \norm{x - x_s}^2$, which is a $\widehat{L}$-Lipschitz, concave function of $\lambda$.~\cite{lee2015faster} tells us that we can use cutting plane algorithms to obtain $\widehat{\lambda}$ satisfying $u(\widehat{\lambda}) \geq \max_{{\lambda \in S}}u(\lambda) - \widetilde{\epsilon}$ using $\order{k \log \frac{k\widehat{L}}{\widetilde{\epsilon}}}$ gradient queries to $u$ and $\mathrm{poly}(k\log\frac{\widehat{L}}{\widetilde{\epsilon}})$ computation. The gradient of $u$ is given by $\nabla u(\lambda) = \nabla_\lambda h(x^*(\lambda),\lambda)$, where $x^*(\lambda) \mathrel{\mathop:}= \mathop{\mathrm{argmin}}_x h(x,\lambda) + \widehat{L} \norm{x - x_s}^2$. Since $h(x,\lambda) + \widehat{L} \norm{x - x_s}^2$ is a $3\widehat{L}$-smooth and $\widehat{L}$-strongly convex function in $x$, $x^*(\lambda)$ can be computed up to $\widetilde{\epsilon}$ error using gradient descent in $\order{\log \frac{\widehat{L}}{\widetilde{\epsilon}}}$ iterations. If we choose $\widetilde{\epsilon} = \widehat{\epsilon}^2/\mathrm{poly}(k,\widehat{L}/\mu)$, then Proposition~\ref{prop:dual-primal} tells us that $x^*(\lambdahat)$ satisfies the requirements of Step (3) of Algorithm~\ref{algo:prox} and the total number of gradient calls to each $g_i$ is at most $\order{\mathrm{poly}(k) \log \frac{\widehat{L}}{\epsilon}}$ in each outer iteration of Algorithm~\ref{algo:prox}. \end{proof} \begin{proposition}\label{prop:dual-primal} Suppose $h:\mathbb{R}^{d_1} \times \mathcal{U} \rightarrow \mathbb{R}$ be such that $h(\cdot,\lambda)$ is $\mu$-strongly convex for every $\lambda \in \mathcal{U}$, $h(x,\cdot)$ is concave for every $x \in \mathbb{R}^{d_1}$ and $h$ is $L$-gradient Lipschitz. Let $\widehat{\lambda}$ be such that $\min_x h(x,\widehat{\lambda}) \geq \max_\lambda \min_x h(x,\lambda) - \epsilon$ and let $x^*(\lambdahat) \mathrel{\mathop:}= \mathop{\mathrm{argmin}}_x h(x,\widehat{\lambda})$. Then, we have $\max_\lambda h(x^*(\lambdahat),\lambda) \leq \min_x \max_\lambda h(x,\lambda) + c \left(\frac{L}{\mu} \cdot \epsilon + \frac{LD_\mathcal{U}}{\sqrt{\mu}} \cdot \sqrt{\epsilon}\right)$, where $D_\mathcal{U} = \max_{\lambda_1,\lambda_2 \in \mathcal{U}} \norm{\lambda_1 - \lambda_2}$ is the diameter of $\mathcal{U}$. \end{proposition} \begin{proof}[Proof of Proposition~\ref{prop:dual-primal}] From the hypothesis, we have: \begin{align*} \epsilon \geq h(x^*,\lambda^*) - h(x^*(\lambdahat),\widehat{\lambda}) \geq h(x^*,\widehat{\lambda}) - h(x^*(\lambdahat),\widehat{\lambda}) \geq \frac{\mu}{2} \norm{x^* - x^*(\lambdahat)}^2, \end{align*} where $(x^*,\lambda^*)$ is the Nash equilibrium and the second step follows from the fact that $\lambda^* = \mathop{\mathrm{argmax}}_{\lambda}h(x^*,\lambda)$ and the third step follows from the fact that $x^*(\lambdahat) = \mathop{\mathrm{argmin}}_x h(x,\widehat{\lambda})$. Consequently, $\norm{x^* - x^*(\lambdahat)} \leq \sqrt{2\epsilon/\mu}$. Let $\bar{\lambda} \mathrel{\mathop:}= \mathop{\mathrm{argmax}}_{\lambda} h(x^*(\lambdahat),\lambda)$. We now have that: \begin{align*} \max_\lambda h(x^*(\lambdahat),\lambda) - \max_\lambda \min_x h(x,\lambda) &= h(x^*(\lambdahat),\bar{\lambda}) - h(x^*,\lambda^*) \\ &= h(x^*(\lambdahat),\bar{\lambda}) - h(x^*(\lambdahat),\lambda^*) + h(x^*(\lambdahat),\lambda^*)- h(x^*,\lambda^*) \\ &\overset{(\zeta_1)}{\leq} \iprod{\nabla_\lambda h(x^*(\lambdahat),\lambda^*)}{\bar{\lambda} - \lambda^*} + \frac{L}{2}\norm{x^*(\lambdahat) - x^*}^2 \\ &\overset{(\zeta_2)}{\leq} \norm{\nabla_\lambda h(x^*(\lambdahat),\lambda^*)}\norm{\bar{\lambda} - \lambda^*} + \frac{L\epsilon}{\mu} \\ &\overset{(\zeta_3)}{\leq} \left(\norm{\nabla_\lambda h(x^*,\lambda^*)} + L \norm{x^*(\lambdahat)-x^*}\right) \mathcal{D}_\mathcal{U} + \frac{L\epsilon}{\mu} \\ &\leq \frac{L \mathcal{D}_\mathcal{U} \sqrt{2\epsilon}}{\sqrt{\mu}} + \frac{L\epsilon}{\mu}, \end{align*} where $(\zeta_1)$ follows from the fact that $h(x^*(\lambdahat),\cdot)$ is concave and $x^* = \mathop{\mathrm{argmin}}_x h(x,\lambda^*)$, $(\zeta_2)$ follows from the bound $\norm{x^* - x^*(\lambdahat)} \leq \sqrt{2\epsilon/\mu}$, $(\zeta_3)$ follows from the $L$-gradient Lipschitz property of $h$, and the last step follows from the fact that $\nabla_\lambda h(x^*,\lambda^*)=0$. This proves the proposition. \end{proof} \section{Introduction} This paper considers minimax optimization $\min_x \max_y f(x,y)$ in the context of two-player zero-sum games, where the min-player (controlling $x$) tries to minimize objective $f$ assuming a worst-case opponent (controlling $y$) that acts so as to maximize it. Minimax optimization naturally arises in a variety of important machine learning paradigms, with the most prominent examples being the training of generative adversarial networks (GANs)~\cite{goodfellow2014generative} and adversarially robust models~\cite{madry2017towards}. These applications commonly engage deep neural networks with various techniques such as convolution, recurrent layers, and batch normalization. As a result, the objective function $f$ is highly \emph{nonconvex} in $x$ and \emph{nonconcave} in $y$. Theoretically, minimax optimization has been extensively studied starting from the seminal work of von Neumann~\cite{neumann1928theorie}, with many efficient algorithms proposed for solving it~\cite{robinson1951iterative,korpelevich1976extragradient,nemirovski2004prox}. A majority of these classical results have been focused on \emph{convex-concave} functions, and heavily rely on the minimax theorem, i.e., $\min_x \max_y f(x,y) = \max_y \min_x f(x,y)$, which no longer holds beyond the convex-concave setting. Recent line of works~\cite{lin2020gradient,nouiehed2019solving,thekumparampil2019efficient,lin2020near,ostrovskii2020efficient} address the \emph{nonconvex-concave} setting where $f$ is nonconvex in $x$ but concave in $y$ by proposing meaningful optimality notions and designing computationally efficient algorithms to find such points. A crucial property heavily exploited in this setting is that the inner maximization over $y$ given a fixed $x$ can be computed efficiently, which unfortunately does not extend to the \emph{nonconvex-nonconcave} setting. Consequently, nonconvex-nonconcave optimization remains challenging, and many fundamental issues persist: it remains open what is an appropriate notion of optimality that can be computed efficiently; it is also unsettled on how to eliminate the cyclic or diverging behavior of existing algorithms. Practitioners often use simple and popular algorithms such as gradient descent ascent (GDA) and other variants for solving these challenging optimization problems. While these algorithm seem to perform well in some cases of adversarial training, they are highly unstable in other scenarios such as training GANs. Indeed the instability of GDA and other empirically popular methods is not surprising since they are known to not converge even in very simple settings~\cite{daskalakis2018limit,bailey2020finite}. This current state of affairs strongly motivates the need to understand nonconvex-nonconcave minimax optimization more thoroughly and to design better algorithms for solving them. \textbf{This work} considers the challenging nonconvex-nonconcave setting. Our framework sprouts from the practical consideration that under a computational budget, the max-player can not fully maximize $f(x,\cdot)$ since nonconcave maximization is NP-hard in general. Instead, we assume that the max-player has a toolkit of multiple (potentially randomized) algorithms $\mathcal{A}_1,\mathcal{A}_2,\cdots,\mathcal{A}_k$ in an attempt to solve the maximization problem given fixed $x$, and picks the best solution among these algorithms. This motivates us to study the surrogate of the minimax optimization problem as \begin{align}\label{eqn:minimax-reform} \textstyle \min_x \max_{i \in [k]} f(x,\mathcal{A}_i(x)) = \min_x \max_{\lambda \in \Delta_k} \sum_{i=1}^{k} \lambda_i f(x,\mathcal{A}_i(x)), \end{align} where $\Delta_k$ denotes the $k$-dimensional simplex, and $\mathcal{A}_i(x)$ denotes the output of algorithm $\mathcal{A}_i$ for a given $x$. When both the objective function $f$ and the algorithms $\{\mathcal{A}_i\}_{i=1}^k$ are smooth (defined formally in Section~\ref{sec:prelims}), we can show that \eqref{eqn:minimax-reform} becomes a \emph{smooth nonconvex-concave} minimax optimization problem, where recent advances can be leveraged in solving such problems. In particular, given the smooth algorithms deployed by the adversary (i.e. the max-player), this paper proposes two algorithms for solving problems in \eqref{eqn:minimax-reform}. The first algorithm is based on stochastic gradient descent (SGD), which is guaranteed to find an appropriate notion of ``$\epsilon$-approximate stationary point'' in $\mathcal{O}(\epsilon^{-4})$ gradient computations. The second algorithm is based on proximal algorithm, in the case of \emph{deterministic} adversarial algorithms $\{\mathcal{A}_i\}_{i=1}^k$, this algorithm has an improved gradient complexity $\mathcal{O}(\epsilon^{-3})$ or $\tilde{\mathcal{O}}(\mathrm{poly}(k)/\epsilon^2)$ depending on the choice of subroutine within the algorithm. All our algorithms are guaranteed to make monotonic progress, thus having no limit cycles. Our second set of results show that, many popular algorithms deployed by the adversary such as multi-step stochastic gradient ascent, and multi-step stochastic Nesterov's accelerated gradient ascent are in fact smooth. Therefore, our framework readily applies to those settings in practice. Finally, we present complementing experimental results using our theoretical framework and algorithms for generative adversarial network problems and adversarial training. The results highlight the benefits of our approach in terms of the stable monotonic improvement during training and also underscore the importance of optimizing through the algorithm of the adversary. \section{Proof of results in Section~\ref{sec:prelims}} \begin{proof}[Proof of Lemma~\ref{lem:smooth-func}] For any fixed $z$, we note that $\mathcal{A}(\cdot,z)$ is a deterministic algorithm. Consequently, it suffices to prove the lemma for a deterministic algorithm $\mathcal{A}(\cdot)$. By chain rule, the derivative of $f(x,\mathcal{A}(x))$ is given by: \begin{equation} \nabla f(x,\mathcal{A}(x)) = \nabla_x f(x,\mathcal{A}(x)) + D\mathcal{A}(x) \cdot \nabla_y f(x,\mathcal{A}(x)), \label{eq:totalderiv} \end{equation} where $D\mathcal{A}(x) \in \mathbb{R}^{d_1 \times d_2}$ is the derivative of $\mathcal{A}(\cdot): \mathbb{R}^{d_1} \rightarrow \mathbb{R}^{d_2}$ at $x$ and $\nabla_x f(x,\mathcal{A}(x))$ and $\nabla_y f(x,\mathcal{A}(x))$ denote the partial derivatives of $f$ with respect to the first and second variables respectively at $(x,\mathcal{A}(x))$. An easy computation shows that \begin{align*} \norm{\nabla f(x,\mathcal{A}(x))} &\leq \norm{\nabla_x f(x,\mathcal{A}(x))} + \norm{D\mathcal{A}(x)} \cdot \norm{\nabla_y f(x,\mathcal{A}(x))} \\ &\leq G + G' \cdot G = (1+G')G. \end{align*} This shows that $f(x,\mathcal{A}(x))$ is $(1+G')G$-Lipschitz. Similarly, we have: \begin{align*} &\norm{\nabla f(x_1,\mathcal{A}(x_1)) - \nabla f(x_2,\mathcal{A}(x_2))} \\ & \leq \norm{\nabla_x f(x_1,\mathcal{A}(x_1)) - \nabla_x f(x_2,\mathcal{A}(x_2))} + \norm{D\mathcal{A}(x_1) \nabla_y f(x_1,\mathcal{A}(x_1)) - D\mathcal{A}(x_2) \nabla_y f(x_2,\mathcal{A}(x_2))}. \end{align*} For the first term, we have: \begin{align*} &\norm{\nabla_x f(x_1,\mathcal{A}(x_1)) - \nabla_x f(x_2,\mathcal{A}(x_2))} \\ &\leq \norm{\nabla_x f(x_1,\mathcal{A}(x_1)) - \nabla_x f(x_2,\mathcal{A}(x_1))} + \norm{\nabla_x f(x_2,\mathcal{A}(x_1)) - \nabla_x f(x_2,\mathcal{A}(x_2))} \\ &\leq L \left(\norm{x_1 - x_2} + \norm{\mathcal{A}(x_1)-\mathcal{A}(x_2)}\right) \leq L \left(1+G'\right) \norm{x_1-x_2}. \end{align*} Similarly, for the second term we have: \begin{align*} &\norm{D\mathcal{A}(x_1) \nabla_y f(x_1,\mathcal{A}(x_1)) - D\mathcal{A}(x_2) \nabla_y f(x_2,\mathcal{A}(x_2))} \\ &\leq \norm{D\mathcal{A}(x_1)} \norm{\nabla_y f(x_1,\mathcal{A}(x_1)) - \nabla_y f(x_2,\mathcal{A}(x_2))} + \norm{\nabla_y f(x_2,\mathcal{A}(x_2))} \norm{D\mathcal{A}(x_2) - D\mathcal{A}(x_1)} \\ &\leq \left(LG'(1+G') + GL'\right) \norm{x_1-x_2}. \end{align*} This proves the lemma. \end{proof} \begin{proof}[Proof of Lemma~\ref{lem:argmax-weakconvex}] Given any $x$ and $y$, and any $\lambda$ such that $\lambda_j \geq 0$ and $\sum_{j\in S(x)}\lambda_j=1$, we have: \begin{align*} g(y) &= \max_{j \in [k]} g_j(y) \geq \sum_{j \in S(x)} \lambda_j g_j(y) \geq \sum_{j \in S(x)} \lambda_j \left(g_j(x) + \iprod{\nabla g_j(x)}{y-x} - \frac{1}{2L} \norm{x-y}^2\right) \\ &= g(x) + \iprod{\sum_{j \in S(x)} \lambda_j \nabla g_j(x)}{y-x} - \frac{1}{2L} \norm{x-y}^2 , \end{align*} proving the lemma. \end{proof} \begin{proof}[Proof of Lemma~\ref{lem:moreau-properties}] We re-write $f_{\lambda}(x)$ as minimum value of a $(\frac1{\lambda} -L)$-strong convex function $\phi_{\lambda, x}$, as $g$ is $L$-weakly convex (Definition~\ref{def:weak-convex}) and $\frac1{2\lambda} \|x-x'\|^2$ is differentiable and $\frac1{\lambda}$-strongly convex, \begin{align} \label{eq:moreau-reformula} g_{\lambda}(x) = \min_{x' \in \mathbb{R}^{d_1}} \bigg[ \phi_{\lambda, x}(x') = g(x') + \frac{1}{2\lambda} \|x - x'\|^2 \bigg]\,. \end{align} Then first part of (a) follows trivially by the strong convexity. For the second part notice the following, \begin{align} \min_x g_{\lambda}(x) &= \min_x \min_{x'} g(x') + \frac1{2\lambda} \|x-x' \|^2 \nonumber \\ &= \min_{x'} \min_x g(x') + \frac1{2\lambda} \|x-x' \|^2 \nonumber \\ &= \min_{x'} g(x') \nonumber \end{align} Thus $\arg\min_x g_{\lambda}(x) = \arg\min_x g(x)$. For $(b)$ we can re-write the Moreau envelope $g_\lambda$ as, \begin{align} g_\lambda(x) &= \min_{x'} g(x') + \frac1{2\lambda} \| x - x' \|^2 \nonumber \\ &= \frac{\|x\|^2}{2\lambda} - \frac1{\lambda} \max_{x'} (x^Tx' - \lambda g(x') - \frac{\|x'\|^2}2) \nonumber \\ &= \frac{\|x\|^2}{2\lambda} - \frac1{\lambda} \bigg(\lambda g(\cdot) + \frac{\|\cdot\|^2}2\bigg)^*(x) \label{eq:moreau-conjugate} \end{align} where $(\cdot)^*$ is the Fenchel conjugation operator. Since $L < 1/\lambda $, using $L$-weak convexity of $g$, it is easy to see that $\lambda g(x') + \frac{\|x'\|^2}2$ is $(1 - \lambda L)$-strongly convex, therefore its Fenchel conjugate would be $\frac1{(1 - \lambda L)}$-smooth \cite[Theorem 6]{kakade2009duality}. This, along with $\frac1\lambda$-smoothness of first quadratic term \textit{}implies that $g_\lambda(x)$ is $\big(\frac1\lambda + \frac1{\lambda(1 - \lambda L)}\big)$-smooth, and thus differentiable. For $(c)$ we again use the reformulation of $g_{\lambda}(x)$ as $\min_{x' \in \mathbb{R}^{d_1}} \phi_{\lambda, x}(x')$ \eqref{eq:moreau-reformula}. Then by first-order necessary condition for optimality of $\hat{x}_{\lambda}(x)$, we have that $x - \hat{x}_{\lambda}(x) \in \lambda \partial g(x)$. Further, from proof of part (a) we have that $\phi_{\lambda, x}(x')$ $(1 - \lambda L)$-strongly-convex in $x'$ and it is quadratic (and thus convex) in $x$. Then we can use Danskin's theorem \cite[Section 6.11]{bertsekas2009convex} to prove that, $\nabla g_\lambda (x) = (x - \hat{x}_\lambda(x))/\lambda \in \partial g(x)$. \end{proof} \section{Related Work} We now cover related work on several relevant topics. Further details are provided in Appendix~\ref{app:related_work} \textbf{Nonconvex-Nonconcave Zero-Sum Games.} The existing work on nonconvex-nonconcave zero-sum games has generally focused on (1) defining and characterizing local equilibrium solution concepts~\cite{ratliff2013allerton, ratliff:2016aa, jin2020local, fiez2020implicit, zhang2020optimality, farnia2020gans}, (2) designing gradient-based learning algorithms with local convergence guarantees to only a desired local equilibrium concept~\cite{adolphs2019local, mazumdar2019finding, jin2020local, fiez2020implicit, wang2019solving, zhang2020newton}, and (3) characterizing the local convergence behavior of gradient descent-ascent (GDA)~\cite{nagarajan2017gradient, mescheder2018training, mazumdar2020gradient,daskalakis:2018aa,jin2020local, fiez2020gradient}, since this is known to be computationally hard in general and GDA can get stuck in limit cycles~\cite{daskalakis2020complexity,hsieh2020limits, letcher2020impossibility}. The closest set of works to ours in this direction propose relaxed equilibrium notions that are shown to exist and be computable in polynomial time~\cite{keswani2020gans,mangoubi2020second}. The aforementioned works are similar to this paper in the sense that the min-player faces the max-player with computational restrictions, but are different from ours in terms of the model of the max-player and the algorithms to solve the problem. \textbf{Nonconvex-Concave Zero-Sum Games.} The structure presented in nonconvex-concave zero-sum games makes it possible to achieve global finite-time convergence guarantees to $\epsilon$--approximate stationary points of the objective function $f(\cdot, \cdot)$ and the best-response function $\Phi(\cdot)=\max_{y}f(\cdot, y)$. A significant number of papers in the past few years investigate the rates of convergence that can be obtained for this problem~\cite{jin2020local, rafique2018non, lu2020hybrid, lin2020gradient, lin2020near, luo2020stochastic, nouiehed2019solving, ostrovskii2020efficient, thekumparampil2019efficient, zhao2020primal, kong2019accelerated}. The best known existing results in the deterministic setting show that $\epsilon$--approximate stationary points of the functions $f(\cdot, \cdot)$ and $\Phi(\cdot)$ can be obtained with gradient complexities of $\widetilde{O}(\epsilon^{-2.5})$~\cite{ostrovskii2020efficient, lin2020near} and $\widetilde{O}(\epsilon^{-3})$~\cite{thekumparampil2019efficient, zhao2020primal, kong2019accelerated, lin2020near}, respectively. Moreover, the latter notion of an $\epsilon$--approximate stationarity point can be obtained using $\widetilde{O}(\epsilon^{-6})$ gradient calls in the stochastic setting of nonconvex-concave zero-sum games~\cite{rafique2018non}. We build on the advances in nonconvex-concave problems to obtain our results. \textbf{Gradient-Based Learning with Opponent Modeling.} A number of gradient-based learning schemes have been derived in various classes of games based on modeling opponent behavior and adjusting the gradient updates based on this prediction~\cite{zhang2010multi, foerster2018learning, letcher2018stable, fiez2020implicit, chasnov2020opponent, metz2016unrolled}. In particular, several works model the opponent as doing a gradient step and derive a learning rule by plugging in the predicted endpoint into the objective, evaluating a Taylor expansion around the last strategies to form an augmented objective, and then computing the gradient of this augmented objective~\cite{zhang2010multi, foerster2018learning, letcher2018stable}. In contrast, we directly compute the derivative of the objective function of the min-players through the model of the opponent. The only work that is similar in this manner is unrolled generative adversarial networks~\cite{metz2016unrolled}. A key conceptual distinction of our framework is its sequential nature with the opponent initializing from scratch at each interaction. Moreover, we give provable finite-time convergence guarantees which do not appear in past work in this realm. \section{Detailed Related Work} \label{app:related_work} \textbf{Nonconvex-Nonconcave Zero-Sum Games.} The existing work on nonconvex-nonconcave zero-sum games has generally focused on (1) defining and characterizing local equilibrium solution concepts and (2) analyzing the local stability and convergence behavior of gradient-based learning algorithms around fixed points of the dynamics. The concentration on local analysis stems from the inherent challenges that arise in nonconvex-nonconcave zero-sum games from both a dynamical systems perspective and a computational perspective. In particular, it is know that broad classes of gradient-based learning dynamics can admit limit cycles and other non-trivial periodic orbits that are antithetical to any type of global convergence guarantee in this class of games~\cite{hsieh2020limits, letcher2020impossibility}. Moreover, on constrained domains, it has been shown that finding even a local equilibrium is computationally intractable~\cite{daskalakis2020complexity}. A number of local equilibrium notions for nonconvex-nonconcave zero-sum games now exist with characterizations in terms of gradient-based conditions relevant to gradient-based learning. This includes the local Nash~\cite{ratliff2013allerton, ratliff:2016aa} and local minmax (Stackelberg)~\cite{jin2020local, fiez2020implicit} equilibrium concepts, which both amount to local refinements and characterizations of historically standard game-theoretic equilibrium notions. In terms of provable guarantees, algorithms incorporating higher-order gradient information have been proposed and analyzed that guarantee local convergence to only local Nash equilibria~\cite{adolphs2019local, mazumdar2019finding} or local convergence to only local minmax equilibria~\cite{wang2019solving, zhang2020newton, fiez2020implicit} in nonconvex-nonconcave zero-sum games. Beyond the local Nash and minmax equilibrium, notions including the proximal equilibrium concept~\cite{farnia2020gans}, which is a class between the set of local Nash and local minmax equilibria, and the local robust equilibrium concept~\cite{zhang2020optimality}, which includes both local minmax and local maxmin equilibria, have been proposed and studied. It is worth noting that a shortcoming of each of the local equilibrium notions is that may fail to exist on unconstrained domains. Significant attention has been given to the local stability and convergence of simultaneous gradient descent-ascent in nonconvex-nonconcave zero-sum games. This stems from the fact that it is the natural analogue of learning dynamics for zero-sum game optimization to gradient descent for function optimization. Moreover, simultaneous gradient descent-ascent is know to often perform reasonably well empirically and is ubiquitous in a number of applications such as in training generative adversarial networks and adversarial learning. However, it has been shown that while local Nash are guaranteed to be stable equilibria of simultaneous gradient descent-ascent~\cite{mazumdar2020gradient,daskalakis:2018aa,jin2020local}, local minmax may not be unless there is sufficient timescale separation between the minimizing and maximizing players~\cite{jin2020local, fiez2020gradient}. Specific to generative adversarial networks, it has been shown that simultaneous gradient descent-ascent locally converges to local equilibria under certain assumptions on the generator network and the data distribution~\cite{nagarajan2017gradient, mescheder2018training}. Later in this section we discuss in further detail learning dynamics studied previously in games which bear resemblance to that which we consider in this paper depending on the model of the maximizing player. The challenges of nonconvex-nonconcave zero-sum games we have highlighted limit the types of provable guarantees that can be obtained and consequently motivate tractable relaxations including to nonconvex-concave zero-sum games and the general framework we formulate in this work. Before moving on, we mention that from a related perspective, a line of recent work~\cite{keswani2020gans,mangoubi2020second} in nonconvex-nonconcave zero-sum games proposes relaxed equilibrium notions that are shown to be computable in polynomial time and are guaranteed to exist. At a high level, the equilibria correspond to a joint strategy at which the maximizing player is at an approximate local maximum of the cost function and the minimizing player is at an approximate local minimum of a smoothed and relaxed best-response function of the maximizing player. The aforementioned works are similar to this paper in the sense that the minimizing player faces a maximizing player with computational restrictions, but diverge in terms of the model of the maximizing player and the algorithms for solving the problem. \textbf{Nonconvex-Concave Zero-Sum Games.} The past few years has witnessed a significant amount of work on gradient-based dynamics in nonconvex-concave zero-sum games. The focus of existing work on nonconvex-concave zero-sum games has key distinctions from that in nonconvex-nonconcave zero-sum games. Generally, the work on nonconvex-concave zero-sum games has analyzed dynamics on constrained domains, where typically the strategy space of the maximizing player is constrained to a closed convex set and occasionally the minimizing player also faces a constraint. In contrast, nonconvex-nonconcave zero-sum games have generally been analyzed on unconstrained domains. Moreover, instead of focusing on computing notions of game-theoretic equilibrium as is typical in nonconvex-nonconcave zero-sum games, the body of work on nonconvex-concave zero-sum games has focused on achieving stationarity of the game cost function $f(\cdot, \cdot)$ or the best-response function $\Phi(\cdot)=\max_{y}f(\cdot, y)$. The structure present in nonconvex-concave zero-sum games has been shown to simplify the problem compared to nonconvex-nonconcave zero-sum games so that global finite-time convergence guarantees are achievable. Thus, work in this direction has focused on improving the rates of convergence in terms of the gradient complexity to find $\epsilon$--approximate stationary points of $f(\cdot, \cdot)$ or $\Phi(\cdot)$, both with deterministic and stochastic gradients. Guarantees on the former notion of stationarity can be translated to guarantees on the latter notion of stationarity with extra computational cost~\cite{lin2020gradient}. For the the class of nonconvex-strongly-concave zero-sum games, a series of works design algorithms that are shown to obtain $\epsilon$--approximate stationary points of the functions $f(\cdot, \cdot)$ or $\Phi(\cdot)$ with a gradient complexity of $\widetilde{O}(\epsilon^{-2})$ in terms of $\epsilon$ in the deterministic setting~\cite{jin2020local, rafique2018non, lu2020hybrid, lin2020gradient, lin2020near}. In the deterministic nonconvex-strongly concave problem, the notions of stationarity are equivalent in terms of the dependence on $\epsilon$ up to a logarithmic dependence~\cite{lin2020gradient}. Lower bounds for this problem have also been established~\cite{zhang2021complexity, li2021complexity}. In the stochastic nonconvex-strongly-concave problem, existing work has developed algorithms that are shown to obtain $\epsilon$--approximate stationary points of the function $\Phi(\cdot)$ in gradient complexities of $\widetilde{O}(\epsilon^{-4})$~\cite{rafique2018non, jin2020local, lin2020gradient} and $\widetilde{O}(\epsilon^{-3})$~\cite{luo2020stochastic} in terms of $\epsilon$ dependence. In the deterministic nonconvex-concave problem, a number of algorithms with provable guarantees to $\epsilon$--approximate stationary points of the function $f(\cdot, \cdot)$ have been shown with gradient complexities of $\widetilde{O}(\epsilon^{-4})$~\cite{lu2020hybrid}, $\widetilde{O}(\epsilon^{-3.5})$~\cite{nouiehed2019solving}, and $\widetilde{O}(\epsilon^{-2.5})$~\cite{ostrovskii2020efficient, lin2020near}. Similarly, in this class of problems, there exist results on algorithms that guarantee convergence to an $\epsilon$--approximate stationary points of the function $\Phi(\cdot)$ with gradient complexities $\widetilde{O}(\epsilon^{-6})$~\cite{rafique2018non, jin2020local, lin2020gradient} and $\widetilde{O}(\epsilon^{-3})$ \cite{thekumparampil2019efficient, zhao2020primal, kong2019accelerated, lin2020near}. Finally, existing results in the stochastic setting for achieving an $\epsilon$--approximate stationary point of $\Phi(\cdot)$ show gradient complexities of $\widetilde{O}(\epsilon^{-6})$~\cite{rafique2018non} and $\widetilde{O}(\epsilon^{-8})$~\cite{lin2020gradient}. In this work, we build on the developments for nonconvex-concave problems to obtain our results. \textbf{Gradient-Based Learning with Opponent Modeling.} A number of gradient-based learning schemes have been derived is various classes of games based on the following idea: if a player knows how the opponents in a game are optimizing their cost functions, then it is natural to account for this behavior in the players own optimization procedure. The simultaneous gradient descent learning dynamics can be viewed as the simplest instantiation of this perspective, where each player is optimizing their own cost function assuming that all other players in the game will remain fixed. In general, the more sophisticated existing learning dynamics based on opponent modeling assume the opponents are doing gradient descent on their cost function and this prediction is incorporated into the objective being optimized in place of the current strategies of opponents. A key conceptual distinction between this approach and our work is that in existing opponent modeling methods the dynamics of the players are always updated simultaneously whereas the procedure we consider is sequential in nature with the opponent initializing again at each interaction. Moreover, the types of guarantees we prove are distinct compared to existing work in this realm. In this modern literature, gradient-based learning with opponent modeling dates back to the work of~\citet{zhang2010multi}. They study simple two-player, two-action, general-sum matrix games, and analyze a set of learning dynamics called iterated descent descent with policy prediction (IGA-PP) and show asymptotic convergence to a Nash equilibrium. In this set of learning dynamics, each player assumes the other player is doing gradient descent and this prediction is used in the objective. In particular, each player $i$ has a choice variable $x^i$ and a cost function $f_i(x^i, x^{-i})$ that after incorporating the prediction becomes $f_i(x_t^i, x_t^{-i} - \gamma \nabla_{-i} f_{-i}(x_t^{i}, x_t^{-i}))$. To optimize the objective, each player takes a first-order Taylor expansion of their cost function to give the augmented objective \[f_i(x_t^i, x_t^{-i} - \gamma \nabla_{-i} f_{-i}(x_t^{i}, x_t^{-i}))\approx f_i(x_t^i, x_t^{-i})- \gamma \nabla_{-i}f_i(x_i^t, x_{-i}^t)^{\top} \nabla_{-i} f_{-i}(x_t^{i}, x_t^{-i}).\] Each player in the game simultaneously follows the gradient of their augmented objective which is given by \[\nabla_if_i(x_t^i, x_t^{-i})- \gamma \nabla_{-i, i}f_i(x_i^t, x_{-i}^t)^{\top} \nabla_{-i} f_{-i}(x_t^{i}, x_t^{-i}).\] This gradient computation is derived based on the fact that the assumed update of the other player $\nabla_{-i} f_{-i}(x_t^{i}, x_t^{-i})$ does not depend on the optimization variable. Similar ideas have recently been revisited in more general nonconvex multiplayer games~\cite{foerster2018learning, letcher2018stable}. In learning with opponent learning awareness (LOLA)~\cite{foerster2018learning}, players again assume the other players are doing gradient descent and take their objective to be $f_i(x_t^i, x_t^{-i} - \gamma \nabla_{-i} f_{-i}(x_t^{i}, x_t^{-i}))$. To derive the learning rule, an augmented objective is again formed by computing a first-order Taylor expansion, but now the term $\nabla_{-i} f_{-i}(x_t^{i}, x_t^{-i})$ in the augmented objective is treated as dependent on the optimization variable so that the gradient of the augmented objective is given by \[\nabla_if_i(x_t^i, x_t^{-i})- \gamma \nabla_{-i, i}f_i(x_i^t, x_{-i}^t)^{\top} \nabla_{-i} f_{-i}(x_t^{i}, x_t^{-i})- \gamma \nabla_{-i, i} f_{-i}(x_t^{i}, x_t^{-i})^{\top}\nabla_{-i}f_i(x_i^t, x_{-i}^t).\] Finally, to arrive at the final gradient update for each player, the middle term in the equation above is removed and each player takes steps along the gradient update \[\nabla_if_i(x_t^i, x_t^{-i})- \gamma \nabla_{-i, i} f_{-i}(x_t^{i}, x_t^{-i})^{\top}\nabla_{-i}f_i(x_i^t, x_{-i}^t).\] While no convergence results are given for LOLA, a follow-up work shows local convergence guarantees to stable fixed points for IGA-PP and learning dynamics called stable opponent shaping (SOS) that interpolate between IGA-PP and LOLA~\cite{letcher2018stable}. A related work derives learning dynamic based on the idea that the opponent selects a best-response to the chosen strategy~\cite{fiez2020implicit}. The resulting learning dynamics can be viewed as LOLA with the opponent selecting a Newton learning rate. For nonconvex-nonconcave zero-sum games, local convergence guarantees to only local Stackelberg equilibrium are given in for this set of learning dynamics~\cite{fiez2020implicit}. It is worth remarking that gradient-based learning with opponent modeling is historically rooted in the general framework of consistent conjectural variations (see, e.g., \cite[Chapter 4.6]{bacsar1998dynamic}), a concept that is now being explored again and is closely related to the previously mentioned learning dynamics~\cite{chasnov2020opponent}. Perhaps the closest work on gradient-based learning with opponent modeling to this paper is that of unrolled generative adversarial networks~\cite{metz2016unrolled}. In unrolled generative adversarial networks, the generator simulates the discriminator doing a fixed number of gradient steps from the current parameter configurations of the generator and discriminator. The resulting discriminator parameters are then used in place of the current discriminator parameters in the generator objective. The generator then updates following the gradient of this objective, optimizing through the rolled out discriminator update by computing the total derivative. Simultaneously with the generator update, the discriminator updates its parameters by performing a gradient step on its objective. In our framework, for generative adversarial networks when the discriminator is modeled as performing $T$-steps of gradient ascent, the procedure we propose is similar but an important difference is that when the generator simulates the discriminator unrolling procedure the discriminator parameters are initialized from scratch and there is no explicit discriminator being trained simultaneously with the generator. \textbf{Games with computationally bounded adversaries}: There are also a few works in the game theory literature which consider resource/computationally bounded agents. For example~\cite{freund1995efficient} considers \emph{repeated} games between resource bounded agents,~\cite{sandhlom1997coalitions} considers coalition formation between resource bounded agents in cooperative games and~\cite{halpern2014decision} shows that resource constraints in otherwise rational players might lead to some commonly observed human behaviors while making decisions. However, the settings, models of limited computation and the focus of results considered in all of these prior works are distinct from those of this paper. \textbf{Stability of algorithms in numerical analysis}: To our knowledge such results on the smoothness of the classes of algorithms we study---i.e., gradient-based updates such as SGA and SNAG---with respect to problem parameters (e.g., in this case, $x$) have not been shown in the machine learning and optimization literature. This being said, in the study of dynamical systems---more specifically differential equations---the concept of continuity (and Lipschitzness) with respect to parameters and initial data has been studied using a \emph{variational} approach wherein the continuity of the solution of the differential equation is shown to be continuous with respect to variations in the parameters or initial data by appealing to nonlinear variation of parameters results such as the Bellman-Grownwall inequality or Alekseev's theorem (see classical references on differential equations such as \cite[Chapter 2]{coddington1955theory} or \cite[Chapter IV.2]{hartman2002odes}). In numerical methods, such results on the ``smoothness'' or continuity of the differential equation with respect to initial data or problem parameters are used to understand stability of particular numerical methods (see, e.g., \cite[Chapter 1.2]{atkinson2011numerical}). In particular, a initial value problem is only considered well-posed if there is continuous dependence on initial data. For instance, the simple scalar differential equation \[\dot{y}(t)=-y(t)+1, \ 0\leq t\leq T, \ y(0)=1\] has solution $y(t)\equiv 1$, yet the perturbed problem, \[\dot{y}_\epsilon(t)=-y_\epsilon(t)+1, \ 0\leq t\leq T, \ y_\epsilon(0)=1+\epsilon,\] has solution $y_\epsilon(t)=1+\epsilon e^{-t}$ so that \[|y(t)-y_\epsilon(t)|\leq |\epsilon|, \ 0\leq t\leq T.\] If the maximum error $\|y_\epsilon-y\|_\infty$ is (much) larger than $\epsilon$ then the initial value problem is \emph{ill-conditioned} and any typical attempt to numerically solve such a problem will lead to large errors in the computed solution. In short, the stability properties of a numerical method (i.e., discretization of the differential equation) are fundamentally connected to the continuity (smoothness) with respect to intial data. Observe that methods such as gradient ascent can be viewed as a discretization of an differential equation: \[\dot{y}(t)=\nabla_yf(x,y(t)) \ \longrightarrow y_{k+1}=y_k+\eta \nabla_yf(x,y_k).\] As such, the techniques for showing continuity of the solution of a differential equation with respect to initial data or other problem parameters (e.g., in this case $x$) can be adopted to show smoothness of the $T$-step solution of the discretized update. Our approach to showing smoothness, on the other hand, leverages the recursive nature of the discrete time updates defining the classes of algorithms we study. This approach simplifies the analysis by directly going after the smoothness parameters using the udpate versus solving the difference (or differential) equation for $y_T(x)$ and then finding the smoothness parameters which is the method typically used in numerical analysis of differential equations. An interesting direction of future research is to more formally connect the stability analysis from numerical analysis of differential equations to robustness of adversarial learning to initial data and even variations in problem parameters. \section{Empirical Results} \label{sec:empirical} This section presents empirical results evaluating our SGD algorithm (Algorithm~\ref{algo:sgd}) for generative adversarial networks~\cite{goodfellow2014generative} and adversarial training~\cite{madry2017towards}. We demonstrate that our framework results in stable monotonic improvement during training and that the optimization through the algorithm of the adversary is key to robustness and fast convergence. Finally, we show that in practice the gradient norms do not grow exponentially in the number of gradient ascent steps $T$ taken by the adversary. \textbf{Generative Adversarial Networks.} A common and general formulation of generative adversarial networks is characterized by the following minimax optimization problem (see, e.g.,~\cite{nagarajan2017gradient, mescheder2018training}): \begin{equation} \textstyle \min_{\theta}\max_{\omega}f(\theta,\omega)=\mathbb{E}_{x\sim p_{\mathcal{X}}}[\ell(D_{\omega}(x))]+\mathbb{E}_{z\sim p_{\mathcal{Z}}}[\ell(-D_{\omega}(G_{\theta}(z)))]. \label{eq:ganobjective} \end{equation} In this formulation $G_\theta: \mathcal{Z}\rightarrow \mathcal{X}$ is the generator network parameterized by $\theta$ that maps from the latent space $\mathcal{Z}$ to the input space $\mathcal{X}$, $D_\omega:\mathcal{X}\rightarrow \mathbb{R}$ is discriminator network parameterized by $\omega$ that maps from the input space $\mathcal{X}$ to real-valued logits, and $p_{\mathcal{X}}$ and $p_{\mathcal{Z}}$ are the distributions over the input space and the latent space. The loss function defines the objective where $\ell(w)=-\log(1+\exp(-w))$ recovers the original ``saturating'' generative adversarial networks formulation~\cite{goodfellow2014generative}. \textbf{Dirac--GAN.} The Dirac-GAN~\cite{mescheder2018training} is a simple and common baseline for evaluating the efficacy of generative adversarial network training methods. In this problem, the generator distribution $G_{\theta}(z) = \delta_\theta$ is a Dirac distribution concentrated at $\theta$, the discriminator network $D_{\omega}(x) = -\omega x$ is linear, and the real data distribution $p_{\mathcal{X}}=\delta_0$ is a Dirac distribution concentrated at zero. The resulting objective after evaluating~\eqref{eq:ganobjective} with the loss function $\ell(w)=-\log(1+\exp(-w))$ is \[\textstyle \min_{\theta}\max_{\omega}f(\theta,\omega)=\ell(\theta\omega)+\ell(0)=-\log(1+e^{-\theta\omega})-\log(2).\] To mimic the real data distribution, the generator parameter $\theta$ should converge to $\theta^{\ast}=0$. Notably, simultaneous and alternating gradient descent-ascent are known to cycle and fail to converge on this problem (see Figure~\ref{fig:dirac}). We consider an instantiation of our framework where the discriminator samples an initialization uniformly between $[-0.1, 0.1]$ and performs $T=10$ steps of gradient ascent between each generator update. The learning rates for both the generator and the discriminator are $\eta=0.01$. We present the results in Figure~\ref{fig:dirac}. Notably, the generator parameter monotonically converges to the optimal $\theta^{\ast}=0$ and matches the real data distribution using our training method. We also show the performance when the generator descends using partial gradient $\nabla_\theta f(x, \mathcal{A}(\theta))$ instead of the total gradient $\nabla f(\theta, \mathcal{A}(\theta))$ in Algorithm~\ref{algo:sgd}. This method is able to converge to the optimal generator distribution but at a slower rate. Together, this example highlights that our method fixes the usual cycling problem by reinitializing the discriminator and also that optimizing through the discriminator algorithm is key to fast convergence. Additional results are given in Appendix~\ref{app:experiments}. \begin{figure}[!tbp] \begin{minipage}[t]{.525\textwidth} \centering \subfloat{\includegraphics[width=\textwidth]{Figs/dirac_legend.png}} \vspace{0pt} \subfloat{\includegraphics[width=.5\textwidth]{Figs/simgrad_altgrad.png}} \subfloat{\includegraphics[width=.5\textwidth]{Figs/param_sets0.png}} \caption{\textbf{Dirac-GAN}: Generator parameters while training using simultaneous and alternating gradient descent-ascent (left), and our framework (right) with \& without optimizing through the discriminator. Under our framework, training is stable and converges to correct distribution. Further, differentiating through the discriminator results in faster convergence.} \label{fig:dirac} \end{minipage}% \hfill \begin{minipage}[t]{.425\textwidth} \centering \vspace{0pt} \includegraphics[width=\textwidth]{Figs/grad_norm_small.png} \caption{\textbf{Adversarial training}: $\|\nabla f(\theta, \mathcal{A}(\theta))\|$ as a function of number of steps $T$ taken by gradient ascent (GA) algorithm $\mathcal{A}$ evaluated at multiple points in the training procedure. The plot shows that, in practice, the Lipschitz parameter of GA does not grow exponentially in $T$.} \label{fig:grad_norm} \end{minipage}% \end{figure} \begin{figure}[t!] \centering \vspace{0pt} \subfloat[][Real Data]{\includegraphics[width=.14\textwidth]{Figs/samples_real_gaussian.png}\label{fig:gan_real}} \subfloat[][10k]{\includegraphics[width=.14\textwidth]{Figs/higher_gan/samples_10000.png}\label{fig:gan_results1}} \subfloat[][40k]{\includegraphics[width=.14\textwidth]{Figs/higher_gan/samples_40000.png}\label{fig:gan_results2}} \subfloat[][70k]{\includegraphics[width=.14\textwidth]{Figs/higher_gan/samples_70000.png}\label{fig:gan_results3}} \subfloat[][100k]{\includegraphics[width=.14\textwidth]{Figs/higher_gan/samples_100000.png}\label{fig:gan_results4}} \subfloat[][130k]{\includegraphics[width=.14\textwidth]{Figs/higher_gan/samples_130000.png}\label{fig:gan_results5}} \subfloat[][150k]{\includegraphics[width=.14\textwidth]{Figs/higher_gan/samples_150000.png}\label{fig:gan_results6}} \caption{ \textbf{Mixture of Gaussians}: Generated distribution at various steps during course of training. We see that training is stable and results in monotonic progress towards the true distribution. } \label{fig:gan} \end{figure} \textbf{Mixture of Gaussians.} We now demonstrate that the insights we developed from the Dirac-GAN (stability and monotonic improvement) carry over to the more complex problem of learning a 2-dimensional mixture of Gaussians. This is a common example and a number of papers (see, e.g.,~\cite{metz2016unrolled, mescheder2017numerics, balduzzi2018mechanics}) show that standard training methods using simultaneous or alternating gradient descent-ascent can fail. The setup for the problem is as follows. The real data distribution consists of 2-dimensional Gaussian distributions with means given by $\mu = [\sin(\phi), \cos(\phi)]$ for $\phi \in \{k\pi/4\}_{k=0}^7$ and each with covariance $\sigma^2 I$ where $\sigma^2=0.05$. For training, the real data $x\in \mathbb{R}^2$ is drawn at random from the set of Gaussian distributions and the latent data $z \in \mathbb{R}^{16}$ is drawn from a standard normal distribution with batch sizes of 512. The network for the generator and discriminator contain two and one hidden layers respectively, each of which contain $32$ neurons and ReLU activation functions. We consider the objective from~\eqref{eq:ganobjective} with $\ell(w)=-\log(1+\exp(-w))$ which corresponds to the ``saturating'' generative adversarial networks formulation~\cite{goodfellow2014generative}. This objective is known to be difficult to train since with typical training methods the generator gradients saturate early in training. We show results using our framework in Figure~\ref{fig:gan} where the discriminator performs $T=15$ steps of gradient ascent and the initialization between each generator step is obtained by the default network initialization in Pytorch. The generator and discriminator learning rates are both fixed to be $\eta = 0.5$. We see that our method has stable improvement during the course of training and recovers close to the real data distribution. We demonstrate in Appendix~\ref{app:experiments} that this result is robust by presenting the final output of 10 runs of the procedure. Notably, the training algorithm recovers all the modes of the distribution in each run. We also show results using Adam for the discriminator in Appendix~\ref{app:experiments}. \begin{figure}[t!] \centering \includegraphics[width=\textwidth]{Figs/attack_results_all_small.png} \includegraphics[width=.55\textwidth]{Figs/adversarial_legend.png} \caption{\textbf{Adversarial training}: Test accuracy during course of training where the attack used during training is gradient ascent (GA) with learning rate (LR) of $4$ and number of steps (Steps) of $10$ but evaluated against attacks with different Steps and LR. These plots show that training with a single attack gives more robustness to even other attacks with different parameters or algorithms, compared to standard training. Further, using total gradient $\nabla f(\theta,\mathcal{A}(\theta))$ yields better robustness compared to using partial gradient $\nabla_{\theta}f(\theta, \mathcal{A}(\theta))$ as is done in standard adversarial training~\cite{madry2017towards}.} \label{fig:attack} \end{figure} \textbf{Adversarial Training.} Given a data distribution $\mathcal{D}$ over pairs of examples $x\in \mathbb{R}^d$ and labels $y\in [k]$, parameters $\theta$ of a neural network, a set $\mathcal{S}\subset \mathbb{R}^d$ of allowable adversarial perturbations, and a loss function $\ell(\cdot, \cdot, \cdot)$ dependent on the network parameters and the data, adversarial training amounts to considering a minmax optimization problem of the form \[\textstyle \min_{\theta}\mathbb{E}_{(x, y)\sim \mathcal{D}}[\max_{\delta\in \mathcal{S}}\ell(\theta, x+\delta, y)].\] In practice~\cite{madry2017towards}, the inner maximization problem $\max_{\delta\in \mathcal{S}}\ell(\theta, x+\delta, y)$ is solved using \emph{projected} gradient ascent. However, as described in Section~\ref{sec:smoothness}, this is not a smooth algorithm and does not fit our framework. So, we use gradient ascent, \emph{without projection}, for solving the inner maximization. We run an adversarial training experiment with the MNIST dataset, a convolutional neural network, and the cross entropy loss function. We compare Algorithm~\ref{algo:sgd} with usual adversarial training~\cite{madry2017towards} which descends $\nabla_\theta f(\theta, \mathcal{A}(\theta))$ instead of $\nabla f(\theta, \mathcal{A}(\theta))$, and a baseline of standard training without adversarial training. For each algorithm, we train for 100 passes over the training set using a batch size of 50. The minimization procedure has a fixed learning rate of $\eta_1=0.0001$ and the maximization procedure runs for $T=10$ steps with a fixed learning rate of $\eta_2=4$. We evaluate the test classification accuracy during the course of training against gradient ascent or Adam optimization adversarial attacks. The results are presented in Figure~\ref{fig:attack} where the mean accuracies are reported over 5 runs and the shaded regions show one standard deviation around the means. We observe that the adversarial training procedure gives a significant boost in robustness compared to standard training. Moreover, consistent with the previous experiments, our algorithm which uses total gradient outperforms standard adversarial training which uses only partial gradient. We present results against more attacks in Appendix~\ref{app:experiments}. As suggested in Section~\ref{sec:smoothness}, we also find that in practice, the gradient norms $\|\nabla f(\theta, \mathcal{A}(\theta))\|$ do not grow exponentially in the number of gradient ascent steps $T$ in the adversary algorithm $\mathcal{A}$ (see Figure~\ref{fig:grad_norm}). For further details and additional results see Appendix~\ref{app:experiments}. \section{Main Results}\label{sec:results} In this section, we present our main results. Assuming that the adversary employs Lipschitz and gradient-Lipschitz algorithms (Assumption~\ref{ass:smoothalgo}), Section~\ref{sec:subgrad} shows how to compute (stochastic) subgradients of $g(\cdot)$ (defined in~\eqref{eqn:minimax-mod}) efficiently. Section~\ref{sec:conv-sgd} further shows that stochastic subgradient descent (SGD) on $g(\cdot)$ can find an $\epsilon$-FOSP in $\order{\epsilon^{-4}}$ iterations while for the deterministic setting, where the adversary uses only deterministic algorithms, Section~\ref{sec:prox} provides a proximal algorithm that can find an $\epsilon$-FOSP faster than SGD. For convenience, we denote $g_{z,i}(x) \mathrel{\mathop:}= f(x,\mathcal{A}_i(x,z_i))$ and recall $g(x) \mathrel{\mathop:}= \mathbb{E}_{z}\left[\max_{i \in [k]} g_{z,i}(x)\right]$. For deterministic $\mathcal{A}_i$, we drop $z$ and just use $g_i(x)$. \input{conv} \input{smoothness} \section{Preliminaries}\label{sec:prelims} In this section, we present problem formulation and preliminaries. We consider function $f$ satisfying \begin{assumption}\label{ass:func-smooth} We denote $w = (x, y)$, and assume $f:\mathbb{R}^{d_1} \times \mathbb{R}^{d_2} \rightarrow \mathbb{R}$ is: \begin{enumerate} \vspace{-1ex} \item[(a)] $B$-bounded i.e., $\abs{f(w)} \leq B$, \item[(b)] $G$-Lipschitz i.e., $\abs{f(w_1)-f(w_2)} \leq G\norm{w_1-w_2}$, \item[(c)] $L$-gradient Lipschitz i.e., $\norm{\nabla f(w_1)- \nabla f(w_2)} \leq L\norm{w_1-w_2}$, \item[(d)] $\rho$-Hessian Lipschitz i.e., $\norm{\nabla^2 f(w_1)- \nabla^2 f(w_2)} \leq \rho \norm{w_1-w_2}$. \end{enumerate} where $\norm{\cdot}$ denotes Euclidean norm for vectors and operator norm for matrices. \end{assumption} We aim to solve $\min_{x \in \mathbb{R}^{d_1}} \max_{y \in \mathbb{R}^{d_2}} f(x,y)$. Since $\max_{y \in \mathbb{R}^{d_2}} f(x,y)$ involves non-concave maximization and hence is NP-hard in the worst case, we intend to play against algorithm(s) that $y$-player uses to compute her strategy. Concretely, given $x \in \mathbb{R}^{d_1}$, we assume that the $y$-player chooses her (potentially random) strategy ${\widehat{y}}_z(x) = \mathcal{A}_{i^*(x)}(x,z_{i^*(x)})$, where we use shorthand $z\mathrel{\mathop:}= (z_1,\cdots,z_k)$, as $\textstyle i^*(x) = \mathop{\mathrm{argmax}}_{i\in[k]} f(x,\mathcal{A}_i(x,z_i))$, where $\mathcal{A}_1,\cdots,\mathcal{A}_k$ are $k$ \emph{deterministic} algorithms that take as input $x$ and a random seed $z_i \in \mathbb{R}^\ell$, where $z_i$ are all independent. Note that the framework captures randomized algorithms e.g., $\mathcal{A}$ could be stochastic gradient ascent on $f(x,\cdot)$, with initialization, minibatching etc. determined by the random seed $z$. This also incorporates running the same algorithm multiple times, with different seeds and then choosing the best strategy. We now reformulate the minimax objective function to: \begin{align}\label{eqn:minimax-mod} \textstyle \min_{x \in \mathbb{R}^{d_1}} g(x) \quad \mbox{ where } \quad g(x) \mathrel{\mathop:}= \mathbb{E}_{z}\left[f(x,{\widehat{y}}_z(x))\right]. \end{align} For general algorithms $\mathcal{A}_i$, the functions $f(x,\mathcal{A}_i(x,z_i))$ need not be continuous even when $f$ satisfies Assumption~\ref{ass:func-smooth}. However, if the algorithms $\mathcal{A}_i$ are smooth as defined below, the functions $f(x,\mathcal{A}_i(x,z_i))$ behave much more nicely. \begin{definition}[Algorithm Smoothness]\label{def:smooth} A randomized algorithm $\mathcal{A}:\mathbb{R}^{d_1} \times \mathbb{R}^{\ell}\rightarrow \mathbb{R}^{d_2}$ is: \begin{enumerate} \item[(a)] $G$-Lipschitz, if $\norm{\mathcal{A}(x_1, z)-\mathcal{A}(x_2, z)} \leq G\norm{x_1-x_2}$ for any $z$. \item[(b)] $L$-gradient Lipschitz, if $\norm{D\mathcal{A}(x_1, z)-D\mathcal{A}(x_2, z)} \leq L\norm{x_1-x_2}$ for any $z$. \end{enumerate} \end{definition} Here $D\mathcal{A}(x, z) \in \mathbb{R}^{d_1} \times \mathbb{R}^{d_2}$ is the Jacobian of the function $\mathcal{A}(\cdot, z)$ for a fixed $z$. The following lemma tells us that $f(x,\mathcal{A}(x,z))$ behaves nicely whenever $\mathcal{A}$ is a Lipschitz and gradient Lipschitz algorithm. For deterministic algorithms, we also use the shortened notation $\mathcal{A}(x)$ and $D\mathcal{A}(x)$. \begin{lemma}\label{lem:smooth-func} Suppose $\mathcal{A}$ is $G'$-Lipschitz and $L'$-gradient Lipschitz and $f$ satisfies Assumption~\ref{ass:func-smooth}. Then, for a fixed $z$, function $f(\cdot,\mathcal{A}(\cdot,z))$ is $G(1+G')$-Lipschitz and $L(1+G')^2 + GL'$-gradient Lipschitz. \end{lemma} While $g(x)$ defined in~\eqref{eqn:minimax-mod} is not necessarily gradient Lipschitz, it can be shown to be weakly-convex as defined below. Note that an $L$-gradient Lipschitz function is $L$-weakly convex. \begin{definition}\label{def:weak-convex} A function $g:\mathbb{R}^{d_1} \to \mathbb{R}$ is {\em $L$-weakly convex} if $\forall \; x$, there exists a vector $u_x$ satisfying: \begin{align} g(x') \geq g(x) + \iprod{u_x}{x'-x} - \tfrac{L}{2} \|x' - x\|^2 \;\; \forall \, \; x'. \label{eq:weakly-cvx} \end{align} Any vector $u_x$ satisfying this property is called the subgradient of $g$ at $x$ and is denoted by $\nabla g(x)$. \end{definition} An important property of weakly convex function is that the maximum over a finite number of weakly convex function is still a weakly convex function. \begin{lemma}\label{lem:argmax-weakconvex} Given $L$-weakly convex functions $g_1,\cdots,g_k: \mathbb{R}^d \rightarrow \mathbb{R}$, the maximum function $g(\cdot) \mathrel{\mathop:}= \max_{i \in [k]} g_i(\cdot)$ is also $L$-weakly convex and the set of subgradients of $g(\cdot)$ at $x$ is given by: \begin{align*} \textstyle \partial g(x) = \{\sum_{j \in S(x)} \lambda_j \nabla g_j(x) : \lambda_j \geq 0, \; \sum_{j \in S(x)} \lambda_j = 1\}, \text{where} \ S(x) \mathrel{\mathop:}= \mathop{\mathrm{argmax}}_{i \in [k]} g_i(x). \end{align*} \end{lemma} Consequently under Assumption~\ref{ass:func-smooth} and the assumption that $\mathcal{A}_i$ are all $G'$-Lipschitz and $L'$-gradient Lipschitz, we have that $g(\cdot)$ defined in~\eqref{eqn:minimax-mod} is $L(1+G')^2 + GL'$-weakly convex. The standard notion of optimality for weakly-convex functions is that of approximate first order stationary point~\cite{davis2018stochastic}. \textbf{Approximate first-order stationary point for weakly convex functions}: In order to define approximate stationary points, we also need the notion of Moreau envelope. \begin{definition}\label{def:Moreau} The \emph{Moreau envelope} of a function $g:\mathbb{R}^{d_1} \to \mathbb{R}$ and parameter $\lambda$ is: \begin{eqnarray} \textstyle g_{\lambda}(x) \;\; = \;\; \min_{x' \in \mathbb{R}^{d_1}} g(x') + \left({2\lambda}\right)^{-1} \|x - x'\|^2\;. \label{eq:envelope} \end{eqnarray} \end{definition} The following lemma provides useful properties of the Moreau envelope. \begin{lemma}\label{lem:moreau-properties} For an $L$-weakly convex function $g:\mathbb{R}^{d_1} \to \mathbb{R}$ and $\lambda < 1/L$, we have: \begin{enumerate} \item[(a)] The minimizer $\hat{x}_{\lambda}(x) = \arg\min_{x' \in \mathbb{R}^{d_1}} g(x') + (2\lambda)^{-1} \|x - x'\|^2$ is unique and $g(\hat{x}_{\lambda}(x)) \leq g_{\lambda}(x) \leq g(x)$. Furthermore, $\arg\min_x g(x) = \arg\min_x g_{\lambda} (x)$. \item[(b)] $g_{\lambda}$ is $\lambda^{-1}(1+(1 - \lambda L)^{-1})$-smooth and thus differentiable, and \item[(c)] $ \min_{u \in \partial g(\hat{x}_{\lambda}(x))} \|u\| \leq \lambda^{-1} \| \hat{x}_{\lambda}(x) - x\| = \| \nabla g_{\lambda}(x) \|$. \end{enumerate} \end{lemma} First order stationary points of a non-smooth nonconvex function are well-defined, i.e., $x^*$ is a {\em first order stationary point (FOSP)} of a function $g(x)$ if, $0 \in \partial f(x^*)$. However, unlike smooth functions, it is nontrivial to define an \emph{approximate} FOSP. For example, if we define an $\varepsilon$-FOSP as the point $x$ with $\min_{u \in \partial g(x)} \| u \| \leq \varepsilon$, where $\partial g(x)$ denotes the subgradients of $g$ at $x$, there may never exist such a point for sufficiently small $\varepsilon$, unless $x$ is exactly a FOSP. In contrast, by using above properties of the Moreau envelope of a weakly convex function, it's approximate FOSP can be defined as \cite{davis2018stochastic}: \begin{definition}\label{def:eps_fosp} Given an $L$-weakly convex function $g$, we say that $x^*$ is an $\varepsilon$-first order stationary point ($\varepsilon$-FOSP) if, $\| \nabla g_{1/2L}(x^*) \| \leq \varepsilon$, where $g_{1/2L}$ is the Moreau envelope with parameter $1/2L$. \end{definition} \noindent Using Lemma \ref{lem:moreau-properties}, we can show that for any $\varepsilon$-FOSP $x^*$, there exists $\hat{x}$ such that $\|\hat{x} - x^* \| \leq \varepsilon/2L$ and $\min_{u\in \partial g(\hat{x})} \| u\| \leq \varepsilon$. In other words, an $\varepsilon$-FOSP is $O(\varepsilon)$ close to a point $\hat{x}$ which has a subgradient smaller than $\varepsilon$. Other notions of FOSP proposed recently such as in~\cite{nouiehed2019solving} can be shown to be a strict generalization of the above definition. \section{Smoothness of Popular Algorithms}\label{sec:smoothness} In this section, we show that two popular algorithms---namely, $T$-step stochastic gradient ascent (SGA) and $T$-step stochastic Nesterov's accelerated gradient ascent (SNAG)---are both Lipschitz and gradient-Lipschitz satisfying Assumption~\ref{ass:smoothalgo} and hence are captured by our results in Section~\ref{sec:results}. Consider the setting $f(x,y)=\frac{1}{n}\sum_{j \in [n]} f_j(x,y)$. Let $z$ be a random seed that captures the randomness in the initial point as well as minibatch order in SGA and SNAG. We first provide the smoothness results on $T$-step SGA for different assumptions on the shape of the function $f$ and for $T$-step SNAG. After giving these results, we make remarks interpreting their significance and the implications. \paragraph{$T$-step SGA:} For a given $x$ and random seed $z$, the $T$-step SGA update is given by: \begin{equation*} \textstyle y_{t+1} = y_t + \eta \nabla_y f_{\sigma(t)}(x,y_t) \end{equation*} where $\sigma:[T]\to [N]$ is a sample selection function and $\eta$ is the stepsize. Observe that with the same randomness $z$, the initial point does not depend on $x$ i.e., $y_0(x) = y_0(x')$, so $Dy_0 = 0$. The following theorems provide the Lipschitz and gradient Lipschitz constants of $y_T(x)$ (as generated by $T$-step SGA) for the general nonconvex-nonconcave setting as well as the settings in which the function $f$ is nonconvex-concave and nonconvex-strongly concave. \begin{restatable}[General Case]{theorem}{sgsmooth} Suppose for all $j \in [n]$, $f_j$ satisfies Assumption~\ref{ass:func-smooth}. Then, for any fixed randomness $z$, $T$-step SGA is $(1+\eta L)^T$-Lipschitz and $4(\rho/L) \cdot (1+\eta L)^{2T}$-gradient Lipschitz. \label{thm:sg-smooth} \end{restatable} \begin{restatable}[Concave Case]{theorem}{sgconcave} Suppose for all $j \in [n]$, $f_j$ satisfies Assumption~\ref{ass:func-smooth} and $f_j(x, \cdot)$ is concave for any $x$. Then, for any fixed randomness $z$, $T$-step SGA is $\eta L T$-Lipschitz and $(\rho/L)\cdot(1+\eta L T)^3 $-gradient Lipschitz. \label{thm:sg-concave} \end{restatable} \begin{restatable}[Strongly-concave Case]{theorem}{sgstrconcave} Suppose for all $j \in [n]$, $f_j$ satisfies Assumption~\ref{ass:func-smooth} and $f_j(x, \cdot)$ is $\alpha$-strongly concave for any $x$. Then, for any fixed randomness $z$, $T$-step SGA is $\kappa$-Lipschitz and $4(\rho/L)\cdot \kappa^3$-gradient Lipschitz, where $\kappa = L/\alpha$ is the condition number. \label{thm:sg-strconcave} \end{restatable} \paragraph{$T$-step SNAG:} For a given random seed $z$, the $T$-step SNAG update is given by: \begin{align*} \tilde{y}_{t}=&y_{t}+ (1-\theta) (y_{t}-y_{t-1})\\ y_{t+1}=&\tilde{y}_t+\eta \nabla_y\widehat{f}_{\sigma(t)}(x,\tilde{y}_t), \end{align*} where $\eta$ is the stepsize, $\theta\in[0,1]$ is the momentum parameter. The output of the algorithm is given by $\mathcal{A}(x,z) = y_T(x)$. Furthermore, we have the following guarantee. \begin{restatable}[General Case]{theorem}{agsmooth} Suppose for all $j \in [n]$, $f_j$ satisfies Assumption~\ref{ass:func-smooth}. Then, for any fixed seed $z$, $T$-step SNAG is $T (1+\eta L/\theta)^T$-Lipschitz and $50(\rho/L) \cdot T^3(1+\eta L/\theta)^{2T}$-gradient Lipschitz. \label{thm:ag-smooth} \end{restatable} \paragraph{Remarks on the Impact of the Smoothness Results:} First, the Lipschitz and gradient Lipschitz parameters for $T$-step SGA and $T$-step SNAG in the setting where $f$ is nonconvex-\emph{nonconcave} are all exponential in $T$, the duration of the algorithm. In general, this seems unavoidable in the worst case for the above algorithms and seems to be the case for most of the other popular algorithms such as ADAM, RMSProp etc.~as well. On the other hand, in the nonconvex-\emph{concave} and nonconvex-\emph{strongly concave} settings, our results show that the smoothness parameters of $T$-step SGA are no longer exponential in $T$. In particular, in the nonconvex-\emph{concave} the Lipschitz parameter is linear in $T$ and the gradient Lipschitz parameter is polynomial in $T$ while in the nonconvex-\emph{strongly concave}, the analogous smoothness parameters are no longer dependent on $T$. We conjecture this is also the case for $T$-step SNAG, though the proof appears quite tedious and hence, we opted to leave that for future work. For problems of practical importance, however, we believe that the smoothness parameters are rarely exponential in $T$. Our experimental results confirm this intuition -- see Figure~\ref{fig:grad_norm}. Second, while we prove the Lipschitz and gradient Lipschitz properties only for SGA and SNAG, we believe that the same techniques could be used to prove similar results for several other popular algorithms such as ADAM, RMSProp etc. However, there are other algorithms, particularly those involving projection that are not gradient Lipschitz (see Proposition~\ref{prop:proj} in Appendix~\ref{sec:proj}). \section{Proofs of results in Section~\ref{sec:smoothness}} \label{app:smoothness} In this appendix, we present the proofs for the lemmas in Section~\ref{sec:smoothness}. Recall the SGA update: \begin{align} \label{eqn:SGA} y_{t+1} = y_t + \eta \nabla_y f_{\sigma(t)}(x,y_t). \end{align} Therefore, the Jacobian of the $T$-step SGA update is given by \begin{align}\label{eqn:SGA-grad} D y_{t+1} = \left(I + \eta\nabla_{yy} f_{\sigma(t)}(x,y_t) \right) D y_t + \eta \nabla_{yx} f_{\sigma(t)}(x,y_t), \; \mbox{with} \; \mathcal{A}(x,z) = y_T(x). \end{align} \subsection{Proof of Theorem~\ref{thm:sg-smooth}} \sgsmooth* \begin{proof} \textbf{Lipschitz of $y_t(x)$.} We first show the Lipschitz claim. We have the following bound on the Jacobian of the update equation given in \eqref{eqn:SGA-grad}: \begin{align*} \norm{D y_{t+1}(x)} \le& \norm{(I + \eta\nabla^2_{yy} f(x,y_t(x)) ) D y_t(x)} + \eta \norm{\nabla^2_{yx} f(x,y_t(x))}\\ \le& (1+\eta L) \norm{D y_t(x)} + \eta L. \end{align*} Since $Dy_0(x) = 0$, the above recursion implies that \begin{equation*} \norm{D y_{t}(x)} \le \eta L \sum_{\tau=0}^{t-1} (1+\eta L)^\tau \le (1+\eta L)^t. \end{equation*} \textbf{Gradient-Lipschitz of $y_t(x)$.} Next, we show the claimed gradient Lipschitz constant. As above, using the update equation in \eqref{eqn:SGA-grad}, we have the following bound on the Jacobian: \begin{align*} &\norm{D y_{t+1}(x_1)- Dy_{t+1}(x_2)}\\ \le& \norm{(I + \eta\nabla^2_{yy} f(x_1,y_t(x_1)) )(D y_{t}(x_1)- D y_{t}(x_2))} + \eta \norm{\nabla^2_{yx} f(x_1, y_t(x_1)) - \nabla^2_{yx} f(x_2, y_t(x_2))}\\ &+ \eta \norm{[\nabla^2_{yy} f(x_1, y_t(x_1)) - \nabla^2_{yy} f(x_2, y_t(x_2))] Dy_t(x_2)}\\ \le& (1+\eta L) \norm{Dy_{t}(x_1)-Dy_{t}(x_2)} + \eta \rho (1+\norm{Dy_t(x_2)})(\norm{x_1 - x_2} + \norm{y_t(x_1) - y_t(x_2)})\\ \le & (1+\eta L)\norm{Dy_t(x_1) - Dy_t(x_2)} + 4\eta\rho (1+\eta L)^{2t} \norm{x_1 - x_2}. \end{align*} The above recursion implies the claimed Lipschitz constant. Indeed, \begin{equation*} \norm{D y_{t}(x_1)- Dy_{t}(x_2)} \le 4\eta \rho \sum_{\tau=0}^{t-1} (1+\eta L)^{t+\tau-1} \norm{x_1 - x_2} \le 4 (\rho/L)\cdot(1+\eta L)^{2t} \norm{x_1 - x_2}. \end{equation*} \end{proof} \subsection{Proof of Theorem~\ref{thm:sg-concave}} \sgconcave* \begin{proof} \textbf{Lipschitz of $y_t(x)$.} We first show the Lipschitz claim. Using the update equation in \eqref{eqn:SGA-grad}, we have the following bound on the Jacobian: \begin{align*} \norm{D y_{t+1}(x)} \le& \norm{(I + \eta\nabla^2_{yy} f(x,y_t(x)) ) D y_t(x)} + \eta \norm{\nabla^2_{yx} f(x,y_t(x))}\\ \le& \norm{D y_t(x)} + \eta L. \end{align*} Since $Dy_0(x) = 0$, the above recursive implies that $\norm{D y_{t}(x)} \le \eta L t$. \textbf{Gradient-Lipschitz of $y_t(x)$.} Next, we show the claimed gradient Lipschitz constant. Using the update equation in \eqref{eqn:SGA-grad}:, we have the following bound on the Jacobian: \begin{align*} &\norm{D y_{t+1}(x_1)- Dy_{t+1}(x_2)}\\ \le& \norm{(I + \eta\nabla^2_{yy} f(x_1,y_t(x_1)) )(D y_{t}(x_1)- D y_{t}(x_2))} + \eta \norm{\nabla^2_{yx} f(x_1, y_t(x_1)) - \nabla^2_{yx} f(x_2, y_t(x_2))}\\ &+ \eta \norm{[\nabla^2_{yy} f(x_1, y_t(x_1)) - \nabla^2_{yy} f(x_2, y_t(x_2))] Dy_t(x_2)}\\ \le& \norm{Dy_{t}(x_1)-Dy_{t}(x_2)} + \eta \rho (1+\norm{Dy_t(x_2)})(\norm{x_1 - x_2} + \norm{y_t(x_1) - y_t(x_2)})\\ \le & \norm{Dy_t(x_1) - Dy_t(x_2)} + \eta\rho (1+\eta L t)^{2} \norm{x_1 - x_2}. \end{align*} This recursion implies the following gradient Lipschitz constant: \begin{equation*} \norm{D y_{t}(x_1)- Dy_{t}(x_2)} \le \eta \rho \sum_{\tau=0}^{t-1} (1+\eta L \tau)^2 \norm{x_1 - x_2} \le (\rho/L)\cdot(1+\eta L t)^3 \norm{x_1 - x_2}. \end{equation*} \end{proof} \subsection{Proof of Theorem~\ref{thm:sg-strconcave}} \sgstrconcave* \begin{proof} Denote the condition number $\kappa = L/\alpha$. \textbf{Lipschitz of $y_t(x)$.} We first show the claimed Lipschitz constant. Using the update equation in \eqref{eqn:SGA-grad}, we have that \begin{align*} \norm{D y_{t+1}(x)} \le& \norm{(I + \eta\nabla^2_{yy} f(x,y_t(x)) ) D y_t(x)} + \eta \norm{\nabla^2_{yx} f(x,y_t(x))}\\ \le& (1-\eta \alpha)\norm{D y_t(x)} + \eta L. \end{align*} Since $Dy_0(x) = 0$, the above recursion gives the following bound: \begin{equation*} \norm{D y_{t}(x)} \le \eta L \sum_{\tau=0}^{t-1} (1-\eta \alpha)^\tau \le \kappa. \end{equation*} \textbf{Gradient-Lipschitz of $y_t(x)$.} Next we show the claimed gradient Lipschitz constant. Again, using the update equation, we have that \begin{align*} &\norm{D y_{t+1}(x_1)- Dy_{t+1}(x_2)}\\ \le& \norm{(I + \eta\nabla^2_{yy} f(x_1,y_t(x_1)) )(D y_{t}(x_1)- D y_{t}(x_2))} + \eta \norm{\nabla^2_{yx} f(x_1, y_t(x_1)) - \nabla^2_{yx} f(x_2, y_t(x_2))}\\ &+ \eta \norm{[\nabla^2_{yy} f(x_1, y_t(x_1)) - \nabla^2_{yy} f(x_2, y_t(x_2))] Dy_t(x_2)}\\ \le& (1-\eta \alpha)\norm{Dy_{t}(x_1)-Dy_{t}(x_2)} + \eta \rho (1+\norm{Dy_t(x_2)})(\norm{x_1 - x_2} + \norm{y_t(x_1) - y_t(x_2)})\\ \le & (1-\eta\alpha)\norm{Dy_t(x_1) - Dy_t(x_2)} + 4\eta\rho \kappa^{2} \norm{x_1 - x_2}. \end{align*} This recursion implies that \begin{equation*} \norm{D y_{t}(x_1)- Dy_{t}(x_2)} \le 4\eta \rho \kappa^2 \sum_{\tau=0}^{t-1} (1-\eta \alpha)^\tau \norm{x_1 - x_2} \le 4(\rho/L)\cdot \kappa^3 \norm{x_1 - x_2}. \end{equation*} \end{proof} \subsection{Proof of Theorem~\ref{thm:ag-smooth}} \agsmooth* \begin{proof} Recall the SNAG update \begin{align} \label{eqn:nesterov} \tilde{y}_{t}&=y_{t}+ (1-\theta) (y_{t}-y_{t-1})\\ y_{t+1}&=\tilde{y}_t+\eta \nabla_yf_{\sigma(t)}(x,\tilde{y}_t). \end{align} Observe that the update equation for $T$-step SNAG implies that \begin{equation} \begin{split} D\tilde{y}_{t} &= Dy_{t}+(1-\theta)(Dy_{t}-Dy_{t-1})\\ Dy_{t+1} &=(I+\eta \nabla_{yy} f_{\sigma(t)}(x,\tilde{y}_t) ) D \tilde{y}_t+\eta \nabla_{yx}f_{\sigma(t)}(x,\tilde{y}_t) \end{split} \label{eq:jacsnag} \end{equation} \textbf{Lipschitz of $y_t(x), v_t(x)$.} We first show the claimed Lipschitz constant. By the update equations in \eqref{eq:jacsnag}, we have that \begin{equation*} Dy_{t+1} =(I+\eta \nabla_{yy} f_{\sigma(t)}(x,\tilde{y}_t) ) (Dy_{t}+(1-\theta)(Dy_{t}-Dy_{t-1}))+\eta\nabla_{yx}f_{\sigma(t)}(x,\tilde{y}_t). \end{equation*} Denote $\delta_t = \norm{Dy_t - Dy_{t-1}}$, and note that $Dy_0 = Dy_{-1} = 0$ so that $\delta_0 = 0$. By the equation above, we have that \begin{align*} \delta_{t+1} \le& \eta L \norm{D y_t} + (1+\eta L) (1-\theta) \delta_t + \eta L\\ \le & \eta L \sum_{\tau = 1}^t \delta_\tau + (1+\eta L) (1-\theta) \delta_t + \eta L. \end{align*} In the following, we use induction to prove that \begin{equation} \label{eq:induction_AG} \delta_t \le (1+\eta L/\theta)^t. \end{equation} It is easy to verify that this is true for the base case $\delta_0 = 0 \le 1$. Suppose the claim is true for all $\tau \le t$, then we have that \begin{align*} \delta_{t+1} \le& \eta L \sum_{\tau = 1}^t (1+\eta L/\theta)^{\tau} + (1+\eta L) (1-\theta) (1+\eta L/\theta)^t + \eta L \\ \le& \eta L \sum_{\tau = 0}^t (1+\eta L/\theta)^{\tau} + (1-\theta) (1+\eta L/\theta)^{t+1} \\ =& \theta [(1+\eta L/\theta)^{t+1} - 1] + (1-\theta) (1+\eta L/\theta)^{t+1} \le (1+\eta L/\theta)^{t+1}. \end{align*} This proves the induction claim. Therefore, by \eqref{eq:induction_AG}, we have the following two bounds: \begin{align*} \norm{D y_t(x)} \le& \sum_{\tau = 1}^t \delta_\tau \le t (1+\eta L/\theta)^t, \\ \norm{D \tilde{y}_t(x)} \le& (2-\theta)\norm{D y_t(x)} + (1-\theta)\norm{D y_{t-1}(x)} \le 3t (1+\eta L/\theta)^t. \end{align*} \textbf{Gradient-Lipschitz of $y_t(x)$.} Next, we show the claimed gradient Lipschitz constant. For any fixed $x_1, x_2$, denote $w_t = D y_{t}(x_1)- Dy_{t}(x_2)$, we have \begin{align*} w_{t+1} =& (I+\eta \nabla_{yy} f_{\sigma(t)}(x_1,\tilde{y}_t(x_1)) ) (w_t + (1-\theta)(w_t - w_{t-1})) \\ &+ \underbrace{\eta (\nabla_{yx}f_{\sigma(t)}(x_1,\tilde{y}_t(x_1)) - \nabla_{yx}f_{\sigma(t)}(x_2,\tilde{y}_t(x_2)))}_{T_1} \\ &+ \underbrace{\eta (\nabla_{yy}f_{\sigma(t)}(x_1,\tilde{y}_t(x_1)) - \nabla_{yy}f_{\sigma(t)}(x_2,\tilde{y}_t(x_2)))(Dy_{t}(x_2) + (1-\theta)(Dy_{t}(x_2) - Dy_{t-1}(x_2)))}_{T_2}. \end{align*} We note that we can upper bound the last two terms above as follows: \begin{align*} T_1 + T_2 \le& \eta\rho(\norm{x_1 - x_2} + \norm{\tilde{y}_t(x_1) - \tilde{y}_t(x_2)})\\ &+ \eta \rho(\norm{x_1 - x_2} + \norm{\tilde{y}_t(x_1) - \tilde{y}_t(x_2)})(2\norm{Dy_t(x_2)} + \norm{Dy_{t-1}(x_2)})\\ \le& 24 \eta \rho t^2 (1+\eta L/\theta)^{2t} \norm{x_1 - x_2}. \end{align*} Therefore, let $\zeta_t = \norm{w_t - w_{t-1}}$, and $\Delta = \norm{x_1 - x_2}$, we have the following: \begin{align*} \zeta_{t+1} \le& \eta L \norm{w_t} + (1+\eta L) (1-\theta) \zeta_{t} + 24 \eta \rho t^2(1+\eta L/\theta)^{2t} \Delta\\ \le& \eta L \sum_{\tau = 1}^t \zeta_\tau + (1+\eta L) (1-\theta) \zeta_{t} + 24 \eta \rho t^2(1+\eta L/\theta)^{2t} \Delta. \end{align*} In the following, we use induction to prove that \begin{equation} \label{eq:induction_AG_GL} \zeta_t \le 50(\rho/L)\cdot t^2(1+\eta L/\theta)^{2t} \Delta :=\psi(t). \end{equation} It is easy to verify that this is true for the base case $\zeta_0 = 0 $. Suppose the claim is true for all $\tau \le t$, then we have that \begin{align*} \zeta_{t+1} \le& 50\eta \rho \sum_{\tau = 1}^t \tau^2(1+\eta L/\theta)^{2\tau} \Delta + (1+\eta L) (1-\theta) \psi(t) + 24 \eta \rho t^2(1+\eta L/\theta)^{2t} \Delta\\ \le& \theta(\rho/L)\cdot [50 t^2 \frac{(1+\eta L/\theta)^{2(t+1)} -1}{ (1+\eta L/\theta)^2 - 1}+ 24(\eta L/\theta) t^2 (1+\eta L/\theta)^{2t}]\Delta + (1-\theta) \psi(t+1) \\ \le& \theta(\rho/L)\cdot [25 t^2 (1+\eta L/\theta)^{2(t+1)} + 24 t^2 (1+\eta L/\theta)^{2(t+1)}]\Delta + (1-\theta) \psi(t+1) \\ \le& \theta (\rho/L)\cdot[50 t^2 (1+\eta L/\theta)^{2(t+1)}]\Delta + (1-\theta)\psi(t+1) \le \psi(t+1). \end{align*} This proves the induction claim. Therefore, by \eqref{eq:induction_AG_GL}, we have that \begin{equation*} \norm{D y_{t}(x_1)- Dy_{t}(x_2)} = \norm{w_t} \le \sum_{\tau = 1}^t \zeta_\tau \le 50(\rho/L)t^3 (1+\eta L/\theta)^{2t} \norm{x_1 - x_2}. \end{equation*} \end{proof} \subsection{Projected gradient ascent is not gradient-Lipschitz}\label{sec:proj} \begin{proposition}\label{prop:proj} Consider $f(x,y)=xy$ for $(x,y) \in \mathcal{X} \times \mathcal{Y}$, where $\mathcal{X} = [0,10]$ and $\mathcal{Y} = [0,1]$. $1$-step projected gradient ascent given by: \begin{align*} y_{1}(x) = \mathcal{P}_\mathcal{Y}(y_0 + \eta \nabla_y f(x,y_0)) \quad y_0 = 0, \end{align*} where $\eta > 1/10$ is not a gradient-Lipschitz algorithm. \end{proposition} \begin{proof} We see that $y_1(x) = \min(1,\eta x)$ and $f(x,y_1(x)) = x\min(1,\eta x)$. For $\eta < 1/10$, we see that $f(x,y_1(x))$ is not gradient-Lipschitz at $x=1/\eta \in (0,10)$. \end{proof}
{'timestamp': '2021-06-04T02:06:04', 'yymm': '2106', 'arxiv_id': '2106.01488', 'language': 'en', 'url': 'https://arxiv.org/abs/2106.01488'}
arxiv
\section{Introduction} \label{sec:introduction} Frei et al.~\cite{fre-hem-rot:c:complexity-of-stability} comprehensively studied the problem of how stable certain central graph parameters are when a given graph is slightly modified, i.e., under operations such as adding or deleting either edges or vertices. Given a graph parameter $\xi$ (like, e.g., the independence number or the chromatic number), they formally introduced the problems $\xi$-$\ensuremath{\textsc{Stability}}$, $\xi$-$\ensuremath{\textsc{VertexStability}}$, $\xi$-$\ensuremath{\textsc{Unfrozenness}}$, and $\xi$-$\ensuremath{\textsc{VertexUnfrozenness}}$ and showed that they are, typically, $\ensuremath{\Theta_{2}^{\Pol}}$-complete, that is, they are complete for the complexity class known as ``parallel access to $\ensuremath{\mathrm{NP}}$,'' which was introduced by Papadimitriou and Zachos~\cite{pap-zac:c:two-remarks} and intensely studied by, e.g., Wagner~\cite{wag:j:min-max,wag:j:bounded}, Hemaspaandra et al.~\cite{hem-hem-rot:j:dodgson,hem-spa-vog:j:kemeny}, and Rothe et al.~\cite{rot-spa-vog:j:young}; see the survey by Hemaspaandra et al.~\cite{hem-hem-rot:j:raising-lower-bounds-survey}.\footnote{$\ensuremath{\Theta_{2}^{\Pol}}$ is contained in the second level of the polynomial hierarchy and contains the problems that can be solved in polynomial time by an algorithm that accesses its $\ensuremath{\mathrm{NP}}$ oracle in parallel (i.e., it first computes all its queries and then asks them all at once and accepts its input depending on the answer vector). Alternatively, $\ensuremath{\Theta_{2}^{\Pol}}=\ensuremath{\mathrm{P}}^{\ensuremath{\mathrm{NP}}[\mathcal{O}(\log n)]}$ can be viewed as the class of problems solvable in polynomial time via \emph{adaptively} accessing its $\ensuremath{\mathrm{NP}}$ oracle (i.e., computing the next query depending on the answer to the previous query) logarithmically often (in the input size).} Furthermore, Frei et al.~\cite{fre-hem-rot:c:complexity-of-stability} proved that some more specific versions of these problems, namely $k$-$\chi$-$\ensuremath{\textsc{Stability}}$ and $k$-$\chi$-$\ensuremath{\textsc{VertexStability}}$, are $\ensuremath{\mathrm{NP}}$-complete for $k = 3$ and $\ensuremath{\mathrm{DP}}$-complete for $k \geq 4$, respectively, where $\ensuremath{\mathrm{DP}}$ was introduced by Papadimitriou and Yannakakis~\cite{pap-yan:j:dp} as the class of problems that can be written as the difference of $\ensuremath{\mathrm{NP}}$ problems. Overall, the results of Frei et al.~\cite{fre-hem-rot:c:complexity-of-stability} indicate that these problems are rather intractable and there exist no efficient algorithms solving them exactly. Considering the vast number of real-world applications for these problems mentioned by Frei et al.~\cite{fre-hem-rot:c:complexity-of-stability}---e.g., the design of infrastructure, coloring algorithms for biological networks~\cite{min-urb:j:graph-theory-landscape-connectivity-conservation,kho:j:application-of-graph-coloring-to-biological-networks} or for complex information, social, and economic networks~\cite{jac:b:social-and-economic-networks}, etc.---these results are rather disappointing and unsatisfying. This obstacle motivates us to study whether there are scenarios that allow for efficient solutions to these problems which in general are intractable. Our work is based on the assumption that most of the real-world applications of stability of graph parameters do not use arbitrarily complex graphs but may often be restricted to certain special graph classes. Consequently, our studies show that---despite the completeness results by Frei et al.~\cite{fre-hem-rot:c:complexity-of-stability}---there are tractable solutions to these problems when one limits the scope of the problem to a special graph class. We study seven different classes of special graphs: empty graphs consisting of only isolated vertices and no edges~($\ensuremath{\mathcal{I}}$), complete graphs that have all possible edges~($\ensuremath{\mathcal{K}}$), paths ($\ensuremath{\mathcal{P}}$), trees ($\ensuremath{\mathcal{T}}$), forests ($\ensuremath{\mathcal{F}}$), bipartite graphs ($\ensuremath{\mathcal{B}}$), and co-graphs~($\ensuremath{\mathcal{C}}$). For each such class, we study twelve different problems: \begin{itemize} \item stability, vertex-stability, and unfrozenness \item for the four graph parameters~$\alpha$, $\beta$, $\omega$, and~$\chi$. \end{itemize} In total, we thus obtain the 84 $\ensuremath{\mathrm{P}}$ membership results shown in Table~\ref{tab:results}, which gives the theorem, proposition, or corollary corresponding to each such $\ensuremath{\mathrm{P}}$ result. This can be useful for real-world applications when knowledge about the stability, vertex-stability, or unfrozenness of a graph with respect to a certain graph parameter is required and graphs with such a special structure may typically occur in this application. \begin{table}[t!] \centering \caption{Overview of $\ensuremath{\mathrm{P}}$ results established for seven special graph classes in this paper. E stands for the edge-related problem and V for the vertex-related problem.} \begin{tabular}{l r r @{\quad} c c c c c c c} \toprule &&& $\ensuremath{\mathcal{I}}$ & $\ensuremath{\mathcal{K}}$ & $\ensuremath{\mathcal{P}}$ & $\ensuremath{\mathcal{T}}$ & $\ensuremath{\mathcal{F}}$ & $\ensuremath{\mathcal{B}}$ & $\ensuremath{\mathcal{C}}$ \\ \midrule \multirow{3}{*}{$\alpha$} & \multirow{2}{*}{$\ensuremath{\textsc{Stability}}$} & E & Thm.~\ref{thm:empty-graphs-stability-vertexstability} & Prop.~\ref{prop:complete-graphs-xi-critical} & Thm.~\ref{thm:path-stability-vertexstability} & Cor.~\ref{cor:tree-stability-vertexstability} & Thm.~\ref{thm:forests-stability-vertexstability} & Cor.~\ref{cor:bipartite-stability-vertexstability} & Cor.~\ref{cor:co-graph-alpha-stability} \\ && V & Thm.~\ref{thm:empty-graphs-stability-vertexstability} & Cor.~\ref{cor:complete-graphs-vertexstability} & Thm.~\ref{thm:path-stability-vertexstability} & Cor.~\ref{cor:tree-stability-vertexstability} & Thm.~\ref{thm:forests-stability-vertexstability} & Cor.~\ref{cor:bipartite-stability-vertexstability} & Thm.~\ref{thm:cograph-alpha-vertexstability} \\ & \multicolumn{2}{r@{\quad}}{$\ensuremath{\textsc{Unfrozenness}}$} & Cor.~\ref{cor:empty-graphs-unfrozenness} & Cor.~\ref{cor:complete-graph-unfrozenness} & Prop.~\ref{prop:path-alpha-beta-unfrozenness} & Cor.~\ref{cor:tree-forest-alpha-beta-unfrozenness} & Cor.~\ref{cor:tree-forest-alpha-beta-unfrozenness} & Cor.~\ref{cor:bipartite-alpha-unfrozenness} & Cor.~\ref{cor:co-graph-alpha-beta-unfrozenness} \\ \midrule \multirow{3}{*}{$\beta$} & \multirow{2}{*}{$\ensuremath{\textsc{Stability}}$} & E & Thm.~\ref{thm:empty-graphs-stability-vertexstability} & Prop.~\ref{prop:complete-graphs-xi-critical} & Thm.~\ref{thm:path-stability-vertexstability} & Cor.~\ref{cor:tree-stability-vertexstability} & Thm.~\ref{thm:forests-stability-vertexstability} & Cor.~\ref{cor:bipartite-stability-vertexstability} & Cor.~\ref{cor:co-graph-beta-stability} \\ && V & Thm.~\ref{thm:empty-graphs-stability-vertexstability} & Cor.~\ref{cor:complete-graphs-vertexstability} & Thm.~\ref{thm:path-stability-vertexstability} & Cor.~\ref{cor:tree-stability-vertexstability} & Thm.~\ref{thm:forests-stability-vertexstability} & Cor.~\ref{cor:bipartite-stability-vertexstability} & Cor.~\ref{cor:co-graph-beta-vertex-stability} \\ & \multicolumn{2}{r@{\quad}}{$\ensuremath{\textsc{Unfrozenness}}$} & Cor.~\ref{cor:empty-graphs-unfrozenness} & Cor.~\ref{cor:complete-graph-unfrozenness} & Prop.~\ref{prop:path-alpha-beta-unfrozenness} & Cor.~\ref{cor:tree-forest-alpha-beta-unfrozenness} & Cor.~\ref{cor:tree-forest-alpha-beta-unfrozenness} & Thm.~\ref{thm:bipartite-beta-unfrozenness} & Cor.~\ref{cor:co-graph-alpha-beta-unfrozenness} \\ \midrule \multirow{3}{*}{$\omega$} & \multirow{2}{*}{$\ensuremath{\textsc{Stability}}$} & E & Thm.~\ref{thm:empty-graphs-stability-vertexstability} & Prop.~\ref{prop:complete-graphs-xi-critical} & Thm.~\ref{thm:path-stability-vertexstability} & Cor.~\ref{cor:tree-stability-vertexstability} & Thm.~\ref{thm:forests-stability-vertexstability} & Cor.~\ref{cor:bipartite-stability-vertexstability} & Thm.~\ref{thm:co-graph-omega-stability} \\ && V & Thm.~\ref{thm:empty-graphs-stability-vertexstability} & Cor.~\ref{cor:complete-graphs-vertexstability} & Thm.~\ref{thm:path-stability-vertexstability} & Cor.~\ref{cor:tree-stability-vertexstability} & Thm.~\ref{thm:forests-stability-vertexstability} & Cor.~\ref{cor:bipartite-stability-vertexstability} & Cor.~\ref{cor:co-graph-omega-vertex-stability} \\ & \multicolumn{2}{r@{\quad}}{$\ensuremath{\textsc{Unfrozenness}}$} & Cor.~\ref{cor:empty-graphs-unfrozenness} & Cor.~\ref{cor:complete-graph-unfrozenness} & Prop.~\ref{prop:path-omega-chi-unfrozen} & Prop.~\ref{prop:tree-omega-chi-unfrozenness} & Thm.~\ref{thm:forest-omega-chi-unfrozenness} & Cor.~\ref{cor:bipartite-omega-unfrozenness} & Cor.~\ref{cor:co-graph-omega-unfrozenness} \\ \midrule \multirow{3}{*}{$\chi$} & \multirow{2}{*}{$\ensuremath{\textsc{Stability}}$} & E & Thm.~\ref{thm:empty-graphs-stability-vertexstability} & Prop.~\ref{prop:complete-graphs-xi-critical} & Thm.~\ref{thm:path-stability-vertexstability} & Cor.~\ref{cor:tree-stability-vertexstability} & Thm.~\ref{thm:forests-stability-vertexstability} & Cor.~\ref{cor:bipartite-stability-vertexstability} & Thm.~\ref{thm:co-graph-chi-stability} \\ && V & Thm.~\ref{thm:empty-graphs-stability-vertexstability} & Cor.~\ref{cor:complete-graphs-vertexstability} & Thm.~\ref{thm:path-stability-vertexstability} & Cor.~\ref{cor:tree-stability-vertexstability} & Thm.~\ref{thm:forests-stability-vertexstability} & Cor.~\ref{cor:bipartite-stability-vertexstability} & Thm.~\ref{thm:co-graph-chi-vertex-stability} \\ & \multicolumn{2}{r@{\quad}}{$\ensuremath{\textsc{Unfrozenness}}$} & Prop.~\ref{prop:empty-graphs-chi-unfrozenness} & Cor.~\ref{cor:complete-graph-unfrozenness} & Prop.~\ref{prop:path-omega-chi-unfrozen} & Prop.~\ref{prop:tree-omega-chi-unfrozenness} & Thm.~\ref{thm:forest-omega-chi-unfrozenness} & Thm.~\ref{thm:bipartite-chi-unfrozenness} & Thm.~\ref{thm:co-graph-chi-unfrozenness} \\ \bottomrule \end{tabular} \label{tab:results} \end{table} \section{Preliminaries} \label{sec:preliminaries} We follow the notation of Frei et al.~\cite{fre-hem-rot:c:complexity-of-stability} and briefly collect the relevant notions here (referring to their paper~\cite{fre-hem-rot:c:complexity-of-stability} for further discussion). Let $\ensuremath{\mathcal{G}}$ be the set of all undirected, simple graphs without loops. For $G \in \ensuremath{\mathcal{G}}$, we denote by $V(G)$ its vertex set and by $E(G)$ its edge set; by $\overline{G}$ its complementary graph with $V(\overline{G}) = V(G)$ and $E(\overline{G}) = \{ \{ v, w \} \in V(G) \times V(G) \mid v \neq w \wedge \{ v, w \} \notin E(G) \}$. For $v\in V(G)$, $e\in E(G)$, and $e'\in E(\overline{G})$, let $G-v$, $G-e$, and $G+e'$, respectively, denote the graphs that result from $G$ by deleting~$v$, deleting~$e$, and adding~$e'$. A \emph{graph parameter} is a map $\xi: \mathcal{G}\to\ensuremath{\mathbb{N}}$. We focus on the prominent graph parameters $\alpha$ (the size of a maximum independent set), $\beta$ (the size of a minimum vertex cover), $\chi$ (the chromatic number, i.e., the minimum number of colors needed to color the vertices of a graph so that no two adjacent vertices have the same color), and $\omega$ (the size of a maximum clique). For a graph parameter~$\xi$, an edge $e\in E(G)$ is said to be $\xi$-\emph{stable} if $\xi(G)=\xi(G-e)$, i.e., $\xi(G)$ remains unchanged after $e$ is deleted from~$G$. Otherwise (i.e., if $\xi(G)$ is changed by deleting~$e$), $e$ is said to be $\xi$-\emph{critical}. Stability and criticality are defined analogously for a vertex $v\in V(G)$ instead of an edge $e\in E(G)$. A graph is said to be \emph{$\xi$-stable} if all its edges are $\xi$-stable. A graph whose vertices (instead of edges) are all $\xi$-stable is said to be \emph{$\xi$-vertex-stable}, and \emph{$\xi$-criticality} and \emph{$\xi$-vertex-criticality} are defined analogously. Obviously, each edge and each vertex is either stable or critical, yet a graph might be neither. Traditionally, the analogous terms for stability or vertex-stability when an edge or a vertex is \emph{added} rather than deleted are \emph{unfrozenness} and \emph{vertex-unfrozenness}: They too indicate that a graph parameter does not change by this operation. And if, however, a graph parameter \emph{changes} when an edge or vertex is \emph{added} (not deleted), the notions analogous to criticality and vertex-criticality are simply termed \emph{frozenness} and \emph{vertex-frozenness}. Again, each edge and each vertex is either unfrozen or frozen, but a graph might be neither. For a graph parameter~$\xi$, define $\xi$-$\ensuremath{\textsc{Stability}}$ to be the set of $\xi$-stable graphs; and analogously so for the sets $\xi$-$\ensuremath{\textsc{VertexStability}}$, $\xi$-$\ensuremath{\textsc{VertexCriticality}}$, $\xi$-$\ensuremath{\textsc{Unfrozenness}}$, $\xi$-$\ensuremath{\textsc{Frozenness}}$, and $\xi$-$\ensuremath{\textsc{VertexUnfrozenness}}$. These are the decision problems studied by Frei et al.~\cite{fre-hem-rot:c:complexity-of-stability} for general graphs in terms of their computational complexity. We will study them restricted to the graph classes mentioned in the introduction, formally defined in the subsections of Section~\ref{sec:special-graph-classes}. A graph class $\ensuremath{\mathcal{J}} \subseteq \ensuremath{\mathcal{G}}$ is closed for (induced) subgraphs if for every $G \in \ensuremath{\mathcal{J}}$ it holds that all (induced) subgraphs $H$ of $G$ satisfy $H \in \ensuremath{\mathcal{J}}$. The notation of perfect graphs was originally introduced by Berge~\cite{ber:j:perfect-graphs} in 1963: A graph $G \in \ensuremath{\mathcal{G}}$ is called \emph{perfect} if for all induced subgraphs $H$ of~$G$, we have $\chi(H) = \omega(H)$. Note that $G$ is also an induced subgraph of itself. Let $\ensuremath{\mathrm{P}}$ be the class of problems solvable in (deterministic) polynomial time. For more background on computational complexity (e.g., regarding the complexity classes $\ensuremath{\mathrm{NP}}$, $\ensuremath{\mathrm{DP}}$, and $\ensuremath{\Theta_{2}^{\Pol}}$ mentioned in the introduction; note that $\ensuremath{\mathrm{P}} \subseteq \ensuremath{\mathrm{NP}} \subseteq \ensuremath{\mathrm{DP}} \subseteq \ensuremath{\Theta_{2}^{\Pol}}$ by definition), we refer to the textbooks by Papadimitriou~\cite{pap:b:complexity} and Rothe~\cite{rot:b:cryptocomplexity}. \section{General Stability and Unfrozenness Results} \label{sec:general-stability} In this section, we provide general results that hold for specific graph classes satisfying special requirements. These results can be used to easily determine for a given graph class whether some stability or unfrozenness results are tractable. \begin{theorem} \label{thm:general-efficient-problems} Let $\ensuremath{\mathcal{J}} \subseteq \ensuremath{\mathcal{G}}$ be a graph class closed for induced subgraphs, and $\xi$ a tractable graph parameter for $\ensuremath{\mathcal{J}}$. Then $\xi$-$\textsc{VertexStability} \in \ensuremath{\mathrm{P}}$ for all $G \in \ensuremath{\mathcal{J}}$. \end{theorem} \begin{proofs} Let $G \in \ensuremath{\mathcal{J}}$ and compute $\xi(G)$. For all $v \in V(G)$, we have $G - v \in \ensuremath{\mathcal{J}}$, since $\ensuremath{\mathcal{J}}$ is closed for induced subgraphs. Hence, for all $v \in V(G)$, we can compute $\xi(G - v)$ efficiently and compare it to $\xi(G)$. If there is no vertex such that the values differ, $G$ is $\xi$-vertex-stable. This approach is computable in time polynomial in $|G|$, so that $\xi$-$\textsc{VertexStability} \in \ensuremath{\mathrm{P}}$ for all $G \in \ensuremath{\mathcal{J}}$. \end{proofs} Since every graph class that is closed for subgraphs is also closed for induced subgraphs, Corollary~\ref{cor:induced} is a simple consequence of the previous theorem. \begin{corollary} \label{cor:induced} Let $\ensuremath{\mathcal{J}} \subseteq \ensuremath{\mathcal{G}}$ be a graph class closed under subgraphs and $\xi$ a tractable graph parameter for $\ensuremath{\mathcal{J}}$. Then $\xi$-$\ensuremath{\textsc{VertexStability}} \in \ensuremath{\mathrm{P}}$ for all $G \in \ensuremath{\mathcal{J}}$. \end{corollary} The first theorem made a statement related to vertex-stability about graph classes closed for induced subgraphs. Theorem~\ref{thm:general-closed-subgraph-stability-in-p} is related to edge-stability; its proof is deferred to the appendix, as is the case for most upcoming results. \begin{theorem} \label{thm:general-closed-subgraph-stability-in-p} Let $\ensuremath{\mathcal{J}} \subseteq \ensuremath{\mathcal{G}}$ be a graph class closed under subgraphs and $\xi$ a tractable graph parameter for $\ensuremath{\mathcal{J}}$. Then $\xi$-$\textsc{Stability} \in \ensuremath{\mathrm{P}}$ for all $G \in \ensuremath{\mathcal{J}}$. \end{theorem} Some of the special graph classes we study in the next section are perfect, which is why we now provide some results for perfect graph classes. \begin{theorem} \label{thm:perfect} Let $G \in \ensuremath{\mathcal{G}}$ be a perfect graph. Then it holds that $G$ is $\omega$-vertex-stable if and only if $G$ is $\chi$-vertex-stable. \end{theorem} Based on this result, the next corollary follows immediately. \begin{corollary} \label{cor:perfect-graphs-omega-chi} Let $\ensuremath{\mathcal{J}} \subseteq \ensuremath{\mathcal{G}}$ be a class of perfect graphs. Then, for all graphs in $\ensuremath{\mathcal{J}}$, we have $\chi$-$\ensuremath{\textsc{VertexStability}} = \omega$-$\ensuremath{\textsc{VertexStability}}$. \end{corollary} While the above results are related to the concepts of stability and vertex-stability, the subsequent two results address the topic of unfrozenness. \begin{theorem} \label{thm:general-closed-complement-subgraph-omega-unfrozenness-in-p} Let $\ensuremath{\mathcal{J}} \subseteq \ensuremath{\mathcal{G}}$ be a graph class closed under complements and subgraphs. If $\alpha$ or $\beta$ is tractable for $\ensuremath{\mathcal{J}}$, then $\omega$-$\ensuremath{\textsc{Unfrozenness}} \in \ensuremath{\mathrm{P}}$ for all $G \in \ensuremath{\mathcal{J}}$. \end{theorem} Note that this theorem exploits a relation between $\alpha$- and $\beta$-$\ensuremath{\textsc{Stability}}$ and $\omega$-$\ensuremath{\textsc{Unfrozenness}}$. The next theorem follows by a similar approach, but exploits a relation between $\omega$-$\ensuremath{\textsc{Stability}}$ and $\alpha$- and $\beta$-$\ensuremath{\textsc{Unfrozenness}}$. \begin{theorem} \label{thm:general-other} Let $\ensuremath{\mathcal{J}} \subseteq \ensuremath{\mathcal{G}}$ be a graph class closed under complements and subgraphs. If $\omega$ is tractable for $\ensuremath{\mathcal{J}}$, then $\alpha$- and $\beta$-$\ensuremath{\textsc{Unfrozenness}} \in \ensuremath{\mathrm{P}}$ for all $G \in \ensuremath{\mathcal{J}}$. \end{theorem} \section{Tractability Results for Special Graph Classes} \label{sec:special-graph-classes} Ahead of our results for the individual graph classes, we provide two observations (proven in the appendix) which we will use multiple times in upcoming proofs.\footnote{Note that the second observation is in line with Observation~2 of Frei et al.~\cite{fre-hem-rot:c:complexity-of-stability}.} \begin{observation} \label{obs:vertex-stability-subset-stability} $\chi$-$\textsc{VertexStability} \subseteq \chi$-$\textsc{Stability}.$ \end{observation} \begin{observation} \label{beta-critical-edge-critical-vertices} Let $G \in \ensuremath{\mathcal{G}}$ be a graph. If an edge $\{ u, v \} \in E(G)$ is $\beta$-critical, then $u$ and $v$ are $\beta$-critical, too. \end{observation} With these two observations we can now inspect several graph classes. In the following subsections we study the problems $\xi$-$\ensuremath{\textsc{Stability}}$, $\xi$-$\ensuremath{\textsc{VertexStability}}$, and $\xi$-$\ensuremath{\textsc{Unfrozenness}}$ with $\xi \in \{ \alpha, \beta, \omega, \chi \}$, restricted to special graph classes. Frei et al.~\cite{fre-hem-rot:c:complexity-of-stability} showed that for $\xi \in \{ \alpha, \omega, \chi \}$ we have $\xi$-$\ensuremath{\textsc{VertexUnfrozenness}} = \emptyset$ as well as $\beta$-$\ensuremath{\textsc{VertexUnfrozenness}} = \{ (\emptyset, \emptyset) \}$, where $(\emptyset, \emptyset)$ is the \emph{null graph}, i.e., the graph without vertices or edges. This is why we do not study problems related to vertex-unfrozenness, as all related questions are already answered. \subsection{Empty Graphs} \label{subsec:empty-graphs} Let $I_n = (\{v_1, \ldots, v_n\}, \emptyset)$ denote the \emph{empty graph} with $n \in \ensuremath{\mathbb{N}}$ isolated vertices and $\ensuremath{\mathcal{I}} = \{ I_n \mid n \in \ensuremath{\mathbb{N}} \}$ the set of all empty graphs. \begin{theorem} \label{thm:empty-graphs-stability-vertexstability} It holds that $I_n \in \ensuremath{\mathcal{I}}$ is (1) $\chi$-vertex-stable for $n = 0$ and $n \geq 2$, (2) $\omega$-vertex-stable for $n = 0$ and $n \geq 2$, (3) $\beta$-vertex-stable, (4) $\alpha$-vertex-stable only for $n = 0$, and (5) $\xi$-stable for $\xi \in \{ \alpha, \beta, \chi, \omega \}$. \end{theorem} With the previous theorem we can efficiently decide for every empty graph whether it is $\xi$-stable or $\xi$-vertex-stable for $\xi \in \{\alpha, \beta, \chi, \omega \}$. Furthermore, \cref{thm:empty-graphs-stability-vertexstability} also provides results for the null graph $(\emptyset, \emptyset)$. Therefore, we exclude the null graph from all subsections hereafter in order to decrease redundancy. \begin{proposition}\label{prop:empty-graphs-chi-unfrozenness} The only $\chi$-unfrozen empty graphs are $I_0$ and $I_1$. \end{proposition} The next corollary, which follows from the results in the next subsection, shows that all remaining problems related to unfrozenness are in $\ensuremath{\mathrm{P}}$, too. \begin{corollary}\label{cor:empty-graphs-unfrozenness} $\alpha$-, $\beta$-, and $\omega$-$\ensuremath{\textsc{Unfrozenness}}$ belong to $\ensuremath{\mathrm{P}}$ for empty graphs. \end{corollary} \subsection{Complete Graphs}\label{subsec:complete-graphs} Since we studied empty graphs, it was an immediate consequence that we also study complete graphs. A \emph{complete graph} with $n \in \ensuremath{\mathbb{N}}$ vertices is defined as $K_n = (\{ v_1, \ldots, v_n \}, \{ \{ v_i, v_j \} \mid 1 \leq i < j \leq n \})$ and we denote the set of all complete graphs by $\ensuremath{\mathcal{K}}$. We know that $\ensuremath{\mathcal{I}} \subseteq \beta$-$\ensuremath{\textsc{VertexStability}}$ holds. Together with the first statement of Proposition~6 from \cite{fre-hem-rot:c:complexity-of-stability} we obtain that $\ensuremath{\mathcal{K}} \subseteq \omega$-$\ensuremath{\textsc{VertexCriticality}}$, so every complete graph is $\omega$-vertex-critical. Furthermore, we know that $\ensuremath{\mathcal{I}} \setminus \{ I_1 \} \subseteq \omega$-$\ensuremath{\textsc{VertexStability}}$. Applying the second statement of Proposition~6 from \cite{fre-hem-rot:c:complexity-of-stability}, we obtain that $\ensuremath{\mathcal{K}} \setminus \{ K_1 \} \subseteq \alpha$-$\ensuremath{\textsc{VertexStability}}$ as well as $\ensuremath{\mathcal{K}} \setminus \{ K_1 \} \subseteq \beta$-$\ensuremath{\textsc{VertexCriticality}}$. Consequently, every complete graph which does not possess exactly one vertex is $\beta$-vertex-critical and $\alpha$-vertex-stable. \begin{observation}\label{obs:complete-graphs-chi-vertex-criticality} It holds that $\ensuremath{\mathcal{K}} \subseteq \chi$-$\ensuremath{\textsc{VertexCriticality}}$. \end{observation} So far we know for all parameters $\xi \in \{ \alpha, \beta, \omega, \chi \}$ whether complete graphs are vertex-stable or not, summarized in the subsequent corollary. \begin{corollary}\label{cor:complete-graphs-vertexstability} For every $\xi \in \{\alpha, \beta, \omega, \chi\}$, the problem $\xi$-$\ensuremath{\textsc{VertexStability}}$ belongs to $\ensuremath{\mathrm{P}}$ for complete graphs. \end{corollary} Next, let us take a look at the edge-related stability problems. \begin{observation} For $K_n \in \ensuremath{\mathcal{K}}$, we have $\chi(K_n) = n$, $\alpha(K_n) = 1$, $\beta(K_n) = n - 1$, and $\omega(K_n) = n$. \end{observation} Since $K_0 = I_0$ and $K_1 = I_1$, these cases were already covered in the previous subsection, so the next result is stated only for $n \geq 2$. \begin{proposition}\label{prop:complete-graphs-xi-critical} Let $n \in \ensuremath{\mathbb{N}}$ with $n \geq 2$. Then $K_n$ is $\xi$-critical for $\xi \in \{ \alpha, \beta, \omega, \chi \}$. \end{proposition} We call a complete graph complete because all possible edges (ignoring loops) are present in the graph. Hence, for every $K_n \in \ensuremath{\mathcal{K}}$, we have $\overline{E}(K_n) = \emptyset$, so the next corollary is immediately clear.\footnote{This corollary is in line with \cite[Proposition~5(2)]{fre-hem-rot:c:complexity-of-stability}, as $\ensuremath{\mathcal{I}} = \{ \overline{K_n} \mid n \in \ensuremath{\mathbb{N}} \}$.} \begin{corollary}\label{cor:complete-graph-unfrozenness} For all $\xi \in \{ \alpha, \beta, \omega, \chi \}$, every $K_n \in \ensuremath{\mathcal{K}}$ is $\xi$-unfrozen. \end{corollary} \subsection{Paths}\label{subsec:paths} Denote by $P_n = (\{ v_1, \ldots, v_n \}, \{ \{v_i,v_{i+1}\} \mid 1 \leq i < n \})$ the \emph{path} with $n$ vertices and by $\ensuremath{\mathcal{P}}$ the set of all paths. Again, all proofs are deferred to the appendix. \begin{observation}\label{obs:path-parameters} For $n \geq 2$, we have $\chi(P_0) = 0$, $\chi(P_1) = 1$, and $\chi(P_n) = 2$ and $\omega(P_0) = 0$, $\omega(P_1) = 1$, and $\omega(P_n) = 2$. Additionally, for $n \geq 0$, we have $\beta(P_n) = \lfloor \frac{n}{2} \rfloor$ and $\alpha(P_n) = \lceil \frac{n}{2} \rceil$. \end{observation} Having made this straightforward observation, we can formulate the following stability results for paths. Thereby, $P_0 = (\emptyset, \emptyset)$ is ignored, as argued earlier. \begin{theorem}\label{thm:path-stability-vertexstability} Let $\xi \in \{ \alpha, \beta, \chi, \omega \}$. $P_1$ is $\xi$-stable and $\beta$-vertex-stable but not $\rho$-vertex-stable for $\rho \in \{ \chi, \alpha, \omega \}$. $P_2$ is neither $\xi$-stable nor $\rho$-vertex-stable for $\rho \in \{ \beta, \chi, \omega \}$, but it is $\alpha$-vertex-stable. $P_3$ is $\xi$-stable but not $\xi$-vertex-stable. For $n \geq 4$, $P_n$ is $\chi$- and $\omega$-stable as well as $\chi$- and $\omega$-vertex-stable; it is not $\beta$-vertex-stable; and it is neither $\alpha$-stable nor $\beta$-stable but $\alpha$-vertex-stable if $n$ is even, and it is $\alpha$-stable and $\beta$-stable but not $\alpha$-vertex-stable if $n$ is odd. \end{theorem} This theorem yields for all paths $\ensuremath{\mathcal{P}} \subseteq \ensuremath{\mathcal{G}}$ and $\xi \in \{ \alpha, \beta, \chi, \omega \}$ that $\xi$-$\textsc{Stability}$ and $\xi$-$\textsc{VertexStability}$ are in~$\ensuremath{\mathrm{P}}$. We exclude $P_1 = I_1$ onwards. \begin{observation}\label{obs:path-2-3-unfrozen-frozen} For $\xi \in \{ \alpha, \beta, \omega, \chi \}$, $P_2$ is $\xi$-unfrozen and $P_3$ is $\xi$-frozen. \end{observation} It remains to study the unfrozenness of paths with $n \geq 4$ vertices. \begin{proposition}\label{prop:path-omega-chi-unfrozen} For $n \geq 4$, $P_n$ is neither $\chi$-unfrozen nor $\omega$-unfrozen. \end{proposition} \begin{proposition}\label{prop:path-alpha-beta-unfrozenness} For $n \geq 4$, $P_n$ is neither $\alpha$- nor $\beta$-unfrozen if $n$ is odd, and $P_n$ is $\alpha$- and $\beta$-unfrozen if $n$ is even. \end{proposition} Again, $\xi$-$\ensuremath{\textsc{Unfrozenness}}$ is in~$\ensuremath{\mathrm{P}}$ for all paths $\ensuremath{\mathcal{P}} \subseteq \ensuremath{\mathcal{G}}$ and $\xi \in \{ \alpha, \beta, \chi, \omega \}$. \subsection{Trees and Forests}\label{subsec:trees-forests} We say $G \in \ensuremath{\mathcal{G}}$ is a \emph{tree} (i.e., $G \in \ensuremath{\mathcal{T}}$) if $G$ has no isolated vertices and no cycles of length greater than or equal to~$3$. Furthermore, $G$ is a \emph{forest} (i.e., $G \in \ensuremath{\mathcal{F}}$) if there exist trees $G_1, \ldots, G_n \in \ensuremath{\mathcal{T}}$ such that $G = G_1 \cup \cdots \cup G_n$. For every tree $G \in \ensuremath{\mathcal{T}}$, it holds that $|E(G)| = |V(G)| - 1$ (see, e.g., Bollobás~\cite{bol:b:modern-graph-theory}). So, we have $\omega(G) = \chi(G) = 2$ if $|V(G)| > 1$, and $\omega(G) = \chi(G) = 1$ if $|V(G)| = 1$. Also, there exists a tractable algorithm to determine $\alpha(G)$ for trees (for example, as $\ensuremath{\mathcal{T}} \subseteq \ensuremath{\mathcal{B}}$, we can simply use the algorithm for bipartite graphs from \cref{obs:bipartite-alpha-beta-efficiently}). Thus we can compute $\beta$ for trees using Gallai's theorem~\cite{gal:j:extreme-punkt-kantenmengen} (stated as Theorem~\ref{thm:gallai} in the appendix), and all four graph parameters $\alpha$, $\beta$, $\omega$, and $\chi$ are tractable for trees. Now, let $G \in \ensuremath{\mathcal{F}}$ with $G = G_1 \cup \cdots \cup G_n$ and $G_i \in \ensuremath{\mathcal{T}}$, $1 \leq i \leq n$, be a forest. It is easy to check that $\alpha(G) = \sum_{i=1}^{n} \alpha(G_i)$, $\beta(G) = \sum_{i=1}^{n} \beta(G_i)$, $\omega(G) = \max_{1 \leq i \leq n} \omega(G_i)$, and $\chi(G) = \max_{1 \leq i \leq n} \chi(G_i)$. Furthermore, it is known that the class of forests $\ensuremath{\mathcal{F}}$ is closed under subgraphs and induced subgraphs. From these observations we have the following results (with proofs in the appendix). \begin{theorem} \label{thm:forests-stability-vertexstability} Let $\xi \in \{ \alpha, \beta, \omega, \chi \}$ be a graph parameter. Then the problems $\xi$-$\textsc{Stability}$ and $\xi$-$\textsc{VertexStability}$ are in $\ensuremath{\mathrm{P}}$ for all forests. \end{theorem} With $\ensuremath{\mathcal{T}} \subseteq \ensuremath{\mathcal{F}}$ the next corollary follows immediately. \begin{corollary}\label{cor:tree-stability-vertexstability} For all $G \in \ensuremath{\mathcal{T}}$ and $\xi \in \{ \alpha, \beta, \omega,\chi \}$, the problems $\xi$-$\textsc{Stability}$ and $\xi$-$\textsc{VertexStability}$ belong to $\ensuremath{\mathrm{P}}$. \end{corollary} We now focus on the unfrozenness problems. All trees and forests with fewer than three vertices ($I_1$, $I_2$, and~$P_2$) were already covered in previous sections. It remains to study trees and forests with at least three vertices. \begin{proposition}\label{prop:tree-omega-chi-unfrozenness} Every tree $G \in \ensuremath{\mathcal{T}}$ with $|V(G)| \geq 3$ is neither $\omega$- nor $\chi$-unfrozen. \end{proposition} Based on this result we can deduce whether forests are $\omega$- or $\chi$-unfrozen. As forests without edges are empty graphs, we study forests with at least one edge. \begin{theorem}\label{thm:forest-omega-chi-unfrozenness} If $F \in \ensuremath{\mathcal{F}}$ contains $P_2$ but no $P_3$ as induced subgraphs, $F$ is $\omega$- and $\chi$-unfrozen. If $F$ contains $P_3$ as an induced subgraph, $F$ is not $\omega$- nor $\chi$-unfrozen. \end{theorem} $\alpha$- and $\beta$-$\ensuremath{\textsc{Unfrozenness}}$ are covered in \cref{cor:tree-forest-alpha-beta-unfrozenness} of the next subsection. \subsection{Bipartite Graphs}\label{subsec:bipartite-graphs} $G = (V_1 \cup V_2, E)$ is a \emph{bipartite graph} if $V_1 \cap V_2 = \emptyset$ and $E \subseteq V_1 \times V_2$. Denote the set of all bipartite graphs by~$\ensuremath{\mathcal{B}}$. We begin with two simple observations. Again, most proofs are deferred to the appendix. \begin{observation}\label{obs:bipartite-graph-chi-omega} Let $G \in \ensuremath{\mathcal{B}}$ be a bipartite graph. Then $\chi(G) = \omega(G) = 1$ if $E(G) = \emptyset$, and $\chi(G) = \omega(G) = 2$ if $E(G) \neq \emptyset$. \end{observation} Consequently, we can efficiently calculate $\chi$ and $\omega$ for all bipartite graphs. Next, we describe a tractable method to calculate $\alpha$ and $\beta$ for bipartite graphs. \begin{observation}\label{obs:bipartite-alpha-beta-efficiently} We can calculate $\alpha(G)$ and $\beta(G)$ efficiently for $G \in \ensuremath{\mathcal{B}}$. \end{observation} Hence, we can efficiently calculate $\xi(G)$ for every $G \in \ensuremath{\mathcal{B}}$ and $\xi \in \{ \alpha, \beta, \omega, \chi \}$. Furthermore, as the class of bipartite graphs is closed under subgraphs and induced subgraphs, the following corollary follows from Theorem~\ref{thm:general-efficient-problems}. \begin{corollary}\label{cor:bipartite-stability-vertexstability} For every $\xi \in \{ \alpha, \beta, \omega, \chi \}$, the problems $\xi$-$\ensuremath{\textsc{Stability}}$ and $\xi$-$\ensuremath{\textsc{VertexStability}}$ are in $\ensuremath{\mathrm{P}}$ for all bipartite graphs. \end{corollary} Next, we discuss approaches for how to decide whether a bipartite graph is stable. If a bipartite graph $G$ has no edges, we have $G = I_{|V(G)|}$. For bipartite graphs with one edge, we have the following simple result. \begin{proposition}\label{prop:bipartite-one-edge} Let $G$ be a bipartite graph with $|E(G)| = 1$. Then $G$ is neither $\xi$-stable nor $\xi$-vertex-stable for $\xi \in\{ \alpha, \beta, \omega, \chi \}$. \end{proposition} Next, we provide results for bipartite graphs with more than one edge. \begin{lemma}\label{lem:bipartite-more-edges-chi} Every bipartite graph $G$ with $|E(G)| \geq 2$ is $\chi$-stable. \end{lemma} With Lemma~\ref{lem:bipartite-more-edges-chi} we can characterize $\chi$-vertex-stability. \begin{theorem}\label{thm:bipartite-chi-vertexstability-characterization} Let $G$ be a bipartite graph with $|E(G)| \geq 2$. $G$ is $\chi$-vertex-stable if and only if for all $v \in V(G)$ it holds that $\text{deg}(v) < |E(G)|$. \end{theorem} The proof of the following lemma is similar to that of Lemma~\ref{lem:bipartite-more-edges-chi}. \begin{lemma}\label{lem:bipartite-more-edges-omega} Every bipartite graph $G$ with $|E(G)| \geq 2$ is $\omega$-stable. \end{lemma} With Lemma~\ref{lem:bipartite-more-edges-omega} we also can characterize $\omega$-vertex-stability. \begin{theorem}\label{thm:bipartite-omega-vertex-stable} Let $G$ be a bipartite graph with $|E(G)| \geq 2$. $G$ is $\omega$-vertex-stable if and only if for all $v \in V(G)$ it holds that $\text{deg}(v) < |E(G)|$. \end{theorem} Besides these (vertex-)stability characterizations for bipartite graphs, we now address unfrozenness for them. \begin{theorem}\label{thm:bipartite-chi-unfrozenness} Let $G$ be a bipartite graph. $G$ is $\chi$-unfrozen if and only if $G$ possesses no $P_3$ as an induced subgraph. \end{theorem} \begin{proofs} We prove both directions separately. First, assume $G$ is $\chi$-unfrozen but contains $P_3$ as an induced subgraph. Write $V(P_3) = \{ v_1, v_2, v_3 \}$ and $E(P_3) = \{ \{ v_1, v_2 \}, \{ v_2, v_3 \} \}$ for the corresponding vertices and edges. Then $e = \{ v_1, v_3 \} \in \overline{E}(G)$. However, adding $e$ to $G$ we obtain $\chi(G) = 2 < 3 = \chi(G + e)$, as $P_3 + e$ forms a $3$-clique in~$G$, a contradiction to the assumption that $G$ is $\chi$-unfrozen. Next, assume that $G$ possesses no $P_3$ as an induced subgraph but is not $\chi$-unfrozen. Hence, there must exist $e = \{ u, v \} \in \overline{E}(G)$ such that $\chi(G + e) = 3 > 2 = \chi(G)$. Denote the two disjoint vertex sets of $G$ by $V_1 \cup V_2 = V(G)$. Obviously, $u \in V_1$ and $v \in V_2$ cannot be true, since then $\chi(G + e) = 2$ would hold. Therefore, without loss of generality, we assume $u, v \in V_1$. Adding $e$ to $G$ must create a cycle of odd length in~$G$, as cycles of even length as well as paths can be colored with two colors. Consequently, $G + e$ possesses $C_n$ with $n = 2k + 1 \geq 3$, $k \in \ensuremath{\mathbb{N}}$, as a subgraph. This implies that $G$ must possess $P_3$ as an induced subgraph, again a contradiction. \end{proofs} Slightly modifying (the direction from right to left in) the previous proof yields Corollary~\ref{cor:bipartite-omega-unfrozenness}. This time, adding $e$ to $G$ must create a $3$-clique in~$G$. \begin{corollary}\label{cor:bipartite-omega-unfrozenness} $G \in \ensuremath{\mathcal{B}}$ is $\omega$-unfrozen if and only if $G$ possesses no $P_3$ as an induced subgraph. \end{corollary} Both results show that $\omega$- and $\chi$-$\ensuremath{\textsc{Unfrozenness}}$ belong to $\ensuremath{\mathrm{P}}$ for bipartite graphs. For the last results of this section we require the following lemma. \begin{lemma}\label{lem:bipartite-vertex-cover-with-u} Let $G \in \ensuremath{\mathcal{B}}$ be a bipartite graph and $u \in V(G)$. If $\beta(G - u) = \beta(G) - 1$, then there exists some vertex cover $V' \subseteq V(G)$ with $u \in V'$ and $|V'| = \beta(G)$. \end{lemma} \begin{theorem}\label{thm:bipartite-beta-unfrozenness} For every $G \in \ensuremath{\mathcal{B}}$, the problem $\beta$-$\ensuremath{\textsc{Unfrozenness}}$ belongs to~$\ensuremath{\mathrm{P}}$. \end{theorem} The previous proof allows for every nonedge of a bipartite graph to decide if it is $\beta$-unfrozen such that $\beta$-$\ensuremath{\textsc{Frozenness}} \in \ensuremath{\mathrm{P}}$ follows for $G \in \ensuremath{\mathcal{B}}$. Gallai's theorem~\cite{gal:j:extreme-punkt-kantenmengen} immediately yields $\alpha$-$\ensuremath{\textsc{Unfrozenness}} \in \ensuremath{\mathrm{P}}$ for bipartite graphs. \begin{corollary}\label{cor:bipartite-alpha-unfrozenness} $\alpha$-$\ensuremath{\textsc{Unfrozenness}}$ and $\beta$-$\ensuremath{\textsc{Frozenness}} \in \ensuremath{\mathrm{P}}$ for all $G \in \ensuremath{\mathcal{B}}$. \end{corollary} Since $\ensuremath{\mathcal{T}} \subseteq \ensuremath{\mathcal{F}} \subseteq \ensuremath{\mathcal{B}}$, the next corollary follows as well. \begin{corollary}\label{cor:tree-forest-alpha-beta-unfrozenness} The problems $\alpha$- and $\beta$-$\ensuremath{\textsc{Unfrozenness}}$ as well as the problem $\beta$-$\textsc{Frozenness}$ belong to $\ensuremath{\mathrm{P}}$ for all trees and forests. \end{corollary} \subsection{Co-Graphs}\label{subsec:co-graphs} First of all, we recursively define co-graphs, following a slightly adjusted definition by Corneil et al.~\cite{cor-ler-bur:j:complement-reducible-graphs}. \begin{definition}[co-graph] The graph $G = (\{ v \}, \emptyset)$ is a \emph{co-graph}. If $G_1$ and $G_2$ are co-graphs, then $G_1 \cup G_2$ and $G_1 + G_2$ are co-graphs, too. \end{definition} We denote the set of all co-graphs by $\ensuremath{\mathcal{C}}$ and use the operators $\cup$ and $+$ as is common (see, e.g., \cite{fre-hem-rot:c:complexity-of-stability}). We will use the following result by Corneil et al.~\cite{cor-ler-bur:j:complement-reducible-graphs}. \begin{theorem}\label{thm:cograph-properties} Co-graphs are (i) closed under complements and (ii) closed under induced subgraphs, but (iii) not closed under subgraphs in general. Furthermore, $G \in \ensuremath{\mathcal{G}}$ is a co-graph if and only if $G$ possesses no $P_4$ as an induced subgraph. \end{theorem} Property~(iii) is not proven in their work~\cite{cor-ler-bur:j:complement-reducible-graphs}. However, $C_4\in \ensuremath{\mathcal{C}}$ is an easy example since $C_4$ is a co-graph (see \cref{ex:co-graph-c4} below), and removing one edge yields $P_4$. Since every co-graph can be constructed by $\cup$ and $+$, we can identify a co-graph by its \emph{co-expression}. \begin{example}[co-expression]\label{ex:co-graph-c4} The co-expression $X = (v_1 \cup v_3) + (v_2 \cup v_4)$ describes the graph $C_4 = (\{ v_1, v_2, v_3, v_4 \}, \{ \{ v_1, v_2 \}, \{ v_2, v_3 \}, \{ v_3, v_4 \}, \{ v_4, v_1 \}\})$. \end{example} \begin{figure}[t!] \centering \input{resources/tikz_co-tree-c4} \caption{Co-tree for $C_4$.} \label{fig:co-tree-c4} \end{figure} Obviously, we can build a binary tree for every co-graph via its co-expression. The tree's leaves correspond to the graph's vertices and the inner nodes of the tree correspond to the expression's operations. For example, the tree in \cref{fig:co-tree-c4} corresponds to the co-expression from \cref{ex:co-graph-c4} and, thus, describes a~$C_4$. We call such a tree a \emph{co-tree}. To formulate our results regarding stability and unfrozenness of co-graphs, we need the following result of Corneil et al.~\cite{cor-per-ste:j:linear-recognition-algorithm-cographs}. \begin{theorem}\label{thm:cograph-identify-tree} For every graph $G \in \ensuremath{\mathcal{G}}$, we can decide in $\ensuremath{\mathcal{O}}(|V(G)| + |E(G)|)$ time whether $G$ is a co-graph and, if so, provide a corresponding co-tree. \end{theorem} Combining the previous results with the next one by Corneil et al.~\cite{cor-ler-bur:j:complement-reducible-graphs}, we can efficiently determine a co-graph's chromatic number. \begin{theorem}\label{thm:cograph-chromatic-number} Let $G \in \ensuremath{\mathcal{G}}$ be a co-graph and $T$ the corresponding co-tree. For a node $w$ from~$T$, denote by $G[w]$ the graph induced by the subtree of $T$ with root~$w$. To every leave $v$ of $T$ we add as a label $\chi(G[v]) = 1$. For every inner node $w$ of $T$ we add, depending on the inner node's type, the following label: (1)~If $w$ is a $\cup$-node with children $v_1$ and $v_2$, $\chi(G[w]) = \max \{ \chi(G[v_1]), \chi(G[v_2]) \}$, and (2)~if $w$ is a $+$-node with children $v_1$ and $v_2$, $\chi(G[w]) = \chi(G[v_1]) + \chi(G[v_2])$. If $r$ is the root node of $T$, then it holds that $\chi(G[r]) = \chi(G)$. \end{theorem} A result similar to the previous one for $\alpha$ was given by Corneil et al.~\cite{cor-ler-bur:j:complement-reducible-graphs}. \begin{remark}\label{rem:co-graph-independent-set} We label all leaves of $T$ with $\alpha(G[v]) = 1$. Each inner node $w$ of $T$ with children $v_1$ and $v_2$ is labeled by $\alpha(G[w]) = \max\{ \alpha(G[v_1]), \alpha(G[v_2]) \}$ if $w$ contains the $+$-operation, and by $\alpha(G[w]) = \alpha(G[v_1]) + \alpha(G[v_2])$ if $w$ contains the $\cup$-operation. For the root $r$ of~$T$, it then holds that $\alpha(G[r]) = \alpha(G)$. \end{remark} By the previous remark we can efficiently calculate $\alpha$ for co-graphs. Based on these results, we can state the following theorems whose proofs again are deferred to the appendix. \begin{theorem}\label{thm:co-graph-chi-vertex-stability} For every $G \in \ensuremath{\mathcal{C}}$, the problem $\chi$-$\textsc{VertexStability}$ is in~$\ensuremath{\mathrm{P}}$. \end{theorem} With a similar proof as for the previous theorem, we obtain the next result. \begin{theorem}\label{thm:cograph-alpha-vertexstability} For every $G \in \ensuremath{\mathcal{C}}$, the problem $\alpha$-$\textsc{VertexStability}$ is in $\ensuremath{\mathrm{P}}$. \end{theorem} We can use the same proof as for \cref{thm:cograph-alpha-vertexstability} to obtain the next corollary. However, this time we additionally use Gallai's theorem~\cite{gal:j:extreme-punkt-kantenmengen} to calculate $\beta$ out of $\alpha$ for $G$ and all induced subgraphs with one vertex removed. \begin{corollary}\label{cor:co-graph-beta-vertex-stability} For every co-graph, the problem $\beta$-$\textsc{VertexStability}$ is in $\ensuremath{\mathrm{P}}$. \end{corollary} Although Frei et al.~\cite[Proposition~5(5)]{fre-hem-rot:c:complexity-of-stability} have already shown that the problem $\omega$-$\ensuremath{\textsc{VertexStability}}$ is in $\ensuremath{\mathrm{P}}$ for co-graphs, the next corollary provides an alternative because $\alpha$-$\ensuremath{\textsc{VertexStability}} = \{ \overline{G} \mid G \in \omega\text{-}\ensuremath{\textsc{VertexStability}} \}$ is true and co-graphs are closed under complements. \begin{corollary}\label{cor:co-graph-omega-vertex-stability} For all $G \in \ensuremath{\mathcal{C}}$ the problem $\omega$-$\ensuremath{\textsc{VertexStability}}$ is in $\ensuremath{\mathrm{P}}$. \end{corollary} Next, let us study the edge-related stability problems for co-graphs. To obtain our results, we need the following two auxiliary propositions. \begin{proposition}\label{prop:cograph-critical-vertex-subgraph} Let $G \in \ensuremath{\mathcal{C}}$ with $|V(G)| > 1$ and let $u \in V(G)$ be $\chi$-critical for~$G$. There exist two co-graphs $G_1, G_2$ such that $G = G_1 \cup G_2$ or $G = G_1 + G_2$. Assuming, without loss of generality, that $u \in V(G_1)$, $u$ is $\chi$-critical for~$G_1$. \end{proposition} \begin{proposition}\label{prop:co-graph-critical-vertices-critical-edge} Let $G \in \ensuremath{\mathcal{C}}$ and $e = \{ u, v \} \in E(G)$. If $u$ and $v$ are $\chi$-critical for~$G$, then $e$ is $\chi$-critical for $G$ as well. \end{proposition} Having these results, we are now able to provide our stability-related results. \begin{theorem}\label{thm:co-graph-chi-stability} For all co-graphs, the problem $\chi$-$\textsc{Stability}$ is in $\ensuremath{\mathrm{P}}$. \end{theorem} Next, we want to study the problem of $\omega$-$\textsc{Stability}$ for co-graphs. To do so, we need the following lemmas with their proofs deferred to the appendix. \begin{lemma}\label{lem:co-graph:set-of-cliques} Let $G \in \ensuremath{\mathcal{C}}$ be a co-graph. We can compute \emph{all} cliques of size $\omega(G)$ for $G$ in time polynomial in~$|G|$. \end{lemma} \begin{lemma}\label{lem:co-graph-omega-reduce-by-one} Let $G \in \ensuremath{\mathcal{G}}$ be a graph and $v \in V(G)$ and $e \in E(G)$. Then it holds that $\omega(G - v)$ and $\omega(G - e)$ are in $\{ \omega(G) - 1, \omega(G) \}$. \end{lemma} Having these results, we can show the next theorem. \begin{theorem}\label{thm:co-graph-omega-stability} The problem $\omega$-$\textsc{Stability}$ is in $\ensuremath{\mathrm{P}}$ for co-graphs. \end{theorem} As we now know that we can efficiently determine whether a given co-graph $G$ is $\omega$-stable, we can exploit the fact that co-graphs are closed under complements to obtain the following corollary (whose proof is deferred to the appendix). \begin{corollary}\label{cor:co-graph-alpha-stability} The problem $\alpha$-$\textsc{Stability}$ is in $\ensuremath{\mathrm{P}}$ for co-graphs. \end{corollary} The next result follows from Gallai's theorem~\cite{gal:j:extreme-punkt-kantenmengen} and \cite[Proposition~5]{fre-hem-rot:c:complexity-of-stability}. \begin{corollary}\label{cor:co-graph-beta-stability} The problem $\beta$-$\textsc{Stability}$ is in $\ensuremath{\mathrm{P}}$ for co-graphs. \end{corollary} At this point, we finish the study of stability problems for co-graphs, as all open questions are answered, and turn to the problems related to unfrozenness. The next two corollaries exploit the fact that co-graphs are closed under complements and follow a similar argumentation. \begin{corollary}\label{cor:co-graph-alpha-beta-unfrozenness} The problems $\beta$-$\ensuremath{\textsc{Unfrozenness}}$ and $\alpha$-$\ensuremath{\textsc{Unfrozenness}}$ are in $\ensuremath{\mathrm{P}}$ for co-graphs. \end{corollary} \begin{corollary}\label{cor:co-graph-omega-unfrozenness} The problem $\omega$-$\ensuremath{\textsc{Unfrozenness}}$ is in $\ensuremath{\mathrm{P}}$ for co-graphs. \end{corollary} Finally, we answer the last remaining open question related to unfrozenness and co-graphs. \begin{theorem}\label{thm:co-graph-chi-unfrozenness} The problem $\chi$-$\ensuremath{\textsc{Unfrozenness}}$ is in $\ensuremath{\mathrm{P}}$ for co-graphs. \end{theorem} \section{Conclusion} \label{sec:conclusion} We have provided 84 tractability results regarding the stability, vertex-stability, and unfrozenness problems when restricted to special graph classes. In particular, we studied these three problems for seven important graph classes and four central graph parameters. Doing so, our work provides some baseline for further, more expanding work along this line of research. For future work, we propose to study further special graph classes that are not covered here. Besides the study of stability for other graph classes, one can also study the concept of \emph{cost of stability}:\footnote{Bachrach et al.~\cite{bac-elk-mal-mei-pas-ros-rot-zuc:j:bounds-on-the-cost-of-stabilizing-a-cooperative-game} study a related notion of ``cost of stability'' for cooperative games.} Given a graph, the question is how costly it is to stabilize it. In other words, what is the smallest number of vertices or edges to be added to or removed from the graph such that the resulting graph is stable or unfrozen with respect to some graph parameter. Relatedly, it would make sense to combine these two approaches and study the cost of stability for special graph classes. \section*{Acknowledgments} This work was supported in part by Deutsche Forschungsgemeinschaft under grants RO~1202/14-2 and RO~1202/21-1. \bibliographystyle{splncs04}
{'timestamp': '2021-06-04T02:06:16', 'yymm': '2106', 'arxiv_id': '2106.01496', 'language': 'en', 'url': 'https://arxiv.org/abs/2106.01496'}
arxiv
\section{Introduction} \begin{figure}[t] \centering \includegraphics[width=0.5\textwidth]{./images/salient_citation_graph_example.pdf} \caption{Example of using the citation graph to improve the task of salient entity classification \cite{jain-etal-2020-scirex}. In this task, each entity in the document is classified as salient or not, where a \emph{salient} entity is defined as being relevant to its paper's main ideas.} \label{case_study_example} \end{figure} The rapid expansion in published scientific knowledge has enormous potential for good, if it can only be harnessed correctly. For example, during the first five months of the global COVID-19 pandemic, at least 11000 papers were published online about the novel disease \citep{hallenbeck-2020}, with each representing a potential faster end to a global pandemic and saved lives. Despite the value of this quantity of focused research, it is infeasible for the scientific community to read this many papers in a time-critical situation, and make accurate judgements to help separate signal from the noise. To this end, how can machines help researchers quickly identify relevant papers? One step in this direction is to automatically extract and organize scientific information (e.g. important concepts and their relations) from a collection of research articles, which could help researchers identify new methods or materials for a given task. Scientific information extraction (SciIE) \cite{gupta-manning-2011-analyzing,yogatama-etal-2011-predicting}, which aims to extract structured information from scientific articles, has seen growing interest recently, as reflected in the rapid evolution of systems and datasets \cite{luan-etal-2018-multi,gabor-etal-2018-semeval,jain-etal-2020-scirex}. Existing works on SciIE revolve around extraction solely based on the content of different parts of an individual paper, such as the abstract or conclusion \cite{augenstein-etal-2017-semeval,luan-etal-2019-general}. However, scientific papers do not exist in a vacuum --- they are part of a larger ecosystem of papers, related to each other through different conceptual relations. In this paper, we claim a better understanding of a research article relies not only on its content but also on its relations with associated works, using both the content of related papers and the paper's position in the larger citation network. We use a concrete example to motivate how information from the citation graph helps with SciIE, considering the task of identifying key entities in a long document (known as ``salient entity classification'') in Figure~\ref{case_study_example}. In this example, we see a paper describing a speech recognition system \cite{Saon2016TheI2}. Focusing on two specific entities in the paper (``ImageNet classification challenge" and ``Switchboard task"), we are tasked with classifying whether each is critical to the paper. This task requires reasoning about each entity in relation to the central topic of the paper, which is a daunting task for NLP considering that this paper contains over 3000 words across 11 sections. An existing state-of-the-art model \cite{jain-etal-2020-scirex} mistakenly predicts the \emph{non-salient} entity ``ImageNet classification challenge'' as \emph{salient} due to the limited contextual information. However, this problem is more approachable when informed of the structure of the citation graph that conveys how this paper correlates with other research works. Examining this example paper's position in the surrounding citation network suggests it is concerned with speech processing, which makes it unlikely that ``ImageNet" is salient.\footnote{Our proposed method actually makes correct predictions on both these samples, where the baseline model fails on both.} The clear goal of incorporating inter-article information, however, is hindered by a resource challenge: existing SciIE datasets that annotate papers with rich entity and relation information fail to include their references in a fine-grained, machine-readable way. To overcome this difficulty, we build on top of an existing SciIE dataset and align it with a source of citation graph information, which finally allows us to explore citation-aware SciIE. Architecturally, we adopt the neural multi-task model introduced by \citet{jain-etal-2020-scirex}, and establish a proof of concept by comparing simple ways of incorporating the network structure and textual content of the citation graph into this model. Experimentally, we rigorously evaluate our methods, which we call \emph{CitationIE}, on three tasks: mention identification, salient entity classification, and document-level relation extraction. We find that leveraging citation graph information provides significant improvements in the latter two tasks, including a \textbf{10 point improvement} on F1 score for relation extraction. This leads to a sizable increase in the performance of the end-to-end CitationIE system relative to the current state-of-the-art, \citet{jain-etal-2020-scirex}. We offer qualitative analysis of why our methods may work in \S\ref{Sec:analysis}. \section{Document-level Scientific IE} \subsection{Task Definition} \label{sec:task_definition} We consider the task of extracting document-level relations from scientific texts. Most work on scientific information extraction has used annotated datasets of scientific abstracts, such as those provided for SemEval 2017 and SemEval 2018 shared tasks \cite{augenstein-etal-2017-semeval,gabor-etal-2018-semeval}, the SciERC dataset \cite{luan-etal-2018-multi}, and the BioCreative V Chemical Disease Relation dataset \cite{biocreative}. We focus on the task of open-domain document-level relation extraction from long, full-text documents. This is in contrast to the above methods that only use paper abstracts. Our setting is also different from works that consider a fixed set of candidate relations \citep{hou-etal-2019-identification, kardas-etal-2020-axcell} or those that only consider IE tasks other than relation extraction, such as entity recognition \citep{craft-corpus}. We base our task definition and baseline models on the recently released SciREX dataset \cite{jain-etal-2020-scirex}, which contains 438 annotated papers,\footnote{The dataset contains 306 documents for training, 66 for validation, and 66 for testing.} all related to machine learning research. Each document consists of sections $D = \{S_1, \ldots, S_N\}$, where each section contains a sequence of words $S_i = \{w_{i,1}, \ldots, w_{i, N_i}\}$. Each document comes with annotations of entities, coreference clusters, cluster-level saliency labels, and 4-ary document-level relations. We break down the end-to-end information extraction process as a sequence of these four related tasks, with each task taking the output of the preceding tasks as input. \paragraph{Mention Identification} For each span of text within a section, this task aims to recognize if the span describes a \texttt{Task}, \texttt{Dataset}, \texttt{Method}, or \texttt{Metric} entity, if any. \paragraph{Coreference} This task requires clustering all entity mentions in a document such that, in each cluster, every mention refers to the same entity \cite{Varkel2020PretrainingMR}. The SciREX dataset includes coreference annotations for each \texttt{Task}, \texttt{Dataset}, \texttt{Method}, and \texttt{Metric} mention. \paragraph{Salient Entity Classification} Given a cluster of mentions corresponding to the same entity, the model must predict whether the entity is key to the work described in a paper. We follow the definition from the SciREX dataset \citep{jain-etal-2020-scirex}, where an entity in a paper is deemed salient if it plays a role in the paper's evaluation. \paragraph{Relation Extraction} The ultimate task in our IE pipeline is relation extraction. We consider relations as 4-ary tuples of typed entities $(E_{\texttt{Task}}, E_{\texttt{Dataset}}, E_{\texttt{Method}}, E_{\texttt{Metric}})$, which are required to be salient entities. Given a set of candidate relations, we must determine which relations are contained in the main result of the paper. \begin{figure*}[t] \centering \hspace{-0.6cm} \includegraphics[width=0.85\linewidth]{images/model_architecture_diagram.pdf} \caption{Architecture of the model we use for neural information extraction. Light blue blocks indicate places where we can incorporate information from the citation graph for the citation-aware CitationIE architecture. } \label{model_architecture_diagram} \end{figure*} \subsection{Baseline Model} \label{section:baseline_model} We base our work on top of the model of \citet{jain-etal-2020-scirex}, which was introduced as a strong baseline accompanying the SciREX dataset. We refer the reader to their paper for full architectural details, and briefly summarize their model here This multi-task model performs three of our tasks (mention identification, saliency classification, and relation extraction) in a sequence, treating coreference resolution as an external black box. While word and span representations are shared across all tasks and updated to minimize multi-task loss, the model trains each task on gold input. Figure \ref{model_architecture_diagram} summarizes the baseline model's end-to-end architecture, and highlights the places where we propose improvements for our CitationIE model. \paragraph{Feature Extraction} The model extracts features from raw text in two stages. First, contextualized word embeddings are obtained for each section by running SciBERT \citep{Beltagy2019SciBERTAP} on that section of text (up to 512 tokens). Then, the embeddings from all words over all sections are passed through a bidirectional LSTM \cite{Graves2005BidirectionalLN} to contextualize each word's representation with those from other sections. \paragraph{Mention Identification} The baseline model treats this named entity recognition task as an IOBES sequence tagging problem \cite{Reimers2017OptimalHF}. The tagger takes the SciBERT-BiLSTM \citep{Beltagy2019SciBERTAP, Graves2005BidirectionalLN} word embeddings (as shown in the Figure \ref{model_architecture_diagram}), feeds them through two feedforward networks (not shown in Figure \ref{model_architecture_diagram}), and produces tag potentials at each word. These are then passed to a CRF \cite{Lafferty2001ConditionalRF} which predicts discrete tags. \paragraph{Span Embeddings} For a given mention span, its span embedding is produced via additive attention \citep{Bahdanau2015NeuralMT} over the tokens in the span. \paragraph{Coreference} Using an external model, pairwise coreference predictions are made for all entity mentions, forming coreference clusters. \paragraph{Salient Entity Classification} Saliency is a property of entity clusters, but it is first predicted at the entity mention level. Each entity mention's span embedding is simply passed through two feedforward networks, giving a binary saliency prediction. To turn these mention-level predictions into cluster-level predictions, the predicted saliency scores are max-pooled over all mentions in a coreference cluster to give cluster-level saliency scores. \paragraph{Relation Extraction} The model treats relation extraction as binary classification, taking as input a set of 4 typed salient entity clusters. For each entity cluster in the relation, per-section entity cluster representations are computed by taking the set of that entity's mentions in a given section, and max-pooling over the span embeddings of these mentions. The four entity-section embeddings (one for each entity in the relation) are then concatenated and passed through a feedforward network to produce a relation-section embedding. Then, the relation-section embeddings are averaged over all sections and passed through another feedforward network which returns a binary prediction. \section{Citation-aware SciIE Dataset} Although citation network information has been shown to be effective in other tasks, few works have recently tried using it in SciIE systems. One potential reason is the lack of a suitable dataset. Thus, as a first contribution of this paper, we address this bottleneck by constructing a SciIE dataset that is annotated with citation graph information.\footnote{We have released code to construct this dataset: \url{https://github.com/viswavi/ScigraphIE}} Specifically, we combine the rich annotations of SciREX with a source of citation graph information, S2ORC \citep{lo-etal-2020-s2orc}. For each paper, S2ORC includes parsed metadata about which other papers cite this paper, which other papers are cited by this paper, and locations in the body text where reference markers are embedded. To merge SciREX with S2ORC, we link records using metadata obtained via the Semantic Scholar API:\footnote{\url{https://www.semanticscholar.org/}} paper title, DOI string, arXiv ID, and Semantic Scholar Paper ID. For each document in SciREX, we check against all 81M documents in S2ORC for exact matches on any of these identifiers, yielding S2ORC entries for 433 out of 438 documents in SciREX. The final mapping is included in our repository for the community to use. Though our work only used the SciREX dataset, our methods can be readily extended to other SciIE datasets (including those mentioned in \S\ref{sec:task_definition}) using our released software. \begin{figure}[t] \centering \includegraphics[width=4.0cm]{images/in_degree_histogram.pdf} \includegraphics[width=3.6cm]{images/out_degree_histogram.pdf} \caption{Degree statistics of SciREX documents in the citation graph.} \label{fig:degree_histogram} \end{figure} \paragraph{Statistics} Examining the distribution of citations for all documents in the SciREX dataset (in Figure~\ref{fig:degree_histogram}), we observe a long-tailed distribution of citations per paper, and a bell-shaped distribution of references per paper. In addition to the 5 documents we could not match to the S2ORC citation graph, 7 were incorrectly recorded as containing no references and 5 others were incorrectly recorded as having no citations. These errors are due to data issues in the S2ORC dataset, which relies on PDF parsers to extract information \cite{lo-etal-2020-s2orc}. \section{CitationIE} We now describe our citation-aware scientific IE architecture, which incorporates citation information into mention identification, salient entity classification, and relation extraction. For each task, we consider two types of citation graph information, either separately or together: (1) \textit{structural information} from the graph network topology and (2) \textit{textual information} from the content of citing and cited documents. \subsection{Structural Information} \label{sec:structural_information} The structure of the citation graph can contextualize a document within the greater body of work. Prior works in scientific information extraction have predominantly used the citation graph only to analyze the content of citing papers, such as \emph{CiteTextRank} \citep{citetextrank} and \emph{Citation TF-IDF} \citep{caragea-etal-2014-citation}, which is described in detail in \S\ref{sec:citation_tf_idf}. However, the citation graph can be used to discover relationships between non-adjacent documents in the citation graph; prior works struggle to capture these relationships. \citet{Arnold2009InformationEA} are the only prior work, to our knowledge, to explicitly use the citation graph's structure for scientific IE. They predict key entities related to a paper via random walks on a combined knowledge-and-citation-graph consisting of papers and entities, without considering a document's content. This approach is simple but cannot generalize to new or unseen entities. A rich direction of recent work has studied learned representations of networks, such as social networks \cite{perozzi2014deepwalk} and citation graphs \cite{cora_dataset, Yang2015NetworkRL, Bui2018NeuralGL, comparing_nrl}. In this paper, we show citation graph embeddings can improve scientific information extraction. \paragraph{Construction of Citation Graph} To construct our citation graph, we found all nodes in the S2ORC citation graph within 2 undirected edges of any document in the SciREX dataset, including all edges between those documents. This process took 10 hours on one machine due to the massive size of the full S2ORC graph, resulting in a graph with $\sim$1.1M nodes and $\sim$5M edges. \paragraph{Network Representation Learning} We learn representations for each node (paper) using DeepWalk\footnote{An empirical comparison by \citet{comparing_nrl} found DeepWalk to be quite competitive on two citation graph node classification datasets, despite its speed and simplicity.} \citep{perozzi2014deepwalk} via the GraphVite library \citep{zhu2019graphvite}, resulting in a 128-dimensional ``graph embedding" for each document in our dataset. For each task, we incorporate the document-level graph embedding into that task's model component, by simply concatenating the document's graph embedding with the hidden state in that component. We do not update the graph embedding values during training. \begin{figure}[t] \centering \includegraphics[width=0.7\linewidth]{images/zoomed_in_architecture_diagram_graph.pdf} \caption{Feedforward architecture in each task (with CitationIE-specific parameters shown in light blue).} \label{fig:zoomed_in_model_architecture_graph} \end{figure} \paragraph{Incorporating Graph Embedding} Each task in our CitationIE system culminates in a pair of feedforward networks. Figure \ref{fig:zoomed_in_model_architecture_graph} describes this general architecture, though the input to these networks varies from task to task (SciBERT-BiLSTM embeddings for mention identification, span embeddings for salient entity classification, and per-section relation embeddings for relation extraction). This architecture gives two options for where to concatenate the graph embedding into the hidden state - Stage 1 or Stage 2 - marked with a light blue block in Figure \ref{fig:zoomed_in_model_architecture_graph}. Intuitively, concatenating the graph embedding in a later stage feeds it more directly into the final prediction. We find Stage 1 is superior for relation extraction, and both perform comparably for salient entity classification and mention identification. We give details on this experiment in Appendix \ref{sec:embedding_fusion}. \subsection{Textual Information} Most prior work using the citation graph for SciIE has focused on using the text of citing papers. We examine how to use two varieties of textual information related to citations. \subsubsection{Citances} Citation sentences, also known as ``citances" \citep{Nakov04citances}, provide an additional source of textual context about a paper. They have seen use in automatic summarization \citep{scisummnet}, but not in neural information extraction. In our work, we augment each document in our training set with its citances, treating each citance as a new section in the document. In this way, we incorporate citances into our CitationIE model through the shared text representations used by each task in our system, as shown in Figure \ref{fig:zoomed_in_model_architecture_citances}. If our document has many citations, we randomly sample 25 to use. For each citing document, we select citances centered on the sentence containing the first reference marker pointing to our document of interest, and include the subsequent and consequent sentences if they are both in the same section. \begin{figure}[t] \centering \includegraphics[width=0.7\linewidth]{images/zoomed_in_architecture_diagram_citances.pdf} \caption{Incorporating citances into the text representation extractor.} \label{fig:zoomed_in_model_architecture_citances} \end{figure} We ensure the mention identification step does not predict entities in citance sections, which would lead to false positive entities in downstream tasks. \subsubsection{Citation TF-IDF} \label{sec:citation_tf_idf} \emph{Citation TF-IDF} \citep{caragea-etal-2014-citation}, is a feature representing the TF-IDF value \citep{jones1972statistical} of a given token in its document's citances. We consider a variant of this feature: for each token in a document, we compute the TF-IDF of that token in each citance of the document, and average the per-citance TF-IDF values over all citances. We implemented this feature only for saliency classification, as it explicitly reasons about the significance of a token in citing texts. As a local token-level feature, it also does not apply naturally to relation extraction, which operates on entire clusters of spans. \subsection{Graph Structure and Text Content} We lastly consider using graph embeddings and citances together in a single model for each task. We do this naively by including citances with the document's input text when first computing shared text features, and then concatenating graph embeddings into downstream task-specific components. \section{Experiments} \subsection{Metrics, Baselines and Training} \subsubsection{Metrics} The ultimate product of our work is an end-to-end document-level relation extraction system, but we also measure each component of our system in isolation, giving end-to-end and per-task metrics. All metrics, except where stated otherwise, are the same as described by \citet{jain-etal-2020-scirex}. \paragraph{Mention Identification} We evaluate mention identification with the average F1 score of classifying entities of each span type. \paragraph{Salient Entity Classification} Similar to \citet{jain-etal-2020-scirex} we evaluate this task at the mention level and cluster level. We evaluate both metrics on gold standard entity recognition inputs. \paragraph{Relation Extraction} This is the ultimate task in our pipeline. We use its output and metrics to evaluate the end-to-end system, but also evaluate relation extraction separately from upstream components to isolate its performance. We specifically consider two types of metrics: \noindent (1) \textit{Document-level}: For each document, given a set of ground truth 4-ary relations, we evaluate a set of predicted 4-ary relations as a sequence of binary predictions (where a matching relation is a true positive). We then compute precision, recall, and F1 scores for each document, and average each over all documents. We refer to this metric as the ``\textit{document-level}'' relation metric. To compare with \citet{jain-etal-2020-scirex}, this is the primary metric to measure the full system. \noindent (2) \textit{Corpus-level}: When evaluating the relation extraction component in isolation, we are also able to use a more standard ``\textit{corpus-level}" binary classification evaluation, where each candidate relation from each document is treated as a separate sample. We also run both these metrics on a binary relation extraction setup, by flattening each set of 4-ary relations into a set of binary relations and evaluating these predictions as an intermediate metric. \subsubsection{Baselines} For each task, we compare against \citet{jain-etal-2020-scirex}, whose architecture our system is built on. No other model to our knowledge performs all the tasks we consider on full documents. For the 4-ary relation extraction task, we also compare against the DocTAET model \citep{hou-etal-2019-identification}, which is considered as state-of-the-art for full-text scientific relation extraction \citep{jain-etal-2020-scirex, hou-etal-2019-identification}. \paragraph{Significance} To improve the rigor of our evaluation, we run significance tests for each of our proposed methods against its associated baseline, via paired bootstrap sampling \citep{koehn-2004-statistical}. In experiments where we trained multiple models with different seeds, we perform a hierarchical bootstrap procedure where we first sample a seed for each model and then sample a randomized test set. \subsubsection{Training Details} We build our proposed CitationIE methods on top of the SciREX repository\footnote{\url{https://github.com/allenai/SciREX}} \citep{jain-etal-2020-scirex} in the AllenNLP framework \citep{gardner-etal-2018-allennlp}. For each task, we first train that component in isolation from the rest of the system to minimize the task-specific loss. We then take the best performing modifications and use them to train end-to-end IE models to minimize the sum of losses from all tasks. We train each model on a single GPU with batch size 4 for up to 20 epochs. We include detailed training configuration information in Appendix \ref{sec:training_configurations}. For saliency classification and relation extraction, we trained the baseline and the strongest proposed models three times,\footnote{See Appendix \ref{sec:training_configurations} for exact seeds used} to improve reliability of our results. For mention identification, we did not retrain models, as the first set of results strongly suggested our proposed methods were not helpful. \subsection{Quantitative Results} \paragraph{Mention Identification} For mention identification, we observe no major performance difference from using citation graphs, and include full results in Appendix \ref{sec:mention_identification_results}. \paragraph{Salient Entity Classification} \begin{table}[t] \small \centering \begin{tabular}{lccc} \toprule \textbf{Model} & F1 & P & R \\ \midrule \multicolumn{4}{c}{Salient Mention Evaluation} \\ \midrule Baseline (reported) & 57.9 & 57.5 & 58.4 \\ Baseline (reimpl.) & 57.5 & 50.5 & 66.8 \\ \hdashline \emph{CitationIE} & & & \\ w/ Citation-TF-IDF & 57.1 & 50.2 & 66.1 \\ w/ Citances & 58.7$\dag$ & 51.4 & \textbf{68.5}$\dag$\\ w/ Graph Embeddings & \textbf{59.2}$\dag$ & \textbf{53.5}$\dag$ & 66.3 \\ w/ Graph + Citance & 58.4$\dag$ & 51.3 & 67.8$\dag$\\ \midrule \multicolumn{4}{c}{Salient Entity Cluster Evaluation} \\ \midrule Baseline (reimpl.) & 39.1 & 28.5 & \textbf{75.8} \\ \hdashline \emph{CitationIE} & & & \\ w/ Citation-TF-IDF & 38.6 & 28.4 & 74.3 \\ w/ Citances & 38.7 & 28.2 & 74.8 \\ w/ Graph Embeddings & \textbf{40.3} & \textbf{29.8} & 74.5\\ \bottomrule \end{tabular} \caption{Salient entity classification results. Baseline \citep{jain-etal-2020-scirex} and Graph Embedding model evaluations are each trained with 3 different model seeds, then metrics averaged; rest are from single model due to computational limitations. $\dag$ indicates significance at 95\% confidence. Best model is in bold for each metric. } \label{saliency-results-table} \end{table} \setlength{\tabcolsep}{14pt} \begin{table*}[t] \centering \small \begin{tabular}{lccclccc} \toprule \textbf{Model} & F1 & P & R & & F1 & P & R \\ \midrule & \multicolumn{7}{c}{4-ary Relation Extraction} \\ & \multicolumn{3}{c}{Document-Level Metric} & & \multicolumn{3}{c}{Corpus-Level Metric}\\ \midrule Baseline (reported)\footnotemark & 57.0 & 82.0 & 44.0 & & N/A & N/A & N/A \\ Baseline (reimpl.) & 49.8 & 50.1 & 50.1 & & 48.0 & 48.1 & 48.2 \\ DocTAET & 65.5 & 62.4 & \textbf{85.1} & & 39.9 & 55.7 & 56.8 \\ \hdashline \emph{CitationIE} \\ w/ Citances & \textbf{69.2} & \textbf{70.0} & 76.6 & & 39.4 & 39.9 & 41.9 \\ w/ Graph Embeddings & 68.5 & 67.5 & 76.2 & & \textbf{58.7}$\dag$ & \textbf{61.0}$\dag$ & \textbf{59.6}\\ w/ Graph + Citance & 67.5 & 66.8 & 75.0 & & 51.9 & 54.6 & 54.5 \\ \midrule & \multicolumn{7}{c}{Binary Relation Extraction} \\ & \multicolumn{3}{c}{Document-Level Metric} & & \multicolumn{3}{c}{ Corpus-Level Metric}\\ \midrule Baseline (reported) & 61.1 & 53.1 & 71.8 & & N/A & N/A & N/A \\ Baseline (reimpl.) & 50.8 & 51.1 & 51.1 & & 41.2 & 48.4 & 44.6 \\ \hdashline \emph{CitationIE} \\ w/ Citances & 69.2 & 69.2 & \textbf{71.3} & & 43.3 & 46.7 & 44.0 \\ w/ Graph Embeddings & \textbf{72.9} & \textbf{70.4} & 56.1 & & \textbf{51.0}$\dag$ & \textbf{54.1}$\dag$ & \textbf{57.1} \\ w/ Graph + Citance & 66.2 & 65.9 & 68.1 & & 48.0$\dag$ & 51.4 & 52.7 \\ \bottomrule \end{tabular} \caption{Comparing methods on relation extraction. Baseline, Graph Embedding, and Graph + Citance models were evaluated over 3 model seeds, and the remainder with a single seed. We use Macro-F1 for corpus-level evaluation. $\dag$ indicates significance at 95\% confidence, and best implemented model in each metric is bolded. Graph embeddings significantly improve over baseline on 4-ary and binary corpus-level F1 ($p < 0.05$), but are less significant on document-level F1 metrics ($p \approx 0.11$).} \label{relation-only-table} \end{table*} \footnotetext{ Reported as ``Component-wise Binary and 4-ary Relations" in \citet{jain-etal-2020-scirex}} Table \ref{saliency-results-table} shows the results of our CitationIE methods. We observe:\\ (1) Using citation graph embeddings significantly improves the system with respect to the salient mention metric.\\ (2) Graph embeddings do not improve cluster evaluation significantly (at 95\%) due to the small test size\footnote{The limited size of this test set is an area of concern when using the SciREX dataset, and improving statistical power in SciIE evaluation is a crucial area for future work.} (66 samples) and inter-model variation. \\ (3) Incorporating graph embeddings and citances simultaneously is no better than using either. \\ (4) Our reimplemented baseline differs from the results reported by \citet{jain-etal-2020-scirex} despite using their published code to train their model. This may be because we use a batch size of 4 (due to compute limits) while they reported a batch size of 50. \paragraph{Relation Extraction} Table \ref{relation-only-table} shows that using graph embeddings here gives an 11.5 point improvement in document-level F1 over the reported baseline,\footnote{The large gap between reimplemented and reported baselines is likely due to our reproduced results averaging over 3 random seeds. When using the same seed used by \citet{jain-etal-2020-scirex}, the baseline's document-level test F1 score is almost 20 points better than with two other random seeds. } and statistically significant gains on both corpus-level F1 metrics. Despite seemingly large gains on the document-level F1 metric, these are not statistically significant due to significant inter-model variability and small test set size, despite the graph embedding model performing best at every seed we tried. \paragraph{End-to-End Model} \setlength{\tabcolsep}{10pt} \begin{table}[t] \centering \small \begin{tabular}{llll} \toprule \textbf{Model} & F1 & P & R \\ \midrule & \multicolumn{3}{c}{4-ary Relation Extraction}\\ \midrule Baseline (reported) & 0.8 & 0.7 & 17.3 \\ Baseline (reimpl.) & 0.44 & 0.23 & \textbf{22.66} \\ \hdashline \emph{CitationIE} \\ w/ Graph Embeddings & \textbf{1.48} & 1.31 & 20.04\\ w/ Citances & 0.75 & \textbf{7.03} & 13.36\\ \midrule & \multicolumn{3}{c}{Binary Relation Extraction} \\ \midrule Baseline (reported) & 9.6 & 6.5 & 41.1 \\ Baseline (reimpl.) & 6.48 & 4.09 & 43.83 \\ \hdashline \emph{CitationIE} \\ w/ Graph Embeddings & \textbf{7.70} & \textbf{5.42} & 37.17 \\ w/ Citances & 7.61 & 4.97 & \textbf{43.57} \\\bottomrule \end{tabular} \caption{End-to-end model evaluation. Each model was evaluated over 3 model seeds.} \label{end-to-end-table} \end{table} From Table \ref{end-to-end-table}, we observe:\\ (1) Using graph embeddings appears to have a positive effect on the main task of 4-ary relation extraction. However, these gains are not statistically significant ($p=0.235$) despite our proposed method outperforming the baseline at every seed, for the same reasons as mentioned above. \\ (2) On binary relation evaluation, we observe smaller improvements which had a lower p-value ($p=0.099$) due to lower inter-model variation. \\ (3) Using citances instead of graph embeddings still appears to outperform the baseline (though by a smaller margin than the graph embeddings). \subsection{Analysis} \label{Sec:analysis} We analyzed our experimental results, guided by the following four questions: \paragraph{Do papers with few citations benefit from citation graph information?} Our test set only contains two documents with zero citations, so we cannot characterize performance on such documents. However, Figure \ref{bucketed_eval_on_citation_graph_degree} shows that the gains provided by the proposed CitationIE model with graph embeddings counterintuitively shrink as the number of citations of a paper increases. We also observe this with citances, to a lesser extent. This suggests more work needs to be done to represent citation graph nodes with many edges. \begin{figure}[t] \includegraphics[width=4.1cm]{images/graph_bucketed_by_degree_bigfont.pdf} \hspace{-0.55cm} \includegraphics[width=4.0cm]{images/citances_bucketed_by_degree_bigfont.pdf} \caption{Document-level relation extraction F1 score of CitationIE models with graph embeddings (left) and citances (right), compared with the baseline (red) on documents grouped by number of citations. } \label{bucketed_eval_on_citation_graph_degree} \end{figure} \paragraph{How does citation graph information help relation extraction?} With relation extraction, we found citation graph information provides strongest gains when classifying relations between distant entities in a document, seen in Figure \ref{bucketed_relation_eval_on_cluster_distance}. For each relation in the test set, we computed the average distance between pairs of entity mentions in that relation, normalized by total document length. We find models with graph embeddings or citances perform markedly better when these relations span large swaths of text. This is particularly useful since neural models still struggle to model long-range dependencies effectively \citep{brown2020language}. \begin{figure}[t] \centering \hspace{-0.3cm}\includegraphics[width=4.2cm]{images/graph_bucketed_by_cluster_distance.pdf} \hspace{-0.6cm}\includegraphics[width=4.1cm]{images/citances_bucketed_by_cluster_distance.pdf}\hspace{0.2cm} \caption{Corpus-Level F1 of relation extraction models, bucketed by the average distance between entity mentions in each relation.} \label{bucketed_relation_eval_on_cluster_distance} \end{figure} \paragraph{Does citation graph information help contextualize important terms?} Going back to our motivating example of a speech paper referring to ImageNet in passing \S\ref{case_study_example}, we hypothesized that adding context from citations helps deal with terms that are important in general, but not for a given document. To measure this, we grouped all entities in our test dataset by their ``global saliency rate" measured on the test set: given a span, what is the probability that this span is salient in any given occurrence? \begin{figure}[t] \centering \hspace{-0.3cm}\includegraphics[width=4.3cm]{images/graph_macro_f1_bucketed_by_global_saliency_rate.pdf} \hspace{-0.6cm}\includegraphics[width=4.2cm]{images/citances_macro_f1_bucketed_by_global_saliency_rate.pdf} \caption{Macro F1 of salient mention classification models, evaluated on test-set spans, each bucketed by their training-set global saliency rate.} \label{bucketed_salient_eval_on_global_saliency_rate} \end{figure} In Figure \ref{bucketed_salient_eval_on_global_saliency_rate}, we observe that most of the improvement from graph embeddings and citances comes at terms which are labeled as salient in at least 20\% of their training-set mentions. This suggests that citation graph information yields improvements with reasoning about important terms, without negatively interfering with less-important terms. \section{Implications and Future Directions} We explore the use of citation graph information in neural scientific information extraction with \emph{CitationIE}, a model that can leverage either the structure of the citation graph or the content of citing or cited documents. We find that this information, combined with document text, leads to particularly strong improvements for salient entity classification and relation extraction, and provides an increase in end-to-end IE system performance over a strong baseline. Our proposed methods reflect some of the simplest ways of incorporating citation graph information into a neural SciIE system. As such, these results can be considered a proof of concept. In the future we will explore ways to extract richer information from the graph using more sophisticated techniques, hopefully better capturing the interplay between citation graph structure and content. Finally, we evaluated our proof of concept here on a single dataset in the machine learning domain. While our methods are not domain-specific, verifying that these methods generalize to other scientific domains is important future work. \section*{Acknowledgments} The authors thank Sarthak Jain for assisting with reproducing baseline results, Bharadwaj Ramachandran for giving advice on figures, and Siddhant Arora and Rishabh Joshi for providing suggestions on the paper. The authors also thank the anonymous reviewers for their helpful comments. This work was supported by the Air Force Research Laboratory under agreement number FA8750-19-2-0200. The U.S. Government is authorized to reproduce and distribute reprints for Governmental purposes notwithstanding any copyright notation thereon. The views and conclusions contained herein are those of the authors and should not be interpreted as necessarily representing the official policies or endorsements, either expressed or implied, of the Air Force Research Laboratory or the U.S. Government. \section{Appendices} \subsection{Training Configurations} \label{sec:training_configurations} We train each model on a single 11GB NVIDIA GeForce RTX 2080 Ti GPU with a batch size of 4. We train for up to 20 epochs, and set the \texttt{patience} parameter in AllenNLP to 10; if the validation metric does not improve for 10 consecutive epochs, we stop training early. For each task-specific model, we use a product of validation loss and corpus-level binary F1 score on the validation set as the validation metric. For salient entity classification and relation extraction, we choose the best threshold on the validation set using F1 score. In total, training with these configurations takes roughly 2 hours for salient entity classification, 8 hours for mention identification, 18-24 hours for relation extraction, and 24-30 hours for the end-to-end system. Our CitationIE models took roughly as long to train as the baseline SciREX models did. For models that we trained three different times, we use different seeds for each software library: \begin{itemize} \item For PyTorch, we use seeds 133,\footnote{133/1337/13370 is the default seed setting in AllenNLP.} 11, and 22 \item For Numpy, we use seeds 1337, 111, and 222 \item For Python's \texttt{random} library, we use seeds 11370, 1111, and 2222 \end{itemize} \subsection{Mention Identification Results} \label{sec:mention_identification_results} \setlength{\tabcolsep}{6pt} \begin{table}[h] \centering \small \begin{tabular}{lccc} \toprule \textbf{Model} & F1 & P & R \\ \midrule & \multicolumn{3}{c}{Mention Identification} \\ \midrule Baseline (reported)\footnote{ We used the same evaluation code as the authors, so it is unclear why our evaluation indicate better results} & 70.7 & 71.7 & 71.2 \\ \midrule Baseline (reimpl.) & \textbf{74.6}$\dag$ & 73.7 & \textbf{75.6}$\dag$ \\ w/ Citances & 74.0 & 73.0 & 75.0 \\ w/ Graph Embeddings & 74.4 & \textbf{74.4}$\dag$ & 74.3 \\ w/ Graph + Citance & 73.6 & 73.0 & 74.3 \\ \bottomrule \end{tabular} \caption{Mention Identification Results. $\dag$ indicates significance at 95\% confidence. Best model is in bold for each metric. \label{ner-only-table} } \end{table} We include results from using citation graph information for the mention identification task in Table \ref{ner-only-table}. We observe no major improvements in this task. Intuitively, recognizing a named entity in a document may not require global context about the document (e.g. ``LSTM" almost always refers to a \texttt{Method}, regardless of the paper where it is used), so the lack of gains in this task is unsurprising. \subsection{Combining Graph Embeddings with Word Embeddings} \label{sec:embedding_fusion} Each of our task-specific components in the CitationIE model contains two feedforward networks where we may concatenate graph embedding information. We refer to these two options for where to fuse graph embedding information as "early fusion" and "late fusion", illustrated in Figure \ref{fig:zoomed_in_model_architecture_graph}. Here we show a detailed comparison of early fusion vs late fusion models on Mention Identification (Table \ref{sec:fusion-comparison-ner}), Salient Entity Classification (Table \ref{sec:saliency_classification_fusion_results}), and Relation Extraction (Table \ref{sec:relation-only-fusion-table}). Based on these results, we used early fusion in our final CitationIE models for mention identification and relation extraction. For saliency classification, the relative performance of early fusion and late fusion differed across our two metrics, making this inconclusive. We used early fusion for saliency classification in the end-to-end model due to strong empirical performance there. \label{sec:mention_identification_fusion_results} \setlength{\tabcolsep}{6pt} \begin{table}[h] \centering \small \begin{tabular}{lccc} \toprule \textbf{Model} & F1 & P & R \\ \midrule & \multicolumn{3}{c}{Mention Identification} \\ \midrule Graph Embed. (early fusion) & \textbf{74.4}$\dag$ & \textbf{74.4}$\dag$ & 74.3 \\ Graph Embed. (late fusion) & 74.1 & 73.1 & \textbf{75.1}$\dag$ \\ \bottomrule \end{tabular} \caption{Comparing CitationIE models for mention identification with early graph embedding fusion vs late fusion. Results are shown from single-model evaluation. $\dag$ indicates significance at 95\% confidence. Best model is in bold for each metric. } \label{sec:fusion-comparison-ner} \end{table} \begin{table}[h] \small \centering \begin{tabular}{lccc} \toprule \textbf{Model} & F1 & P & R \\ \midrule \multicolumn{4}{c}{Salient Mention Evaluation} \\ \midrule Graph Embed. (early fusion) & 57.1 & \textbf{54.4}$\dag$ & 60.1 \\ Graph Embed. (late fusion) & \textbf{59.2}$\dag$ & 53.5 & \textbf{66.3}$\dag$\\ \midrule \multicolumn{4}{c}{Salient Entity Cluster Evaluation} \\ \midrule Graph Embed. (early fusion) & \textbf{43.3}$\dag$ & \textbf{33.8}$\dag$ & 72.0 \\ Graph Embed. (late fusion) & 40.3 & 29.8 & \textbf{74.5}$\dag$ \\ \bottomrule \end{tabular} \caption{Comparing CitationIE models for salient entity classification with early graph embedding fusion vs late fusion. The early fusion model was trained once, while late fusion numbers are reported over an average of 3 runs. $\dag$ indicates significance at 95\% confidence. Best model is in bold for each metric. } \label{sec:saliency_classification_fusion_results} \end{table} \setlength{\tabcolsep}{14pt} \begin{table*}[t] \centering \small \begin{tabular}{lccclccc} \toprule \textbf{Model} & F1 & P & R & & F1 & P & R \\ \midrule & \multicolumn{7}{c}{4-ary Relation Extraction} \\ & \multicolumn{3}{c}{Document-Level Metrics} & & \multicolumn{3}{c}{Corpus-Level Metrics}\\ \midrule Graph Embeddings (early fusion) & \textbf{68.5} & \textbf{67.5} & \textbf{76.2} & & 58.7 & 61.0 & 59.6\\ Graph Embeddings (late fusion) & 63.3 & 61.8 & 67.3 & & \textbf{75.8}$\dag$ & \textbf{76.0}$\dag$ & \textbf{76.1}$\dag$ \\ & \multicolumn{7}{c}{Binary Relation Extraction} \\ & \multicolumn{3}{c}{Document-Level Metrics} & & \multicolumn{3}{c}{ Corpus-Level Metrics}\\ \midrule Graph Embeddings (early Fusion) & \textbf{72.9} & \textbf{70.4} & 56.1 & & 51.0 & 54.1 & 57.1 \\ Graph Embeddings (late fusion) & 58.3 & 58.0 & \textbf{59.0} & & \textbf{53.6} & \textbf{58.1}$\dag$ & \textbf{66.4} \\ \bottomrule \end{tabular} \caption{Comparing CitationIE models for relation extraction with early graph embedding fusion vs late fusion. Early fusion models were trained 3 times, late fusion was trained once. $\dag$ indicates significance at 95\% confidence, and the best model in each metric is bolded.} \label{sec:relation-only-fusion-table} \end{table*}
{'timestamp': '2021-06-04T02:09:06', 'yymm': '2106', 'arxiv_id': '2106.01560', 'language': 'en', 'url': 'https://arxiv.org/abs/2106.01560'}
arxiv
\section{Introduction} With the recent breakthrough in computing, a real-world data analysis tends to involve voluminous high-dimensional datasets for modeling various systems with great complexity \citep{reddy2020analysis, zhu2020high}. An increased dimensionality can provide more information about an underlying system, but analyzing a high-dimensional dataset is not an easy task due to the curse of dimensionality \citep{liu2019variable}. That is, for a fixed sample size, data tend to be sparser in spaces characterized by high-dimensional as compared to low-dimensional parameters, so signals are much weaker but noises have far greater impacts, often leading to improper analysis outcomes. A common solution to this problem is to evaluate a data-driven model in a meaningful low-dimensional space by identifying a subset of features that can represent the entire data with a minimal loss of information, e.g., through dimensionality reduction or variable selection \citep{liu2019variable}. Dimensionality reduction extracts inherent features from high-dimensional data and relocates the data in a low-dimensional space constructed by the features, alleviating the curse of dimensionality \citep{van2009dimensionality}. However, existing dimensionality reduction techniques are limited due to the lack of interpretability as the extracted features are ``artificial'' having obscure connections to the original ``physical'' variables \citep{van2009dimensionality}. In engineering applications, identifying important physical variables is crucial for reducing the number of occasions for operational controls or experimental designs used to optimize a system of interest. Although dimensionality reduction can offer low-dimensional evaluation of data, its limited capability restricts its broader usage for system optimization. As an alternative, variable selection, also referred to as subset selection or feature selection, can distinguish important physical variables by extracting a subset of the original variables that are significant \citep{wei2015variable}. Finding an exact optimal subset is computationally intractable, so variable selection typically involves a heuristic search for the subset \citep{fong2013selecting}. A simple heuristic such as a greedy approach cannot ensure the accuracy of the final reduced model, and a complex heuristic such as genetic algorithm is computationally expensive. In addition, while applying a heuristic search, important interactions between physical variables can easily be missed. This paper develops a randomized subspace-based modeling for the purpose of alleviating the curse of dimensionality and providing valuable insight about an underlying system for system optimization. To this end, we model a regression problem as an ensemble of multiple base learners where each base learner is responsible for representing a lower-dimensional input space only; we will refer to this reduced-dimensional physical space as a subspace. The subspace-based modeling is similar to general variable selection approaches as it finds certain subsets of the original variables to achieve dimensionality reduction but differs from them as it leverages multiple distinct subsets and accordingly multiple models to evaluate a function. To balance between model accuracy and computational complexity, we randomly generate subspaces and selectively choose important subspaces. By construction, an important subspace informs that not only the variables therein but also the potential interactions between them are significant. We prescribe the subspaces to be a fixed (low) dimension considering that a high-order interaction exceeding a certain order is rarely significant in practice. By keeping all subspaces at a low dimension, functional evaluation is always performed at a low-dimensional space without a risk of suffering from the curse of dimensionality. The potential of this method to significantly impact our characterization and understanding of advanced engineering systems is demonstrated using the challenging problem of identifying the most influential material properties on damage tolerance for a layered hybrid structure and formulating a reduced order model based on these most sensitive parameters. This example was chosen due to the high dimensional parameter space and wide range of parameter values. Additionally, the high fidelity model used to predict damage tolerance requires a prohibitive amount of computational time to characterize just a small number of parameters in a narrow subspace of the parameter value ranges. The approach presented herein enables a novel method to rapidly reduce and characterize this vast and complex parameter space to solve a challenging physics-based structural mechanics problem. The remainder of this article is organized as follows. Section~\ref{sc:lit_review} reviews relevant studies on dimensionality reduction and important variable selection. Section~\ref{sc:subs_model} presents the proposed subspace-based method by describing model structure, randomized generation and selective extraction of subspaces, and overall learning process. Section~\ref{sc:result} demonstrates the benefits of the proposed method in comparison with others for modeling the damage tolerance of a hybrid material and discusses its potential usages for structural design, analysis, and optimization. Section~\ref{sc:conc} concludes the paper and discusses future work. \section{Literature Review} \label{sc:lit_review} In the past decades, dimensionality reduction has been common in many applications involving a large number of variables, including digital photographs, speech recognition, and bioinformatics \citep{van2009dimensionality}. Dimensionality reduction techniques transform high-dimensional data into a meaningful reduced-dimensional representation, ideally close to its intrinsic dimensions \citep{van2009dimensionality}. The intrinsic dimensions of data are the minimum features needed to account for the observed properties of the data \citep{fukunaga2013introduction}. Traditional dimensionality reduction techniques include Principal Component Analysis (PCA), Independent Component Analysis (ICA), and Multidimensional Scaling (MDS). PCA is one of the most popular linear reduction techniques and dates back to Karl Pearson in 1901 \citep{pearson1901liii}. This technique tries to find orthogonal directions that account for as much variance of data as possible. Due to its attractive advantages of minimal information loss and generation of uncorrelated dimensions, PCA is still popular for use in a broad range of application areas \citep{zou2006sparse}. For example, \citet{li2016evaluating} applied PCA to evaluate energy security of multiple East Asian countries with respect to vulnerability, efficiency, and sustainability. \citet{salo2019dimensionality} proposed a network anomaly detection method based on a reduced dimensionality achieved by combining information gain and PCA. On the other hand, ICA tries to extract independent pieces of information from high-dimensional data, mainly for the purpose of source blind separation that has been popular in signal processing \citep{hastie2009elements}. ICA can be useful in other areas of study; for example, \citet{sompairac2019independent} discussed the benefits of ICA to unravel the complexity of cancer biology, particularly in analyzing different types of omics datasets. Different from PCA and ICA, MDS is a nonlinear dimensionality reduction technique. It provides a useful graphical representation of data based on the similarity information of individual data points. MDS is a common technique for analyzing network-structured data as presented in \citet{saeed2019state} that applied MDS to wireless networks localization. Over the recent decades, many nonlinear or nonparametric dimensionality reduction techniques have been proposed \citep{lee2007nonlinear, saul2006spectral}. Kernel PCA is a reformulation of traditional linear PCA constructing feature space through a kernel function \citep{scholkopf1998nonlinear}. \citet{choi2005fault} found PCA was inefficient and problematic for modeling a nonlinear system but kernel PCA effectively captured nonlinearity while achieving dimensionality reduction. \citet{xu2019software} proposed a defect prediction framework that combined kernel PCA and weighted extreme learning machine to extract representative data features and learn an effective defect prediction model. \citet{tenenbaum2000global} proposed an isometric feature mapping (Isomap) technique that was based on classical MDS but sought to retain the intrinsic geometry of datasets as captured in the geodesic manifold distances. It achieves the goal of nonlinear dimensionality reduction by using easily measured local metric information to learn the underlying global geometry of a data set. \citet{hinton2006reducing} suggested using deep autoencoder networks while transforming high-dimensional data into low-dimensional codes by training a multilayer neural network with a small central layer. They presented that the deep autoencoder networks outperformed PCA with a proper selection of initial weights. \citet{belkina2019automated} introduced $t$-distributed stochastic neighbor embedding (t-SNE), and \citet{gisbrecht2015parametric} presented kernel t-SNE as an extension of t-SNE to a parametric framework, which enabled explicit out-of-sample extensions. They demonstrated that kernel t-SNE yielded satisfactory results for large data sets. \citet{mcinnes2018umap} proposed uniform manifold approximation and projection (UMAP) constructed by a theoretical framework based on Riemannian geometry and algebraic topology. Compared to t-SNE, UMAP arguably preserves more of the global structure. Since UMAP does not have computational restrictions on embedding dimension, it can be easily used for general dimensionality reduction. Even with the theoretical and methodological advance of the dimensionality reduction techniques, they still cannot identify important physical variables among the existing variables; instead, they extract inherent features that are artificial. However, determining important variables is a critical task in many experimental studies, including those for structural mechanics \citep{termaath2018probabilistic}, environmental science, and bioinformatics \citep{wei2015variable}. This is because knowing important variables can suggest which variables to test and optimize for subsequent experiments to reduce the number of experimental trials and hence expedite the overall experimental procedure. In this context, variable selection (or feature selection) that extracts a subset of existing variables is a good alternative to typical dimensionality reduction. It is capable of maintaining the original variable structure while reducing the dimensionality. Feature selection methods are typically classified into three groups of filter methods, wrapper methods, and embedded methods \citep{chandrashekar2014survey}. Filter methods evaluate each variable based on some ranking criteria, such as Pearson correlation coefficient \citep{battiti1994using} or mutual information \citep{torkkola2003feature}. Wrapper methods, evaluating different subsets of variables by using a learning algorithm, generally provide better performance compared to filter methods \citep{xue2015survey}. To determine the subsets of variables subject to evaluation, an exhaustive search (rarely used) requires considering $2^n$ different feature combinations when there are $n$ variables, which is impractical. Instead, sequential forward selection \citep{whitney1971direct} and sequential backward selection \citep{marill1963effectiveness} algorithms that apply greedy search have been used broadly. More recently, sequential floating forward selection \citep{pudil1994floating} and adaptive sequential floating forward selection \citep{somol1999adaptive} have been proposed to alleviate poor performance of the greedy search. However, these sequential selection methods still suffer from a nesting problem caused by the nature of the greedy search, so the selection outcome is generally far from the optimum. To overcome the nesting problem, heuristic search methods, e.g., based on genetic algorithm \citep{alexandridis2005two}, have been proposed. These wrapper methods, however, require an extensive amount of computation and are prone to overfitting \citep{chandrashekar2014survey}. Embedded methods aim to alleviate the computational cost of wrapper methods by integrating feature selection and model learning into a single process \citep{xue2015survey}. In other words, some ranking criteria, such as max-relevancy min-redundancy \citep{peng2005feature} and the weights of a classifier \citep{mundra2009svm}, are used for the initial feature reduction, and then wrapper methods are applied for the final feature selection. These days, machine learning methods, such as random forest (RF) \citep{chen2020selecting} and neural network (NN) \citep{olden2004accurate}, have been used to measure variable importance and rank variables based on model's prediction accuracy. \citet{gregorutti2017correlation} explored the usage of RF in the presence of correlated predictors. Their results motivated the use of the recursive feature elimination (RFE) algorithm using permutation importance measure as a ranking criterion. \citet{chen2020selecting} compared results from three popular datasets (bank marketing, car evaluation database, human activity recognition using smartphones) with and without feature selection based on multiple method, including RF and RFE. The experimental results demonstrated that RF achieved the best performance in all experimental groups. On the other hand, \citet{olden2004accurate} compared nine variants of artificial neural network (ANN) for quantifying variable importance using simulated data. For this comparison, the true importance of variables was known and used for verification. Their results showed connection weight approach (CWA) provided the best accuracy and CWA was the only method that correctly identified the rank of variable importance. \citet{liu2019variable} presented a deep Baysian rectified linear unit (ReLU) network for high-dimensional regression and variable selection. The result showed their method outperformed existing classic and other NN-based variable selection methods. Although these variable selection methods provide an efficient tool to extract important variables, they primarily focus on the importance of individual variables, with little consideration for the importance of feature interactions. In a general experimental problem, however, knowledge about the significance of feature interactions is a critical factor for designing experiments. Instead of finding important individual variables, our approach aims to identify critical subspaces, each of which presents which variable combination as a whole (including interactions) is important. For the exploration of potentially important subspaces, a randomized search is employed to improve model accuracy and computational efficiency relative to a greedy search and a metaheuristic search, respectively. Furthermore, our method leverages multiple subsets of variables (subspaces) for model construction instead of relying on a single subset as the existing methods do, which can provide a more flexible model. The details of the proposed method will be discussed in the subsequent sections. \section{Subspace-Based Modeling and Critical Subspaces} \label{sc:subs_model} In this section, we develop randomized subspace-based modeling for solving a general supervised learning problem and identifying critical variables and interactions. The dataset of interest contains data pairs of $\{\mathbf{x}_i, y_i\}_{i=1}^n$ where $\mathbf{x}_i$ is a $p$-dimensional input vector and $y_i$ is the corresponding response. For subspace-based modeling, we form a subspace, a space spanned by a subvector of input $\mathbf{x}$, determine the significance of a subspace for modeling response, and use such a critical subspace as a basic unit for model building. A critical subspace implies that the variables forming the space and their interactions are important, so it naturally extracts important variables and interactions. In the following sections, we describe the proposed model structure, the randomized search for generating subspaces, the significance evaluation of a subspace, and the overall model learning process. \subsection{Subspace-based model} Considering a general supervised learning problem, we estimate a function $f:\mathbb{R}^p \rightarrow \mathbb{R}$ that relates $p$-dimensional input $\mathbf{x}$ and output $y$ as $y=f(\mathbf{x})+\varepsilon$ where $\varepsilon$ is an additive noise. We model the unknown function $f$ as an additive mixture of subfunctions $g_j:\mathbb{R}^k \rightarrow \mathbb{R}$ for $j=1,\ldots, J$ defined in a lower dimensional space of dimension $k\ll p$, instead of estimating the full-dimensional function directly, as \begin{equation} y = f(\mathbf{x}) + \varepsilon \approx g_1(\mathbf{z}_1) + g_2(\mathbf{z}_2) + ... + g_J(\mathbf{z}_J) + \varepsilon, \label{eq:model} \end{equation} where $\mathbf{z}_j$ is the $j$th subvector of $\mathbf{x}$ of size $k$. Each $\mathbf{z}_j$ for $j=1,\ldots,J$ takes different components of $\mathbf{x}$. For example, suppose $k=3$ and $\mathbf{x} = \begin{bmatrix} x_1, x_2, \ldots, x_p \end{bmatrix}^T $ where $p > 20$. Then, we may have $\mathbf{z}_1 = \begin{bmatrix} x_3, x_8, x_{12} \end{bmatrix}^T$ and $\mathbf{z}_2 = \begin{bmatrix} x_7, x_{11}, x_{20} \end{bmatrix}^T$. We define a reduced-dimensional space spanned by each subvector $\mathbf{z}_j$ as a subspace, and $g_j$ estimates the response $y$ within a subspace formed by $\mathbf{z}_j$. As such, in Eq.~\eqref{eq:model}, we model the function $f$ as a mixture of subspace-based models. The advantage of the subspace-based modeling is obvious. By evaluating $y$ in low-dimensional subspaces, there is no risk of suffering from the curse of dimensionality, which is not true when evaluating $y$ in a single high-dimensional space. Different from general dimensionality reduction methods, the subspace-based modeling does not require extracting artificial dimensions, but the reduction of dimensionality is achieved by forming low-dimensional physical spaces, which can provide physical interpretation of the model. One major shortcoming of the subspace-based modeling is that it is not capable of modeling interactions of an order higher than $k$. However, in many real-world problems, a high-order interaction is almost negligible in modeling response. From a preliminary study, we found that $k=3$, i.e., modeling up to 3-factor interactions, provided good prediction results. The key to the success in the subspace-based modeling lies in how to form the subspaces, i.e., how to generate the subvectors of $\mathbf{z}_j$ for $j=1,\ldots,J$. For an exhaustive search, if we assume $p=41$ and $k=3$, the number of all subspace candidates is ${41 \choose 3} = 10660$. Evaluating models for this many subspaces and determining whether to include each of them requires a considerable amount of computation (still, much smaller compared to $2^{41}$ for an exhaustive search for the optimal subset). On the other hand, simple feature selection techniques, such as greedy forward selection and greedy backward selection, are limited in terms of the exploration capability. In the next section, we discuss how to generate subspaces and how to extract critical subspaces. \subsection{Subspace generation and extraction} To explore a broad area covering potential subspace configurations and not to rely on a greedy search, we generate subspaces randomly. In particular, at each draw, we randomly choose $k$ variables out of $p$ variables (full-dimension) and evaluate whether to include this randomly generated subspace into the model or not. For each random draw, we apply sampling without replacement, but we allow duplicated selection of a single variable at multiple draws. In other words, an input variable $x_1$ could be a part of subspace $\mathbf{z}_1$, and the variable can be chosen again at later draws for $\mathbf{z}_j$ for $j>1$. This is to ensure that multiple interactions associated with a key variable are not lost and all of them can be used for modeling the response as long as they have significant impacts. We determine the significance of a randomly generated subspace by evaluating the percentage reduction in the prediction error with respect to root mean square error (RMSE). To evaluate out-of-sample prediction error and avoid possible overfitting, we apply 5-fold cross validation (CV) to calculate the error. This 5-fold CV is applied to the dataset assigned for model learning (excluding testing portion), and the dataset is split into 5 small subsets of the data. Each subset can serve as a validation dataset whereas the remaining four subsets collectively can be used to train a model. In this way, we can generate 5 different train/validation combinations of data, for each of which train and validation portions account for 80\% and 20\% of the dataset, respectively, as shown in Fig.~\ref{fig:extraction}. \begin{figure}[b!] \centering \includegraphics[width=\textwidth]{Figure1.pdf} \caption{A flow chart describing the process of subspace generation and extraction } \label{fig:extraction} \end{figure} To test the significance, a temporary subspace-based model ($g_t$) for a randomly generated subspace ($\mathbf{z}_t$) will be added into the model, and the prediction error of this extended model will be evaluated in terms of the out-of-sample RMSE. The temporary subspace-based model, $g_t$ where $t$ denotes the current iteration number for the subspace generation, is learned for each of the five different train datasets, and the prediction error of the extended model including $g_t$ is calculated by using the corresponding five validation datasets. This will produce $RMSE_{t,q}$ for $q=1,\ldots,5$ for each train/validation split at iteration $t$. To be specific, the RMSE is calculated as \begin{equation} RMSE_{t,q} = \sqrt{\frac{1}{n_{v_q}}\sum_{\{\mathbf{x}_i, y_i\} \in \mathcal{V}_q}{(y_i - \tilde{f}_t(\mathbf{x}_i))^2}} \end{equation} where $\mathcal{V}_q$ is the validation dataset for the $q$th train/validation split and $n_{v_q}$ is the number of observations in the validation dataset. $\tilde{f}_t(\mathbf{x}_i) = \sum_{j \in \mathcal{J}^*} g_j(\mathbf{z}_j) + g_t(\mathbf{z}_t)$ where $\mathcal{J}^*$ is the set of indices for the selected critical subspaces until the previous iteration. The CV score is then the average of the five prediction errors, i.e., \begin{equation} CV_t =\frac{1}{5} \sum_{q=1}^{5} RMSE_{t,q}. \label{eq:cv} \end{equation} We use the percentage reduction of the prediction error for the selection of a critical subspace and also for the termination of the iterative search for new subspaces. The percentage error reduction is defined as \begin{equation} \Delta e = \frac{CV^* - CV_t}{CV^*} \label{eq:epr} \end{equation} where $CV^*$ is the minimum (best) CV score in Eq.~\eqref{eq:cv} obtained until the previous iteration. The initial value of $CV^*$ is calculated from a model that only includes a constant term (the average of the five sample means of $y_i$'s in each training dataset). For the selection of a critical subspace, we set a selection threshold $\eta$, and if \(\Delta e>\eta\), the subspace generated at the $t$th iteration is accepted and included in the model. This means that a subspace that reduces the prediction error at least by a certain percentage will be included in the model. Otherwise, this subspace is disregarded. The search for a new subspace continues until the percentage reduction \(\Delta e\) becomes less than a termination threshold, \(\tau\). In other words, if \(\Delta e<\tau\), the subspace searching process terminates. If none of the selection criterion and the termination criterion are met, the iterative search continues for the next possible critical subspace. Fig.~\ref{fig:extraction} illustrates the overall process of the subspace generation and extraction. \subsection{Subspace model learning and hyperparameter selection} \label{ssc:hyppar} This section describes how to estimate each subspace-based model $g_t$. For this estimation, we use a randomly generated subvector, $\mathbf{z}_t$ as predictors and the current residual calculated before the iteration $t$ as a response to estimate, i.e., using $\tilde{y}_{t,i} = y_i - \sum_{j \in \mathcal{J}^*} g_j(\mathbf{z}_j)$ for $i=1,\ldots,n$ for response. In other words, we consider a regression problem written as \begin{equation} \tilde{y}_{t,i} = g_t(\mathbf{z}_{t,i}) + \tilde{\varepsilon}_{t,i} \label{eq:resid_model} \end{equation} where $\mathbf{z}_{t,i}$ is a subvector of $\mathbf{x}_{i}$, and $\tilde{\varepsilon}_{t,i}$ is a modified noise for $i=1,\ldots,n$. To learn the function $g_t$, we use support vector machine (SVM) as a base learner. It is a supervised learning method which can be used for classification and regression. For a regression analysis, it is also known as support vector regression (SVR). To train a model based on SVR, we use ``$\epsilon$-insensitive'' error function which is a symmetric loss function. For this function, a flexible tube with the radius of $\epsilon$ is formed symmetrically around the estimate. Errors of size less than \(\epsilon\) are ignored, and overestimation and underestimation are penalized equally. This means that some penalty is assigned only to the points outside the tube based on the distance between the points and the tube, but no penalty is applied to the points within the tube \citep{awad2015support}. For SVR, the function $g_t$ can be expressed as a linear combination of basis functions, $h_m$ for $m=1,\ldots,M$, as \begin{equation} g_t(\mathbf{z}_t) = \sum_{m=1}^M{\beta_m h_m(\mathbf{z}_t)} + \beta_0, \end{equation} where $\beta_m$ for $m=1,\ldots,M$ is a coefficient of each basis function and $\beta_0$ is a constant. To estimate $g_t$, we minimize \begin{equation} \begin{split} H(\bm{\beta}, \beta_0) &= \sum_{i=1}^n{V_\epsilon(\tilde{y}_{t,i} - \hat{g}_t(\mathbf{z}_{t,i}))} + \frac{\lambda}{2}\sum_{m=1}^M{\beta_m^2} \\ &\text{where} \; V_\epsilon(r) = \begin{cases} 0, & \text{if} \; |r|<\epsilon, \\ |r| - \epsilon, & \text{otherwise}. \end{cases} \end{split} \label{eq:obj} \end{equation} where $\bm{\beta} = \begin{bmatrix} \beta_1, \ldots, \beta_M \end{bmatrix}^T$ is a coefficient vector, and $\lambda$ is a regularization parameter. The minimizer of Eq.~\eqref{eq:obj} provides the estimate of $g_t$ in the form of \begin{equation} \hat{g}_t(\mathbf{z}) = \sum_{i=1}^n{\alpha_i}K_t(\mathbf{z}, \mathbf{z}_{t,i}). \end{equation} where $\alpha_i$ for $i=1,\ldots,n$ is a Lagrangian dual variable for the Lagrangian primal shown in Eq.~\eqref{eq:obj}, and $K_t(\cdot,\cdot)$ is a kernel function that represents the inner product of the unknown basis functions, $h_m$ for $m=1,\ldots,M$ \citep{hastie2009elements}. To fully specify the estimate of $g_t$, some hyperparameters need to be determined. This includes the regularization parameter, $\lambda$ (related to the cost parameter in a typical SVM), the radius of the tube, $\epsilon$, for the loss function, and some kernel related parameters. For this hyperparameter learning, we apply grid search based on generalized cross-validation (GCV) criterion. The proposed method already employs 5-fold CV for the selection of critical subspaces and the termination of the iterative search, so another layer of out-of-sample prediction will complicate the data structure, and the training process may suffer from the lack of a sufficient number of data points. While measuring in-sample error using training data only, GCV provides a convenient approximation to the leave-one-out CV \citep{hastie2009elements}, so it is a proper criterion for the hyperparameter learning of the proposed method. In general, GCV is calculated as \begin{equation} GCV(\hat{f}) = \frac{1}{n}\sum_{i=1}^{n} \Big[\frac{y_i- \hat{f}(\mathbf{x}_i)}{1-\text{trace}(\mathbf{S})/n)}\Big]^2 \label{eq:gcv} \end{equation} where $\mathbf{S}$ is an $n\times n$ hat matrix that performs a linear projection of $\mathbf{y}=\begin{bmatrix} y_1, \ldots, y_n \end{bmatrix}^T$ to achieve the estimate of $\mathbf{y}$, i.e., $\hat{\mathbf{y}} = \mathbf{S y}$. For the proposed subspace-based model in Eq.~\eqref{eq:model}, deriving this expression of linear projection is not straightforward. Theorem~\ref{thm:trace} shows a good approximation of $\mathbf{S}$ that can be derived under the assumption of a squared loss function. \begin{theorem} Assuming a squared loss function, i.e., $V_\epsilon(r) = r^2$, the estimate of the response $\mathbf{y}$ can be expressed as $\hat{\mathbf{y}} = \mathbf{S y} = (\sum_{j=1}^J{\mathbf{S}_j})\mathbf{y}$ where $\mathbf{S}_j = \mathbf{S}_j^\prime (\mathbf{I} - \sum_{l=0}^{j-1}{\mathbf{S}_l})$, $\mathbf{S}_j^\prime = \mathbf{K}_j(\mathbf{K}_j + \lambda \mathbf{I})^{-1}$, $\mathbf{S}_0 = \mathbf{0}$, $\mathbf{I}$ is an $n\times n$ identity matrix, and $\mathbf{K}_j$ is an $n\times n$ kernel matrix with $\{\mathbf{K}_j\}_{i, i^\prime} = K_j(\mathbf{z}_{j,i}, \mathbf{z}_{j,i^\prime})$ for $i, i^\prime =1,\ldots,n$. \label{thm:trace} \end{theorem} \begin{proof} From Eq.~\eqref{eq:model}, we define $\mathbf{S}_j \mathbf{y}$ for $j=1,\ldots,J$ to represent $g_j(\mathbf{z}_{j,i})$ as a linear combination of $y_i$'s so that we have \begin{equation} \hat{\mathbf{y}} = \mathbf{S}_1 \mathbf{y} + \mathbf{S}_2 \mathbf{y} + \cdots + \mathbf{S}_J \mathbf{y}. \end{equation} Since each $g_j$ estimates residuals from a model including up to the previous subspace-based model ($g_{j-1}$), we have $\tilde{y}_{j,i} = g_j(\mathbf{z}_{j,i}) + \tilde{\varepsilon}_{j,i}$ (as in Eq.~\eqref{eq:resid_model}). For an SVR with a squared loss function, the estimation can be expressed as $\widehat{\tilde{\mathbf{y}}}_j=\mathbf{S}_j^\prime \tilde{\mathbf{y}}_j = \mathbf{K}_j (\mathbf{K}_j + \lambda \mathbf{I})^{-1} \tilde{\mathbf{y}}_j$ (see \citet{hastie2009elements}) where $\widehat{\tilde{\mathbf{y}}}_j$ is the estimate of $\tilde{\mathbf{y}}_j$, a vector including $\tilde{y}_{j,i}$ for $\forall i$, and $\{\mathbf{K}_j\}_{i, i^\prime} = K_j(\mathbf{z}_{j,i}, \mathbf{z}_{j,i^\prime})$ for $i, i^\prime =1,\ldots,n$ for a given kernel $\mathbf{K}_j$. Since $\tilde{\mathbf{y}}_j = \mathbf{y} - \mathbf{S}_1 \mathbf{y} - \mathbf{S}_2 \mathbf{y} - \cdots - \mathbf{S}_{j-1} \mathbf{y}$, \begin{equation} \mathbf{S}_j \mathbf{y} := \widehat{\tilde{\mathbf{y}}}_j=\mathbf{S}_j^\prime \tilde{\mathbf{y}}_j = \mathbf{S}_j^\prime (\mathbf{y} - \mathbf{S}_1 \mathbf{y} - \mathbf{S}_2 \mathbf{y} - \cdots - \mathbf{S}_{j-1} \mathbf{y}) = \mathbf{S}_j^\prime (\mathbf{I} - \sum_{l=1}^{j-1}{\mathbf{S}_l})\mathbf{y} = \mathbf{S}_j^\prime (\mathbf{I} - \sum_{l=0}^{j-1}{\mathbf{S}_l})\mathbf{y}. \end{equation} Now, for $j=1$, the response to estimate is $\tilde{\mathbf{y}}_1 = \mathbf{y}$, so we have \begin{equation} \mathbf{S}_1 \mathbf{y} := \widehat{\tilde{\mathbf{y}}}_1=\mathbf{S}_1^\prime \tilde{\mathbf{y}}_j = \mathbf{S}_1^\prime \mathbf{y} = \mathbf{S}_1^\prime (\mathbf{I} - {\mathbf{S}_0})\mathbf{y}. \end{equation} where $\mathbf{S}_0$ is an $n\times n$ zero matrix. Therefore, the result holds for $\forall j=1,\ldots,J$. \end{proof} As implied in Theorem~\ref{thm:trace}, we do not allow distinct hyperparameters for each $g_j$ estimation as the GCV calculation is based on the full model. Instead, we assume the hyperparameters to be the same across all $g_j$ for $j=1,\ldots,J$. We apply a grid search for the hyperparameter learning, which is to keep hyperparameters at certain levels, add critical subspaces based on this hyperparameter setting, and evaluate the GCV value for the resulting full model (after the termination of the search). The set of hyperparameters and the corresponding subspace-based model that minimize the GCV criterion in Eq.~\eqref{eq:gcv} will be chosen as an optimal model. Because the GCV calculation based on the result of Theorem~\ref{thm:trace} is complicated due to the recursive format, we also consider a simpler version of the trace calculation. For approximation, we use $\mathbf{S}_j^\prime$ instead of $\mathbf{S}_j$. The following describes two alternatives we propose for the GCV calculation: \begin{enumerate} \item[\textbf{A1}.] $\text{trace}(\mathbf{S}) = \sum_{j=1}^J{\text{trace}(\mathbf{S}_j)}$ based on Theorem~\ref{thm:trace}. \item[\textbf{A2}.] $\text{trace}(\mathbf{S}) = \sum_{j=1}^J{\text{trace}(\mathbf{S}_j^\prime)}$ for simplification. \end{enumerate} The performance of the two alternatives will be compared and discussed in Section~\ref{sc:result}. \subsection{Overall algorithm} \begin{algorithm}[t] \SetAlgoLined Apply 5-fold CV to split given data into training data ($\mathcal{T}_q$) and validation data ($\mathcal{V}_q$)\; Build a constant model by using data in $\mathcal{T}_q$ and predict responses for the corresponding $\mathcal{V}_q$\; Initialize $CV^*$ by setting it to the prediction error of the constant model (the average of 5 errors obtained from $\mathcal{V}_q$ for $q=1,\ldots,5$)\; Create a grid for assessing different sets of hyperparameters\; \For {each level combination of hyperparameters}{ Set the iteration number to 0, i.e., $t=0$\; \Repeat{$\Delta e < \tau$}{ $t\leftarrow t+1$\; Randomly draw a subspace\; Use $\mathcal{T}_q$ and build an SVR model by using the randomly drawn subspace\; Make a prediction of $\tilde{y}_{t,i}$ for those in the validation datasets, $\mathcal{V}_q$\; Calculate the prediction error as $\tilde{y}_{t,i} - \hat{g}_t(\mathbf{z}_{t,i})$ and accordingly $RMSE_{t,q}$ and $CV_t$\; \If{$\Delta e > \eta$}{ $CV^* \leftarrow CV_t$\; $\mathcal{J}^* \leftarrow \mathcal{J}^* \cup \{t \}$\; } } Use the entire model learning data ($\mathcal{T}_q \cup \mathcal{V}_q$) to build a full model as in Eq.~\eqref{eq:model} by using the set of subspaces, $\mathcal{J}^*$, determined above\; Calculate GCV (either A1 or A2)\; } Find the minimum GCV\; Determine the optimal hyperpameters and finalize the full model specification\; \caption{Learning process of the randomized subspace modeling} \label{alg:overall} \end{algorithm} For clear illustration of the entire learning process, Alg.~\ref{alg:overall} shows the step-by-step procedures of the proposed subspace-based modeling. To build a model, we use a dataset that is dedicated to model learning; if testing is needed (as in Section~\ref{sc:result}), we split the original dataset into two distinct datasets, one for model learning and another for testing. From this model learning dataset, we apply 5-fold CV to split training data and validation data where validation data are required to determine the significance of subspaces and the convergence of the algorithm. After the data split, we produce a model that includes a single constant term by using training data only and calculate the error of validation set prediction to initialize $CV^*$. Each hyperparameter setting will be evaluated once a full model is established, i.e., once all critical subspaces are determined and added into the model. For each fixed level set of hyperparameters, we generate a subspace randomly and build an SVR model to estimate $g_t$. The quality of a subspace is evaluated via 5-fold CV with respect to $CV_t$ and $\Delta e$ in Eq.~\eqref{eq:cv} and \eqref{eq:epr}. If a subspace meets the selection criterion, it will be added into the model. This process of generating and evaluating a random subspace will continue until the termination criterion is met. Once the algorithm terminates, the GCV value will be computed according to Eq.~\eqref{eq:gcv}. After completing all the iterations for the grid search, we find the optimal hyperparameter values and apply this optimal setting to the entire model learning dataset (training and validation) to build a final model. This final model will be evaluated by a separate test set for the comparison with other methods in Section~\ref{sc:result}. \section{Case Study} \label{sc:result} Design and analysis of layered hybrid structure is challenged by the many possible choices of materials and configurations. This vast parameter space is impractical to explore through physical testing and is computationally prohibitive due to the analysis time required due to the large number and ranges of input parameters. The randomized subspace approach is applied to overcome this limitation and provide an efficient and accurate approach to computationally characterize the parameter space and inform limited physical testing to define parameters. The reduced order model can then be used to rapidly explore the parameter space to customize and optimize layered designs. The specific problem of metal and composite layered structures was chosen due to its complexity and fit for the demonstration objectives. To demonstrate the effectiveness of the proposed method, we compare its performance with other possible alternatives. The methods subject to comparison include various wrapper methods and machine learning-based methods. Some methods using a metaheuristic search are not considered here due to their high computational requirement. Since all alternatives leverage a learning model for variable selection, we first compare the prediction accuracy of models obtained from the alternatives. We also compare important variables selected by the alternatives. To compare the results more effectively, 5-fold CV is used here; in specific, it is used for the comparison of prediction ability and the evaluation of important variable selection. The prediction error is measured by RMSE, and the average and standard deviation of 5 RMSE's are compared. Since the other methods focus on the importance of ``individual'' variables, we extract a common set of important variables obtained from the 5-fold CV-based implementation (even for the proposed method). \subsection{Finite element analysis} Numerical simulation using a validated finite element model (finite element analysis) is an efficient method to design and predict the damage tolerance of a layered hybrid structure for varying material properties. However, given the nearly unlimited choices of material combinations and stacking sequences, it is not possible to explore every possible design and optimize for all possible material and configuration parameters. Therefore, identification of the most influential parameters is necessary to limit the design and optimization parameter space to obtain a computationally tractable solution. The case study layered hybrid configuration is an aluminum plate with a co-cured bonded quasi-isotropic E-glass/epoxy composite overlay. The composite overlay consists of 8 layers of multiple lamina types (see Table \ref{table:stacking sequence}) resulting in a high dimensional number of material parameters needed for characterization and input into the finite element model. \begin{table}[t!] \caption{Composite patch stacking sequence} \centering \begin{tabular}{c c c} \toprule & E-glass fabric & Fabrication style \\ \midrule 1 & Hexcel 7781 & 0$^{\circ}$/90$^{\circ}$ Stain weave\\ 2 & Vectorply E-BX 1200 & $\pm$ 45$^{\circ}$ Stitch \\ 3 & Vectorply E-LT 1800 & 0$^{\circ}$/90$^{\circ}$ Stitch \\ 4 & Vectorply E-BX 1200 & $\pm$ 45$^{\circ}$ Stitch \\ 5 & Vectorply E-BX 1200 & $\pm$ 45$^{\circ}$ Stitch \\ 6&Vectorply E-LT 1800 & 0$^{\circ}$/90$^{\circ}$ Stitch \\ 7& Vectorply E-BX 1200 & $\pm$ 45$^{\circ}$ Stitch \\ 8& Hexcel 7500 & 0$^{\circ}$/90$^{\circ}$ Plain weave\\ \bottomrule \end{tabular} \label{table:stacking sequence} \end{table} This layered multi-material model was loaded under four point bending to engage progressive damage in the structure through multiple damage mechanisms. Damage tolerance was evaluated by the total energy absorbed by the structure (an output parameter that is calculated during analysis and readily extracted using an automated approach). This model captures multiple, interacting damage mechanisms including the plastic deformation in aluminum, shear plasticity in each lamina, the intralaminar fracture of each lamina, delamination within the patch and disbond at the interface. Evaluation using this total damage energy provides a distinct and measurable result for the development of a reduced order predictive model and evaluation of influential parameters and their interactions. A 3D high fidelity finite element model explicitly captures each layer in the hybrid structure as well as the interfaces \citep{heng2018prediction}. Each fabric layer (lamina) is explicitly modeled, and cohesive elements are included between each layer to capture delamination between plies. Each lamina is individually modeled with continuum shell elements (SC8R). A cohesive damage model is implemented for each lamina using a VUMAT user subroutine. Cohesive elements with a triangular traction-separation law are used to detect the interlaminar damage and are also included at the metal/composite interface to capture disbond between the metal and resin. The aluminum substrate is modeled with solid elements (C3D8R). Loading and support pins are modeled as rigid bodies to create the boundary and loading conditions. The numerical simulations are executed in the FE code ABAQUS. This physics-based model was validated under four point bend loading through physical testing (Fig.~\ref{fig:validation}) . \begin{figure}[h!] \centering \includegraphics[width=.6\textwidth]{Figure2.pdf} \caption{Comparison of experimental (top) and numerical results (bottom) at failure under four point bending} \label{fig:validation} \end{figure} To predict the total energy absorption of the layered hybrid structure, the 41 parameters characterizing the material properties needed for input into the finite element model for the multiple layers are used as the predictors (see Table~\ref{table:realvariable} for detail). Latin hypercube sampling is applied to sample the parameter space based on the mean and standard deviation of the parameter ranges. For this case study, completing a single analysis generating a single data record takes an average of 3 hours depending on the parameter combination. Due to the computational time required to analyze the finite element model, we conducted 200 analyses producing a predictor matrix of size 200$\times$41 and a response vector of size 200. With more analyses, it is possible to generate a larger dataset, and this can further improve the prediction quality. However, from a practical perspective, we aim to develop a method that works well even with a small dataset, so we compare alternatives based on this small dataset. \begin{table}[!htbp] \caption{Variables for modeling damage tolerance of a hybrid metal structure (the Resin in this table is ``Resin (M1002 with M2046 Hardener)'') \citep{heng2018prediction} } \centering \resizebox{\textwidth}{!}{ \begin{tabular}{lll} \toprule Variable &Corresponding parameter \\ \midrule $x_1$ ($\sigma_y$) &Yield Stress of Al-5456 \\ $x_2$ ($n$) & Strain Hardening Exponent of Al-5456 \\ $x_3$ ($\sigma_{ss}$)&Nominal Stress First/Second Direction of Resin between Laminate plies \\ $x_4$ ($E_{Al}$)& Young's Modulus of Al-5456 \\ $x_5$ ($P$)& Power Term in Shear Hardening Equation for Laminates \\ $x_6$ ($\sigma_{nn}$)& Nominal Stress Normal-only Mode of Resin between Laminate plies \\ $x_7$ ($X_{7781}$)& Tensile strength of the Laminae Reinforced with Hexcel 7781\\ $x_8$ ($G_{1200}$)& Intralaminar Fracture Toughness of Laminae Reinforced with EBX 1200 \\ $x_9$ ($\epsilon^{pl}_{max}$)& Maximum Shear Plastic Strain for Laminates \\ $x_{10}$ ($G_{II}$)& Shear Mode Fracture Energy First/Second Direction of Resin between Laminate plies \\ $x_{11}$ ($\alpha_{12}$)& Shear Damage Parameter for Laminates\\ $x_{12}$ ($E_{1800}$) & Young’s Modulus of Laminae Reinforced with ELT 1800 \\ $x_{13}$ ($G_I$)& Normal Mode Fracture Energy of Resin between Laminate plies\\ $x_{14}$ ($X_{7500}$)& Tensile strength of the Laminae Reinforced with Hexcel 7500 \\ $x_{15}$ ($\sigma_{nni}$)& Nominal Stress Normal-only Mode of Resin between metal/composite interface \\ $x_{16}$ ($v_{Al}$)& Poisson’s Ratio of Al-5456 \\ $x_{17}$ ($E_{7500}$)& Young’s Modulus of Laminae Reinforced with Hexcel 7500 \\ $x_{18}$ ($\sigma_{ssi}$)& Nominal Stress First/Second Direction of Resin between metal/composite interface \\ $x_{19}$ ($X_{1800}$)& Tensile strength of the Laminae Reinforced with ELT 1800 \\ $x_{20}$ ($B-K_i$)& Mixed Mode Behavior for Benzeggagh-Kenane of Resin \\ & between metal/composite interface \\ $x_{21}$ ($E_{1200}$)& Young’s Modulus of Laminae Reinforced with EBX 1200 \\ $x_{22}$ ($G_{1800}$)& Intralaminar Fracture Toughness of Laminae Reinforced with ELT 1800 \\ $x_{23}$ ($\tilde{\sigma}_y$)& Effective Shear Yield Stress for Laminates\\ $x_{24}$ ($X_{12}$)&Shear Strength of Resin for all Lamina \\ $x_{25}$ ($B$)& Strength Coefficient of Al-5456 \\ $x_{26}$ ($v_{7500}$)& Poisson Ratio of Laminae Reinforced with Hexcel 7500 \\ $x_{27}$ ($X_{1200}$)& Tensile strength of the Laminae Reinforced with EBX 1200 \\ $x_{28}$ ($v_{1200}$)& Poisson Ratio of Laminae Reinforced with EBX 1200 \\ $x_{29}$ ($v_{1800}$)& Poisson Ratio of Laminae Reinforced with ELT 1800 \\ $x_{30}$ ($G_{7500}$)& Intralaminar Fracture Toughness of Laminae Reinforced with Hexcel 7500 \\ $x_{31}$ ($E_{7781}$)& Young’s Modulus of Laminae Reinforced with Hexcel 7781 \\ $x_{32}$ ($v_{7781}$)& Poisson Ratio of Laminae Reinforced with Hexcel 7781 \\ $x_{33}$ ($G_{7781}$)& Intralaminar Fracture Toughness of Laminae Reinforced with Hexcel 7781 \\ $x_{34}$ ($G_{12}$)& Shear Modulus of Laminate for Laminates \\ $x_{35}$ ($d^{max}_{12}$)& Maximum Shear Damage for Laminates \\ $x_{36}$ ($C$)& Coefficient in Shear Hardening Equation for Laminates \\ $x_{37}$ ($E_{nn}$)& Elastic Modulus of Resin between Laminate plies \\ $x_{38}$ ($B-K$)& Mixed Mode Behavior for Benzeggagh-Kenane of Resin between Laminate plies \\ $x_{39}$ ($E_{nni}$)& Elastic Modulus of Resin between metal/composite interface \\ $x_{40}$ ($G_{Ii}$)& Normal Mode Fracture Energy of Resin between metal/composite interface \\ $x_{41}$ ($G_{IIi}$)& Shear Mode Fracture Energy First/Second Direction of \\ &Resin between metal/composite interface \\ \bottomrule \end{tabular}} \label{table:realvariable} \end{table} \subsection{Implementation detail} By design, the randomized subspace modeling includes a 5-fold CV for the selection of critical subspaces. To compare performance with other methods, another layer of a 5-fold CV is implemented to have separate test datasets. The similar treatment is applied to other methods being compared. One layer of a 5-fold CV is used to split test datasets, and another layer of a 5-fold CV is used to learn hyperparameters, if applicable. The other methods subject to comparison include regression models based on linear regression, lasso regression, ridge regression, principal component regression (PCR), partial least squares regression (PLS), RF, $k$-nearest neighbors ($k$-NN), SVR, and NN to cover various linear and nonlinear modeling commonly used for feature selection. Before applying any method, we normalize the data to prevent any scale-relevant errors. To implement the randomized subspace modeling, we set the dimension of subspaces to three, i.e., $k=3$, and the selection and termination thresholds to \(\eta = 1\%\) and \(\tau= 0.001\%\), respectively, based on the results of preliminary studies. For the base learner of the subspace-based modeling (SVR), a kernel needs to be set among multiple possible options, including linear, polynomial (POLY), radial basis function (RBF), and sigmoid kernels. From preliminary experiments, we found kernels capturing linearity, such as linear and POLY kernels, provided better performance. In this regard, we choose POLY kernel, \(K(\mathbf{u}, \mathbf{v}) = (\gamma \mathbf{u}^T \mathbf{v} + \delta)^{d}\) where $\gamma$, $\delta$, and $d$, respectively, denote the scale, offset, and degree of polynomials, and set $\gamma=1/3$, $\delta=0$, and $d=1$ (found optimal). Since $\gamma$ had little impact on the final prediction error, we used the default value available in an R function for SVR fitting. Considering that we use normalized dataset, $\delta=0$ providing the optimal performance is not a surprise. Although $d=1$ produces the optimal result, the POLY kernel was chosen over the linear kernel as it is more flexible and capable of modeling nonlinearity with different parameterization. On the other hand, SVR learning itself involves some parameters, $\epsilon$ and $C := 1/\lambda$. We test three levels for each of the two parameters, i.e., $\epsilon = 0.01, 0.1, 0.5$ and $C= 1, 2, 5$, which generates nine distinct combinations of parameter setting among which an optimal setting is determined. When applying a grid search for this hyperparameter learning, if there exists a poor level combination, it is possible that the naive termination criterion does not work properly. To prevent iterating more than what is required for the exhaustive search, we force the search process to stop after 10000 iterations. For this case study, this hard thresholding was active only for a single level combination out of nine, so the termination criterion generally works well. Excluding NN and the proposed method, all methods are executed in R using \texttt{train()} function in the \texttt{caret} package. This package contains effective tools for data splitting, pre-processing, feature selection, model tuning with resampling and variable importance estimation as well as other functionality \citep{chen2020selecting}. \citet{chen2020selecting} showed RF method with \texttt{varImp()} was an efficient tool for calculating variable importance, so we use the same function to measure variable importance for other methods. On the other hand, NN is implemented in Python using ``keras'' package. To make the result comparable to the existing variable selection methods based on NN \citep{olden2004accurate,liu2019variable}, we test over multiple NN structures, one or two hidden layer(s), and three activation functions of linear, sigmoid, and ReLU. We also evaluate various hyperparameter options including the numbers of neurons, batch size, and epochs. With all this variation, we pick an NN model with the lowest prediction error for the result comparison. For NN, variable importance is determined by the CWA used in \citet{olden2004accurate}. Since all the methods but the randomized subspace modeling calculate variable importance rather than picking important variables, for these methods, we extract the first twenty important variables (based on the importance score) from each of the five-fold learning and find the common variables from the list of all selected variables to report critical individual variables. \subsection{Comparison results}\label{ssc:result} The optimal hyperparameter values of the proposed method vary a little with each model learning set (five of such). Table~\ref{tab:opt_par} shows the optimal values selected based on the two GCV criterion suggested in Section~\ref{ssc:hyppar}. From the table, it is shown, in general, $\epsilon=0.01$ and $C=5$ are found optimal. \begin{table}[h!] \centering \caption{Optimal parameters selected for each of the five model learning/test data split} \begin{tabular}{lcccccc} \toprule && Learn/test 1 & Learn/test 2 & Learn/test 3 & Learn/test 4 & Learn/test 5 \\ \midrule \multirow{2}{*}{A1} & $\epsilon$ &0.01 &0.01 &0.01 &0.01 &0.01 \\ & $C$ &5 &5&5&5&2\\ \midrule \multirow{2}{*}{A2} & $\epsilon$ &0.1&0.01&0.01&0.01&0.01 \\ & $C$ &5 &5&5&5&2\\ \bottomrule \end{tabular} \label{tab:opt_par} \end{table} The optimal models based on the result in Table~\ref{tab:opt_par} are compared with other alternatives as shown in Table~\ref{table:linear}. It is noticed that, in general, linear models perform better than nonlinear models for the material damage tolerance prediction. This applies to both the average and standard deviation of the prediction errors. Among the linear methods, partial least squares regression produces the lowest average prediction error while the regularized methods (lasso and ridge) show comparably decent performance. Although linear regression has the smallest variance of the estimator, its average prediction error is relatively higher than the other methods. For nonlinear methods, only SVM with a polynomial kernel and NN provide an average RMSE comparable to that of the linear counterpart. The two methods also show a similar level of the robustness of the estimator (through standard deviation). The proposed randomized subspace modeling achieves the best performance among all the methods. The model based on A1 GCV criterion is comparable to the best linear methods, and the model based on A2 outperforms all other methods with respect to the average and standard deviation of the RMSE's. This indicates that the proposed methods provide a model that is not only more accurate but also more robust and stable while reducing uncertainty. \begin{table}[h!] \caption{Comparison of the average and standard deviation of RMSE's from 5-fold evaluation} \centering \begin{tabular}{c c c} \toprule Method & Average & Standard deviation \\ \midrule Linear regression & 12.61 & 1.05 \\ Lasso regression & 12.02 & 1.45 \\ Ridge regression & 11.98 & 1.20 \\ Principal component regression & 12.21 & 1.64 \\ Partial least squares regression & 11.89 & 1.15 \\ \midrule Random forest & 14.70 & 3.00 \\ $k$-nearest neighbors & 15.27 & 3.51 \\ SVM (RBF) & 17.49 & 3.77 \\ SVM (POLY) & 12.01 & 1.20 \\ Neural network &12.45&1.13\\ \midrule Subspace-SVM (A1) & 11.99 & 1.12\\ \textbf{Subspace-SVM (A2)} & \textbf{11.64} &\textbf{0.94}\\ \bottomrule \end{tabular} \label{table:linear} \end{table} Although A1 applies the exact calculation of the GCV criterion, it is still based on the assumption of a squared loss function. As such, A1 is also an approximation of the exact GCV criterion. Since $\epsilon$-insensitive loss function used in Eq.~\eqref{eq:obj} penalizes errors out of the $\epsilon$-tube proportionally to the distance from the tube, the exact calculation for a squared loss function that more harshly penalizes larger errors may not guarantee the optimal performance. In A2, simplifying the hat matrix, i.e., dropping the recursive term of $(\mathbf{I} - \sum_{l=0}^{j-1}{\mathbf{S}_l})$, can avoid dependency on other $\mathbf{S}_j$'s, so that it can reduce the variance of the estimator preventing potential overfitting and hence producing better results. In addition, from the computational perspective, A2 does not require storing and adding all the previous $\mathbf{S}_j$'s but just requires calculating the trace of $\mathbf{S}_j^\prime$ for each subspace model estimation, so it is computationally more efficient than A1. By construction, the randomized subspace model extracts critical subspaces. However, none of the other methods has this capability. To assess the variable selection capability of the randomized subspace method, we instead compare which individual variables are selected as an important predictor. As illustrated in Fig.~\ref{fg:indvar}, we select common variables included in all five sets of critical subspaces from the 5-fold evaluation. For all other methods, we first find a set of important individual variables from each of the 5-fold evaluation and select the common variables from the sets for the consistency of the evaluation procedure. \begin{figure}[h!] \centering \includegraphics[width=\textwidth]{Figure3.pdf} \caption{Selection procedure of important individual variables} \label{fg:indvar} \end{figure} \begin{table}[hbt!] \caption{Important variables selected by all alternatives} \centering \resizebox{\textwidth}{!}{ \begin{tabular}{c|ccccccccccccccccccccccc } \toprule Method & $x_1$ & $x_2$ & $x_3$& $x_4$& $x_5$& $x_6$& $x_7$& $x_8$& $x_9$& $x_{10}$ & $x_{11}$ & $x_{12}$ &$x_{13}$ &$x_{14}$& $x_{15}$ &$x_{16}$ &$x_{17}$& $x_{18}$ \\ \midrule Linear &\checkmark &\checkmark&\checkmark&\checkmark&\checkmark &\checkmark&\checkmark&\checkmark&\checkmark&\checkmark&&&&&&&& \\ Lasso &\checkmark&\checkmark&\checkmark&\checkmark&\checkmark&\checkmark&\checkmark&\checkmark&&\checkmark&\checkmark&\checkmark&&&&&& \\ Ridge&\checkmark&\checkmark&\checkmark&\checkmark&\checkmark &\checkmark&\checkmark &\checkmark&&&\checkmark& &\checkmark &\checkmark&&&&\\ PCR&\checkmark&\checkmark&\checkmark&\checkmark & & &\checkmark&&&&&\checkmark&\checkmark &\checkmark&\checkmark &\checkmark&& \\ PLS&\checkmark&\checkmark&\checkmark&\checkmark&\checkmark& &\checkmark&\checkmark&&\checkmark&&\checkmark&&&&&&\checkmark \\ RF&\checkmark&\checkmark&\checkmark&\checkmark&\checkmark&&\checkmark&\checkmark&&&&&\checkmark&&&\checkmark&\checkmark&\\ $k$-NN&\checkmark&\checkmark&\checkmark&\checkmark&&&\checkmark&\checkmark&&&&\checkmark&\checkmark&\checkmark&\checkmark&&\checkmark&\\ SVM (RBF)&\checkmark&\checkmark&\checkmark&\checkmark&&&\checkmark&\checkmark&&&&\checkmark&\checkmark&\checkmark&\checkmark&&\checkmark&\\ SVM(POLY)&\checkmark&\checkmark&\checkmark&\checkmark&&&\checkmark&\checkmark&&&&\checkmark&\checkmark&\checkmark&\checkmark&&\checkmark&\\ NN&\checkmark&\checkmark&&\checkmark&\checkmark&\checkmark&\checkmark&\checkmark&&&&\checkmark&&&&&&\\ Our method&\checkmark&\checkmark&\checkmark&\checkmark&\checkmark&\checkmark&\checkmark&\checkmark&&\checkmark&&\checkmark&&&&&&\\ \bottomrule \end{tabular}} \label{table:var} \end{table} The result of important individual variable selection is shown in Table~\ref{table:var}. In the table, certain variables are identified as important variables by all methods while some are selected by only a few methods. For illustration purpose, we exclude all other variables that are not selected by any of the methods. According to the variable selection result, PCR and NN missed a variable ($x_8$ and $x_3$, respectively) that is chosen by all others. On the other hand, our method captures all variables that are found important by all the other methods, such as $x_1$, $x_2$, $x_4$ and $x_7$ as well as $x_8$ and $x_3$. Variables identified by the majority of the other methods (e.g., $x_5$ and $x_{12}$) are marked as important in our method. Certain variables rarely identified by the others (e.g., $x_9$ and $x_{11}$) are not included in the set of important variables for our method. In a few cases, our method selects a variable not chosen by the majority (such as $x_6$ and $x_{10}$) and does not select a variable voted by the majority ($x_{13}$ and $x_{14}$). Note here that, however, according to Table~\ref{table:linear}, the prediction quality of RF, $k$-NN, and SVM with an RBF kernel are not quite acceptable. By excluding the variable selection results from these methods, our method is, in fact, capable of determining important and unimportant variables of which result well aligns with the results of the remaining methods. In summary, this comparison result demonstrates that our method effectively extracts important variables. Besides the popular machine learning methods, we also compare our variable selection result with that of the elementary effects method \citep{heng2018prediction} in Table~\ref{table:ifa}. The result of the elementary effects method was derived from a dataset generated by one-factor-at-a-time approach, and the method did not extract common variables from 5-fold CV and did not record the top 20 important variables (instead, reported the top 10 important variables). Albeit this is not a valid methodology comparison as there are other aforementioned factors affecting the variable selection, we aim to compare our finding to the existing variable selection for this specific problem. In Table~\ref{table:ifa}, there are four common variables selected by our method and the elementary effects method. The elementary effects method does not mark some variables found important by the majority of the machine learning-based methods, including $x_2$, $x_3$, $x_7$, and $x_8$, and it identifies some variables that are never selected by others, such as $x_{24}$, $x_{31}$, $x_{33}$, and $x_{41}$. Without knowing the true importance of the variables, we cannot draw a solid conclusion, but our methods result well aligns with the result of other alternatives whereas the existing selection from the elementary effects method is a bit far from the majority vote. Our method adds $x_2$, $x_3$, $x_5$, $x_6$, $x_7$, and $x_8$ as important variables and drops $x_{11}$, $x_{17}$, $x_{24}$, $x_{31}$, $x_{33}$, and $x_{41}$ to and from the existing variable selection. \begin{table}[hbt!] \caption{Important variables selected by elementary effects method and our method} \centering \resizebox{\textwidth}{!}{ \begin{tabular}{c|ccccccccccccccccccc} \toprule Method & $x_1$ & $x_2$ & $x_3$& $x_4$& $x_5$& $x_6$& $x_7$& $x_8$& $x_9$& $x_{10}$ & $x_{11}$ & $x_{12}$ &$x_{17}$ &$x_{24}$ & $x_{31}$ &$x_{33}$ &$x_{41}$\\ \midrule Elementary effects method &\checkmark&&&\checkmark&&& &&&\checkmark&\checkmark&\checkmark&\checkmark &\checkmark&\checkmark&\checkmark&\checkmark\\ Our method&\checkmark&\checkmark&\checkmark&\checkmark&\checkmark&\checkmark&\checkmark&\checkmark&&\checkmark&&\checkmark&&&&&&\\ \bottomrule \end{tabular}} \label{table:ifa} \end{table} \subsection {Critical Subspace Analysis} One of the major novelty of the randomized subspace modeling is the capability of extracting critical subspaces, equivalently, identifying important physical variables and important interactions among the variables. In Section~\ref{ssc:result}, the comparison result demonstrates the quality of the important variable selection of the proposed method. Note here that the result of the important (individual) variable selection was derived from critical subspaces identified in each of model learning/testing data splits. This ensures the quality of the critical subspace selection to some extent. To determine critical subspaces for the given dataset, we apply the randomized subspace modeling to the entire data, i.e., using all 200 observations, without any data split to learn the model. The final model is constructed by 8 distinct critical subspaces, as shown in Table~\ref{table:subspace}. We observe that these subspaces contain most of the important individual variables found by our method in Table~\ref{table:var}, except $x_5$, $x_6$, and $x_{12}$, while each subspace includes at least one or two important individual variable(s). Assuming that an interaction formed by individually important variables is more significant than an interaction between others, we can at least conclude that the interactions between $x_2$ and $x_4$, between $x_4$ and $x_{10}$, and between $x_8$ and $x_{10}$ are significant. There are some variables that are not identified as important individual variables but included in the critical subspaces. These variables by themselves may not have significant impact on the damage tolerance, but their interactions with others could influence the response. Still, in its current form, we cannot validate if any combination between all variables in a subspace is significant. We will investigate this aspect as one of future study. For a reference, if only one variable is added to the model at a time ($k=1$), the prediction error is 12.28 with the standard error of 0.84. By ignoring the interactions formed by multiple variables, the prediction capability becomes weaker. This supports, at least to the minimum extent, that some of the interactions we modeled through subspaces improve the prediction, and hence they are considered significant. \begin{table}[t!] \caption{Critical subspace selected by our method} \centering \begin{tabular}{c c c} \toprule Critical subspace & Important individual variables\\ \midrule $x_{19}, x_7, x_{20}$ & $x_7$ \\ $x_3, x_{15}, x_{21}$ & $x_3$ \\ $x_{22}, x_1, x_{16}$ & $x_1$ \\ $x_{23}, x_4, x_{22}$ & $x_4$ \\ $x_{15}, x_4, x_{10}$ & $x_4$, $x_{10}$ \\ $x_{24}, x_3, x_{25}$ & $x_3$ \\ $x_4, x_{17}, x_2$ & $x_4, x_2$ \\ $x_8, x_{10}, x_{26}$ & $x_8$, $x_{10}$ \\ \bottomrule \end{tabular} \label{table:subspace} \end{table} \section{Conclusion} \label{sc:conc} In this paper, we propose the randomized subspace modeling to alleviate challenges in analyzing high-dimensional datasets and provide valuable insight about an underlying system by identifying important physical variables and interactions. The proposed method leverages an ensemble of multiple models derived from critical subspaces, reduced-dimensional physical spaces. The critical subspaces are generated by a randomized search and evaluated by a cross-validated selection criterion. With this structure, the proposed method shows its superiority over other alternatives in modeling a regression problem and identifying important variables. Specifically, for a high-dimensional analysis of hybrid material's damage tolerance, we can draw the following conclusions: \begin{enumerate} \item Compared to the models commonly used in the literature of variable selection (e.g., RF, NN, and Lasso), our method produces the lowest prediction error for this high dimensional, complex problem, demonstrating that our method is competitive for predicting high-dimensional datasets. In addition, the lowest standard error shows that our method produces robust prediction. \item The result of our method's important variable selection well aligns with the majority of other alternatives, verifying our method's variable selection capability. More importantly, our method identifies critical subspaces capturing not only important physical variables but also significant interactions, which is beneficial to experimental designs for broad engineering problems. \end{enumerate} In the future, we plan to improve the randomized search process. This includes a weighted randomized search leveraging variable importance priors obtained from domain knowledge and a multi-step search process that first learns the rankings of variable importance and searches subspaces based on the rankings. Improving the randomized search can avoid adding insignificant variables as a part of the final subspace selection. However, the inherent randomness can still involve an insignificant variable in a subspace. As such, we will also study how to identify and drop insignificant variables from the chosen subspaces. \bibliographystyle{plainnat}
{'timestamp': '2021-09-28T02:00:47', 'yymm': '2106', 'arxiv_id': '2106.01584', 'language': 'en', 'url': 'https://arxiv.org/abs/2106.01584'}
arxiv
\section{Inferring Users' App Dwell Time} \label{infering_features} To model the app engagement accurately, we need to uncover what information could be indicative factors for users' app dwell time. This is the main focus of this section. \subsection{User and Device Characteristics} \subsubsection{User Demographics} Prior studies \cite{zhao2016discovering, seneviratne2015your, kooti2017iphone} have shown that demographics (age and gender) have a significant impact on how users select apps or make in-app purchases on their smartphones. However, little is known about the correlation between users' demographic information and the time spent when using an app. Establishing such a relationship is the main focus of this subsection. By analyzing our user mobile app usage data, we demonstrate that on average, the app usage duration for female users is 2.8 minutes, which is longer than the male users who spent 2.2 minutes. To show the general pattern of usage duration across all apps, Figure~\ref{fig:session_duration_gender} presents the CDF of app usage duration for both the male and female users. We find that the duration distributions are similar between male and female users. \begin{figure} \centering \subfloat[Duration vs. Gender]{ \label{fig:session_duration_gender} \includegraphics[height = 1.9in]{pictures//Session_duration_gender_cdf.jpg} } \subfloat[Duration vs. Age]{ \label{fig:session_duration_age} \includegraphics[height = 1.9in]{pictures//Session_duration_age.jpg} } \caption{Effect of gender and age on app usage duration.} \label{fig:session_duration_user} \end{figure} \begin{table} \centering \scriptsize \caption{Top 5 app categories with the biggest gender effects -- the higher the gender effect is, the bigger difference exists in the app usage duration between male and female users. The gender group $G_1$ has longer app usage duration.} \label{tab:gender_bias} \scalebox{1}{\begin{tabular}{lcc|lcc} \toprule \textbf{App Category}&\textbf{Gender Group $G_1$}&\textbf{Gender Effect}&\textbf{App Category}&\textbf{Gender Group $G_1$}&\textbf{Gender Effect}\\ \midrule widgets&female&3.30&casino&male&1.81\\ medical&female&2.54&video&male&1.64\\ entertainment&female&2.10&health-and-fitness&male&1.60\\ communication&female&1.64&finance&male&1.30\\ shopping&female&1.63&navigation&male&1.27\\ \bottomrule \end{tabular}} \end{table} To investigate the effect of age, we demonstrate in Figure~\ref{fig:session_duration_age} that age affects app usage duration more significantly. Users between 25 and 54 years spend less time while engaging with apps than those who are teenagers or seniors. This scenario is consistent with results from the previous user studies \cite{ferreira2014contextual,pielot2014situ}. \citet{ferreira2014contextual} pointed out that micro-usage (less than 15 seconds) is popular across their participants aged between 22 and 40 years old. \citet{pielot2014situ} found that their participants (aged between 24 and 43 years old) need to deal with the large volume of notifications coming from personal communication due to high social expectations and the exchange of time-critical information. Besides these findings of general patterns across all apps, we hypothesize that the impacts of demographics would vary across different app categories. Therefore, we further explore if users' app usage duration with each app category would be affected by their demographics. To measure the impacts brought by users with different genders in a more generalized manner, we calculate the \emph{gender effect} for each app category of the two genders. First, for each app category $C_a$, we calculate the average app usage duration of female and male users respectively, i.e., $D(C_a, Gi)$ where $Gi\in\{male, female\}$. Secondly we calculate the \emph{gender effect}, $GE(C_a)$, for each app category $C_a$ as: $$GE(C_a) = \frac{D(C_a, G_1)}{D(C_a,G_2)}$$ where $GE(C_a)$ measures the \emph{gender effect} of the app category $C_a$. The higher the effect is, the bigger difference exists in the app usage duration of the male and female users within this app category. The gender group in the numerator has a longer dwell time on this app category. Table~\ref{tab:gender_bias} shows the top 5 app categories with the highest gender effects. We can find the female users have a longer app usage duration than male users with apps like widgets, medical, entertainment, communication, and shopping. On the other side, male users stay longer with the casino, video, health-and-fitness, finance, and navigation apps. \begin{table} \centering \scriptsize \setlength{\tabcolsep}{2pt} \caption{Top 5 app categories with the biggest age effects -- the higher the age effect is, the bigger difference exists in the app usage duration between users with different age. The age group $A_i$ has longer app usage duration when compared with other users.} \label{tab:age_bias} \scalebox{1}{\begin{tabular}{lcc|lcc|lcc} \toprule \textbf{App Category}&\textbf{Age Group $A_i$}&\textbf{Age Effects}& \textbf{App Category}&\textbf{Age Group $A_i$}&\textbf{Age Effects}& \textbf{App Category}&\textbf{Age Group $A_i$}&\textbf{Age Effects}\\ \midrule shopping&13-17&2.75&widgets&18-24&2.35&food-and-drink&25-34&1.59\\ entertainment&13-17&1.81&entertainment&18-24&2.20&video&25-34&1.30\\ social&13-17&1.28&business&18-24&1.65&medical&25-34&1.30 \\ photography&13-17&1.27&tools&18-24&1.41&music&25-34&1.29\\ sports&13-17&1.24&adventure&18-24&1.41&transportation&25-34&1.27\\ \midrule \textbf{App Category}&\textbf{Age Group $A_i$}&\textbf{Age Effects}& \textbf{App Category}&\textbf{Age Group $A_i$}&\textbf{Age Effects}&&&\\ \midrule lifestyle&35-54&1.29&productivity&55+&2.16&&&\\ casino&35-54&1.27&entertainment&55+&2.11&&&\\ word&35-54&1.23&board&55+&2.00&&&\\ travel&35-54&1.22&puzzle&55+&1.90&&&\\ action&35-54&1.21&books&55+&1.88&&&\\ \bottomrule \end{tabular}} \end{table} Similarly, we calculate the \emph{age effect} brought by different users on the app dwell time. Since there are five age groups in our dataset, we choose the average app usage duration of all users as the reference value to calculate the \emph{age effect}. Therefore, for each app category $C_a$, we calculate the average duration of users belonged to different age groups respectively, i.e., $D(C_a, Ai)$ where $Ai\in\{13$-$17$, $18$-$24$, $25$-$34$, $35$-$54$, $55+\}$. Then we calculate the \emph{age effect}, $AG(C_a)$, for each app category $C_a$ as: $$AG(C_a) = \frac{D(C_a, A_i)}{D(C_a,A)}$$ which measures the \emph{age effect} of the app category $C_a$. $A$ represents the users across all ages who have engaged with the app category $C_a$. The higher the effect is, the bigger difference exists in the app usage duration of the users with corresponding ages $A_i$. The age group in the numerator has a longer dwell time on this app category when compared with other users. Table~\ref{tab:age_bias} shows the app categories with top \emph{age effects}. It is interesting to find that teenage users have a longer duration in the shopping apps. Users between 25 and 34 prefer to stay longer with the food-and-drink apps than other users. It is not surprising to find that the older users over 55, will spend a much longer time when using the apps of entertainment, games (board/puzzle), and books apps since they have more spare time. For the longer time spent in productivity apps, this may result from that old users are not as efficient in the operations with the productivity apps (e.g., Microsoft Office, file managers). \subsubsection{Device} \citet{li2017mining} ever analyzed the influence brought by different mobile device models on users' online time and they found that users rely less on the cellular network as the price of the device model increases. However, there has been no empirical research conducted for the impacts on dwell time with different apps brought by device characteristics. In this section, we compare app usage duration across different device types. There are mainly two different types of devices in our dataset: tablet and phone. We use the similar methodology of calculating the \emph{gender effect} for each app category to calculate the \emph{device effect} with the two device types. First, for each app category $C_a$, we calculate the average usage duration of phone users and tablet users respectively, i.e., $D(C_a, T_i)$ where $T_i \in \{phone, tablet\}$. Secondly, we calculate the \emph{device effect}, for each app category $C_a$ as: $$DTE(C_a) = \frac{D(C_a, T_1)}{D(C_a, T_2)}$$ The higher the \emph{device effect} $DTE(C_a)$ is, the bigger difference exists in the app usage duration of the users with different device types. Table~\ref{tab:device_effect} shows the app categories with the most significant difference across the different devices. We can find that the tablet users have a longer dwell time on productivity, books, business, board, and travel apps. On the other hand, phone users have a longer dwell time with navigation, shopping, weather, family, and personalization apps. \begin{table} \centering \scriptsize \caption{Top 5 app categories with the biggest device effects -- the higher the device effect is, the bigger difference exists in the app usage duration between the phone and tablet users. The users with device type $T_1$ have longer app usage duration.} \label{tab:device_effect} \scalebox{1}{\begin{tabular}{lcc|lcc} \toprule \textbf{App Category}&\textbf{Device Type $T_1$}&\textbf{Device Effects}&\textbf{App Category}&\textbf{Device Type $T_1$}&\textbf{Device Effects}\\ \midrule productivity&tablet&4.95&navigation&phone&8.04\\ books&tablet&3.29&shopping&phone&6.02\\ business&tablet&3.00&weather&phone&1.29\\ board&tablet&2.91&family&phone&1.22\\ travel&tablet&2.82&personalization&phone&1.19\\ \bottomrule \end{tabular}} \end{table} \subsection{Temporal Patterns} \begin{table} \scriptsize \centering \caption{Index of dispersion of average app usage duration distribution across a day.} \label{tab:session_duration_variance} \scalebox{1}{\begin{tabular}{lc|lc} \toprule \textbf{App Category}&\textbf{Index of Dispersion}&\textbf{App Category}&\textbf{Index of Dispersion}\\ \midrule tools&0.02&comics&4.18\\ productivity&0.02&adventure (game)&3.86\\ utilities&0.02&strategy (game)&2.51\\ music&0.04&racing (game)&2.05\\ photography&0.05&family&1.59\\ news&0.06&transportation&1.35\\ widgets&0.07&medical&1.03\\ \bottomrule \end{tabular}} \end{table} \begin{figure} \centering \includegraphics[width = 0.65\textwidth]{pictures//High_Var_Hour_Distribution.jpg} \caption{Temporal patterns of average app usage duration for different app categories.} \label{high_var_hour} \end{figure} The temporal usage pattern is always an essential factor for inferring which app user will use, where we usually model the possibility of using different apps at a specific time \cite{huang2012predicting, shin2012understanding, liao2012mining}. From our descriptive analysis in Figure~\ref{fig:hour_distribution}, we can find that the average app usage duration with all app categories across a day is about 2 to 3 minutes, and no sharp fluctuations exist. We use the index of dispersion \cite{cox1966statistical} as a normalized measure of the dispersion for the app usage duration distribution across a day, which is defined as the ratio of the variance $\sigma^2$ to the mean $\mu$: $D =\frac{\sigma^2}{\mu}$. In general, the index of dispersion for all apps is 0.043. To validate that whether the temporal pattern varies on different app categories, we further explore the index of dispersion of the app usage duration across a day for different app categories respectively. Table~\ref{tab:session_duration_variance} shows the app categories with the smallest and biggest index of dispersion in app usage duration. We can find that the usage duration of most game apps will be significantly different across a day. However, for some functional apps like productivity, tools, utilities, and photography, whenever the user accesses them, the app usage duration does not change much. Figure~\ref{high_var_hour} illustrates the distribution of average usage duration across a day for several app categories, where we can find that besides the different variances, the temporal patterns could be significantly different with various app categories (each app category has its own specific temporal pattern). For example, comics apps have a longer usage duration around 4 AM; the usage duration of racing apps is peaking around 3 AM; longer time is spent in adventure apps around 8 PM and 1 AM. \subsection{Short-term context} \begin{figure}[t] \subfloat[]{\label{fig_last:sub-first} \centering \includegraphics[height = 1.9in]{pictures/Last_App_Shopping.jpg}} \subfloat[]{\label{fig_last:sub-second} \centering \includegraphics[height = 1.88in]{pictures//Last_App_Video.jpg}}\\ \subfloat[]{\label{fig_last:sub-third} \centering \includegraphics[height = 1.92in]{pictures//Last_App_Food.jpg}} \subfloat[]{\label{fig_last:sub-fourth} \centering \includegraphics[height=1.88in]{pictures//Last_App_Family.jpg}} \caption{Correlation between last used app and the next app's engagement level (discrete representation of app usage duration: light, medium and intensive). The darker color means higher probabilities that the next app will be engaged with the corresponding engagement level.} \label{fig:last_app_heatmap} \end{figure} \subsubsection{Last Used App} Previous studies identified that some apps were often used together \cite{li2015characterizing,xu2011identifying, bohmer2011falling}. For example, \citet{li2015characterizing} showed that some apps are installed together, whereas other studies \cite{xu2011identifying, bohmer2011falling} found that some genres of apps are highly likely to be accessed sequentially. Therefore, we aim to explore whether the last used app could also impact the next app usage duration. To avoid the biases of the original differences of app usage duration across different app categories and measure the impacts more intuitively, we quantify the app usage duration into the corresponding engagement level defined as in Sec~\ref{engagment_level_definition}. Figure~\ref{fig:last_app_heatmap} shows several examples for illustrating the different patterns between specific last apps and the engagement levels of next apps. Each cell in the table represents the transition probability $P_{ij}$ from the last used app $a_i$ to the next app $a_j$ at a given engagement level $e_{a_j}$. By having $P_{ij}$ for all the three engagement levels, we calculate its standard deviation as $\sigma^i_j$. This represents the extent of how much the last app $a_i$ would have very different transition probabilities on different engagement levels of the next app $a_j$. The higher $\sigma^i_j$, the more likely the last app $a_i$ would result in a specific engagement level of the next app $a_j$. For a given app $a_j$, we average $\sigma^i_j$ across all the last used apps $a_i$ as $\sigma_j = \sum^{i=1..N} \sigma^i_j/N$, where $N$ is the amount of unique last used apps. For all the apps, the $\sigma_j$ ranges between 0.11 and 0.32, whereas the median is 0.15. For the apps with higher $\sigma_j$, i.e., shopping apps ($\sigma_j$ $\approx$ 0.32) and video apps ($\sigma_j$ $\approx$ 0.29), the last used app could lead them to be used with specific engagement level (intensive for shopping and light for video). For example, for the video apps (as shown in Figure ~\ref{fig_last:sub-second}), if they are used after using navigation apps, the time spent on the video app is much more likely to be short. This could be explained by users who are on their commute to work. After checking the navigation, users may need to wait for the bus or subways, so they could have time for enjoying a short video. Additionally, we also show the app categories with average $\sigma_j$ and lower $\sigma_j$, i.e., food-and-drink apps ($\sigma_j$ $\approx$ 0.16) and family apps ($\sigma_j$ $\approx$ 0.11), whereas the last used app could not impact the engagement level of next app usage significantly. For example, no matter which app is used before the family apps (as shown in Figure~\ref{fig_last:sub-fourth}), the time spent on the family apps do not differ much. \subsubsection{Last Engagement Level} \begin{comment} \begin{figure} \centering \includegraphics[width =0.9\textwidth]{pictures//last_engagement_heatmap.eps} \caption{Transition probability of the last engagement level and next engagement level of the same app usage.} \label{fig:last_engagement_heatmap} \end{figure} \end{comment} Besides the last used app, we hypothesize that the time spent on the last app (last engagement level) could also impact how long the user will stay with this app. To focus solely on the impact of the last engagement level, rather than the impact of last used app, we calculate the transition probability between the engagement levels of the last and next usage \emph{within the same app}. We find four typical patterns across all different app categories. We illustrate these correlation patterns between the last and next engagement levels in Figure~\ref{fig:last_engagement_heatmap}. Across all 45 app categories, 37.8\% (17/45) of them follow the pattern of maintaining a higher probability that the next engagement level is as same as the last engagement level (i.e.,~higher probability in the diagonal of the heatmap), such as the books apps shown in Figure~\ref{fig_last_en:sub-first}. Besides this common pattern, we also find that 44.4\% (20/45) of the app categories have a bidirectional (increasing/decreasing) trend with the closest level, like the food-and-drink apps (i.e., engagement level transition between medium and intensive). The last common pattern is illustrated by comics apps, 13.3\% (6/45) of app categories have a similar transition probability across all levels. The remaining pattern is illustrated by travel apps, where no other app categories have similar patterns with them. We can find that there is an apparent increasing trend between engagement level light and medium for travel apps, which could state that users may be more likely to get addicted to planning for a vacation within a travel app. \begin{figure}[t] \subfloat[Books Apps]{\label{fig_last_en:sub-first} \centering \includegraphics[height =1.7in]{pictures/last_engagement_heatmap_books.jpg}} \hspace{35pt} \subfloat[Food-and-drink Apps]{\label{fig_last_en:sub-second} \centering \includegraphics[height = 1.7in]{pictures//last_engagement_heatmap_food.jpg}}\\ \subfloat[Comics Apps]{\label{fig_last_en:sub-third} \centering \includegraphics[height = 1.7in]{pictures//last_engagement_heatmap_comics.jpg}} \hspace{35pt} \subfloat[Travel Apps]{\label{fig_last_en:sub-fourth} \centering \includegraphics[height=1.7in]{pictures//last_engagement_heatmap_travel.jpg}} \caption{Transition probability of the last engagement level and next engagement level of the same app usage.} \label{fig:last_engagement_heatmap} \end{figure} \subsection{Long-term Context} \begin{figure}[t] \subfloat[Weather Apps]{\label{fig_per:sub-first} \centering \includegraphics[height = 1.7in]{pictures/Engagement_Periodic_weather.jpg}} \hspace{35pt} \subfloat[Shopping Apps]{\label{fig_per:sub-second} \centering \includegraphics[height = 1.7in]{pictures//Engagement_Periodic_shopping.jpg}} \caption{Two typical interval time distribution with different engagement levels (we limit the x-axis to 50 hours since over 98\% intervals are shorter than 50 hours): (1) General trend illustrated by weather apps: the shorter interval between two accesses, the less time is spent with the next usage; (2) Specific daily periodic pattern illustrated by shopping apps: similar length of time is spent on the same shopping app after a specific interval (i.e., 24-hour). } \label{fig:engagement_periodic} \end{figure} \subsubsection{Periodic Pattern} Some apps are used repeatedly after every specific period. For example, users may check the mail apps every hour or play with a game app every 3 hours \cite{liao2012mining, tan2012prediction}. To validate whether the periodic pattern also exists in the app dwell time (i.e.,~after a specific interval, users may stay with an app again for the similar length of time as before that interval), we first quantify the interval between the two accesses of the same app at the hour level, e.g., 28 min = 0 hour, 1.6 hours = 2 hours. We then generate the histogram of interval time length with different engagement levels respectively for each app category. Two typical patterns are found among all the app categories, which are shown in Figure~\ref{fig:engagement_periodic}. Figure~\ref{fig_per:sub-first} denotes the interval time length distribution of weather apps, which represents the general trend that a set of most other app categories will obey, i.e.,~the shorter interval between two accesses of the same app, the less time (engagement level: light) user will spend within the next usage of this app. However, as shown in Figure~\ref{fig_per:sub-second} (i.e.,~ the shopping apps), the other typical pattern demonstrates that the less time between two accesses, the more likely the second app access will also result in a longer time stay (engagement level: intensive) on the app. This may be because when users are going to buy something, they will browse/revisit the shopping apps multiple times with short breaks (break for checking other information or chat with friends for asking advice) and finally place the order. Additionally, we find that there is a peak around the interval of 24 hours for the engagement level of light/medium for shopping apps. This states that users prefer to spend a similar length of time to regularly check the shopping apps every day (i.e., after every 24 hours), probably for checking the updated discount or product information. This pattern could also be observed with books apps. \begin{comment} \begin{figure} \centering \includegraphics[width = 0.65\textwidth]{pictures//Engagement_Periodic_2.eps} \caption{Two typical interval time distribution with different engagement levels (we limit the x-axis to 50 hours since over 98\% intervals are shorter than 50 hours): (1) General trend illustrated by weather apps: shorter interval between two accesses, less time is spent with the next usage; (2) Specific daily periodic pattern illustrated by shopping apps: similar length of time is spent on the same shopping app after a specific interval (i.e., 24-hour). } \label{fig:engagement_periodic} \end{figure} \end{comment} \subsubsection{Historical Interest Pattern} \begin{figure} \centering \subfloat[User A]{ \label{fig:user_a_historical} \includegraphics[width=0.9\textwidth]{pictures//Engagement_Historical_User1.jpg} }\qquad \subfloat[User B]{ \label{fig:user_b_historical} \includegraphics[width=0.9\textwidth]{pictures//Engagement_Historical_User2.jpg} }\qquad \subfloat[User C]{ \label{fig:user_c_historical} \includegraphics[width=0.9\textwidth]{pictures//Engagement_Historical_User3.jpg} } \caption{Historical pattern with app engagement levels.} \label{fig:Historical_Engagement} \end{figure} Users' historical interests may be indicative of future intent. For example, users who love sports might potentially access sports apps and consume more sports-related content than others. Therefore it is important to examine the long-term interest patterns of different users. To clarify that if users also have the historical habit for the app dwell time on different app categories, we select three users whose top three preferred (based on usage frequencies) app categories are all the same, which are productivity, widgets, and social apps. We then illustrate the histogram of their historical engagement levels within these three app categories in Figure~\ref{fig:Historical_Engagement}. We can find that \emph{User A} prefers to stay longer (engagement level: intensive) within the widgets apps but spend less time (engagement level: light) with social apps than others. Differently, \emph{User B} has a longer app usage duration (engagement level: intensive) with social apps. Therefore, even for the users with the same historical app preferences, their engagement habits would be different. In a summary, different users may have their own specific historical engagement patterns on app dwell time for various apps. \section{Discussion} In this study, we explored the factors that affect users' app dwell time from users' app usage logs and show evidence that the next app and how long the user will stay on this app could be predicted simultaneously. First, to answer our first research question (\textbf{RQ1}), we take a systematic approach to uncover the dependency of users' app usage duration on user characteristics and context features based on a large-scale dataset. We then showed that the features related to users' historical engagement pattern and periodic usage pattern are good predictors of how long users will stay with an app. To solve the second research question (\textbf{RQ2}), we propose three different joint prediction strategies and demonstrate that the boosting based strategy performs the best. We further conduct the error analysis on the boosting strategy compared to the benchmark sequential based strategy. Based on the analysis, we find that besides the benefits brought by the "pseudo-residuals" within the boosting principle, the engagement features also provide additional insights to help infer which app user will use. These findings inspire us that we should think of adding more engagement related features when predicting the next app. As below, We discuss how our findings can be applied to future mobile systems and applications, the limitations in our study \rebuttal{and the differences between personalized and general engagement prediction.} \subsection{Implications} Firstly, the model proposed in our work can be applied for more tailored engagement-aware recommendations on mobile phones. As the operating system has access to all the features used for training the next app and app engagement models in this work, it is uniquely suited to predict a user's likely next app usage and engagement level under the current context. By doing so, the operating system can manage the delivery of content and services to the end-user by matching their engagement demands with the predicted engagement levels of the user. For instance, an app that shows mobile advertisements require high engagement from the end-users and can ask the app provider to push its content to the user when he/she is likely to be highly engaged. The media apps, like video and news apps, could recommend more satisfactory content based on the predicted engagement level of users to improve user experience. Recently, there is an active area of research for the timely delivery of notifications on mobile devices. Researchers have primarily focused on understanding the receptivity of mobile notifications \cite{mehrotra2016my} and predicting opportune moments to deliver notifications in order to optimize metrics such as response time \cite{pejovic2014interruptme}. While response time is indeed a useful metric to optimize for, they do not capture how much engagement the user will show towards the notification. The primary purpose of a notification is to attract user attention and increase the possibility of user engagement with the notification content. As such, we believe that the models and features we explored in this work can also be incorporated in designing an effective notification delivery mechanism. \subsection{Limitations} Although we have explored several meaningful features that could be applied in benefiting users' app engagement (dwell time) prediction, we must acknowledge the limitations of the dataset used in our study. Firstly, \rebuttal{similar to all other real-world app usage datasets, the app popularity distribution follows Zipf’s law \cite{li2015characterizing, petsas2017measurement}, which indicates that only a few apps have high installation/usage whereas many apps have low installation/usage. But doing a balanced prediction would not fit the realistic evaluation settings, which would bring the bias of the users/contexts to be selected. To handle this imbalance issue within app categories while evaluation, we measure the performance of all prediction problems based on four metrics: accuracy, precision, recall and f1. All the metrics are calculated for each label, and their averages are weighted by support (the number of true instances for each label). We also conducted case studies to explore the prediction results based on different app categories.} Additionally, our dataset might not be representative of the entire population of mobile users, as the users and apps are only coming from the apps registered in this library. This means that not all the apps usage behaviour of users could be tracked and there may be a selection bias in the subset of users being studied. While this might occur to some extent, given the scale of our dataset (with over 1.3 million logs), we believe our data would still provide useful insights, and our predictive models are the best models so far, effective for most users. Lastly, the predictive features we extracted can be further enriched. Other features that precisely characterize users' app engagement behaviours could be further explored, such as the location, wifi access status, battery, device mode setting (e.g., silent), illumination, screen, and blue-tooth. In this work, our main aim is to validate that how long a user will stay with an app could be modelled based on the user characteristics and context features. We would like to further explore additional features and models for improvements in our future work. Despite these limitations, we believe our work is the first-of-its-kind study to examine, and model the mobile app engagement purely based on features derived from users' app usage logs. We also hope that the framework, models, and insights developed in this work can bring clarity and guidance to aid future mobile system developers in designing better, and engagement-aware user experience. \subsection{Personalized V.S. General Engagement Prediction} We know that the performance of the personalized model could be highly impacted by whether there is sufficient data for training or not. In this work, we are interested in relatively short-term user app engagement patterns. Therefore, we collect app usage data from all users for a week. Due to the nature of the data, it might be more difficult to acquire sufficient per-user patterns, which is also validated by our experiment results regarding the next app prediction (i.e. personalized model could not outperform our proposed hybrid model). When the long-term data is available, the personalized approach might be more suitable and achieve better performance. We leave the exploration of the personalized model for app usage prediction in our future work. In terms of the app engagement level (dwell time) prediction, we introduce the engagement levels according to different app categories for handling users’ different consumption behaviour on different contents. Hence our engagement level prediction results do not directly translate to user-specific engagement. Additionally, we believe that defining and measuring aggregate engagement is also useful for content producers, e.g., video producers on Youtube. The content providers often do not target a specific user, but a large number of audience. Other than predicting how long user will stay on the app, we also want to provide content producers with a new set of tools to create engaging content and forecast user behaviour. For future work, we would measure users' engagement at the personalized level as complementary to the aggregated engagement study, especially when we have more sufficient training data for individuals. It would help the mobile apps to provide more fine-grained services to a specific user based on the more accurate expected time length. \section{Related Work} \label{Sec:Related_Work} Our work is related to prior literature on user engagement analysis (\S\ref{user_engagement}) and next app/engagement prediction (\S\ref{app_usage_engagement_prediction}). \subsection{User Engagements} \label{user_engagement} \subsubsection{\textbf{Engagement Measurements}} Approaches to measuring user engagement of online services can be divided into three main groups: (a)~self-reported engagement, (b)~cognitive engagement, and (c)~online behaviour metrics \cite{lehmann2012models}. In the first group (a), questionnaires and interviews are used to elicit user engagement attributes or to create user reports and to evaluate engagement \cite{kim2013study}. The second type of approach (b) uses task-based methods and physiological measures to evaluate the cognitive engagement (e.g., facial expressions, vocal tone, and heart rate) using tools such as eye-tracking \cite{ehmke2007identifying}, heart rate monitoring, brain readings from headset \cite{mathur2016engagement}, swipe on the screen \cite{nelissen2018swipe} and mouse tracking \cite{huang2011no}. However, these two types of methods have known drawbacks, e.g.,~reliance on user subjectivity of the self-reported engagement, and only be able to measure a small number of user interactions of the cognitive engagement. The third type of approach (c), adopted by the web-analytics community, has been studying user engagement through online behaviour metrics that assess users’ depth of engagement within a site, e.g.,~the time spent on a webpage. Studies on user engagement in the contexts of desktop-based systems \cite{van2007realism} and websites \cite{diaz2014predicting,yom2013measuring} have shown that simple metrics such as dwell time are meaningful and robust in modelling user engagement. For example, the time spent on a resource has been validated as an effective metric for measuring user engagement in the context of web search \cite{agichtein2006improving, bilenko2008mining}, and recommendation tasks \cite{yi2014beyond}. Kelly et al. \cite{kelly2004display, fox2005evaluating} consider dwelling times as an indicator of page relevance or user satisfaction during search engine interactions. \citet{yi2014beyond} recommend designing dwell time based user engagement metrics and claim that this would enable them to extract better user engagement signals for training recommendation systems thereby optimizing for long term user satisfaction. Therefore, we also propose to use the metric of time spent on mobile apps (dwell time) as our user engagement metrics within a large-scale dataset. For now, minimal research has been done for modelling mobile app dwell time from a large-scale dataset; only the basic aggregated statics on app usage time was reported. Falaki et al. \cite{falaki2010diversity} found that 90\% of app usage sessions would be less than 6 minutes and Xu et al. \cite{xu2011identifying} reported that the majority of total network access time for all apps is from 10 seconds to 1 hour for each subscriber in one week. Li et al. \cite{li2015characterizing} reported usage time for different app categories in total and found that communication apps account for 49\% cellar time against all apps. B{\"o}hmer \cite{bohmer2011falling} found that the Libraries \& Demos apps (default Updater, Google Services Framework, etc.) have the longest average usage time from opening to closing. However, these summarized basic statistics of app usage time can not provide an in-depth understanding of what factors could influence the dwell time user spend on an app and whether we could predict how long user would stay with an app. In our work, we conduct the first empirical analysis of dwell time during app usage based on a large-scale data set collected from thousands of users; and we are the first to assess how different kinds of features (e.g., demographics, device type, hour of day, and last used app) impact the mobile app dwell time. \subsubsection{\textbf{Influential Factors of App Usage}} Lots of previous research has been conducted to uncover the factors that influence app usage behaviour, ranging from time, demographics, device types, last used app, to periodic patterns. \citet{xu2011identifying} and \citet{li2015characterizing} discovered the temporal pattern of app usage, e.g., news apps were more frequently used in early mornings, whereas sports apps were more frequently used in evenings. They also found that, in general, the app usage frequency changed during the day, which grew from 6 am and reached its first peak around 11 am, and were most active during the evening (7 pm to 9 pm). Additionally, demographics have been identified as an important factor that would impact the way users engage with their apps \cite{seneviratne2015your, zhao2016discovering, kooti2017iphone, van2017describing, tian2020cohort}, e.g., how users select apps or make in-app purchases on their smartphones. \citet{li2017mining} ever analyzed the device-specific apps usage patterns from large-scale android users and they found that users rely less on the cellular network as the price of device model increases. For the correlations between apps usage, Li et al. \cite{li2015characterizing, xu2011identifying, bohmer2011falling} all showed that the last used app would probably impact the next app the user is going to use. However, minimal research has been done for analyzing if any of these features could impact the dwell time of an app. In our work, we conduct the first empirical analysis of how long users will stay with an app on a large data set. We are the first to systematically model how user characteristics (e.g., demographics) and context features (e.g., time, last used app) impact the time user stay with an app. \subsection{App Usage and Engagement Prediction} \label{app_usage_engagement_prediction} \subsubsection{\textbf{Next App and App Engagement Prediction}} Much research work has been conducted on predicting which app user will use (a.k.a.~next app prediction). \rebuttal{Based on the survey \cite{cao2017mining}, we could know that before 2017, most of the app prediction/recommendation works are conducted during 2012-2013.} Tan et al. \cite{tan2012prediction} tried to treat users' app usage patterns as periodic time series cycles and predict the app will be used based on a prediction algorithm with fixed cycle length. Liao et al. \cite{liao2012mining} also predicted the next app based on mined temporal profiles for each app. Additionally, Huang et al \cite{huang2012predicting}, Shin et al. \cite{shin2012understanding} and Zou et al. \cite{zou2013prophet} all pointed out that the latest used app and time are more effective than location and other context information in the next app prediction. After 2017, neural approaches have become increasingly popular. Some researchers proposed different neural models for predicting the next app, including CNN \cite{schmidhuber2015deep} and LSTM \cite{xu2020predicting}, etc. Xu et al. \cite{xu2020predicting} proposed a generic prediction model based on Long Short-term Memory (LSTM), to covert the temporal-sequence dependency and contextual information into a unified feature representation for next app prediction and stated that it outperforms other models. Additionally, Tian et al.~\cite{tian2020identifying} explored the prediction to identify if the pair of two app usage logs belong to the same task. As far as we know, no research has been done for predicting how long users will stay with an app. Only Mathur et al. \cite{mathur2016engagement} tried to model and predict users' attention-based engagements (two levels: focused attention and felt involvement) in the context of smartphones. They conducted the work based on physiological measures (headset readings) within 10 participants, and their research has no works regarding which app users are currently using. In our work, by leveraging a large-scale data set of users' app usage logs, we could be able to model users' engagement (dwell time) within specific apps by exploiting user characteristics, temporal context, and short/long-term behavioural patterns. Most importantly, we investigate the challenges of simultaneously predicting which app user will use and how long the user will stay with this app. \subsubsection{\textbf{Engagement (Dwell Time) Prediction in Other Areas}} For the novel prediction problem proposed in our work, although no research has been conducted on the app dwell time prediction, some researchers investigated the engagement (dwell time) modelling and prediction in other areas, e.g., session-based recommendation (SBR) systems \cite{bogina2017incorporating, zhou2018jump, wangcapturing}, videos watching \cite{wu2018beyond}, news and non-news pages reading \cite{seki2018analysis,homma2018analysis}, and media streaming \cite{vasiloudis2017predicting}. The SBR tasks aim to predict the next click/buying/dwell time based on users' interactions in a session, e.g., buying one item after viewing several products (within a commerce site). They stated that dwell time should be used as a proxy to user satisfaction of the clicked result since clicked through or not is not enough to identify the satisfaction of the user. In their scenario, researchers aim to predict which link/product user would click among a list of recommended similar results (under specific search query). Additionally, they assumed that the longer user stays with the clicked result, the more satisfied the user will be with the result. However, in our dwell time prediction problem, a user would use an app occasionally with no recommendation context, and the longer user stays with this app does not directly mean the user is satisfied with it or not. The dwell time may be affected by the specific app (e.g.,~ a weather app or game app), or whether the user accessed it during commuting or at night while they have more leisure time. Therefore, predicting how long a user will stay with an app is to predict the usage pattern while using the app. It would allow the service provider to optimize the user experience along with its business goals, the apps can be tuned to be more exploratory or exploitative based on the expected length of the usage. The SBR tasks can be solved by item-to-item and matrix factorization methods \cite{hidasi2016general,musto2015word}, Markov Decision Process (MDP) based technique \cite{tavakol2014factored}. Recently, deep learning methods, Recurrent Neural Networks (RNN) have emerged as powerful methods of modelling sequential data in SBR \cite{bogina2017incorporating, zhou2018jump, wangcapturing}. The engagement pattern of the other online services, like video watching \cite{wu2018beyond}, news/non-news page reading \cite{seki2018analysis,homma2018analysis}, and media streaming \cite{vasiloudis2017predicting} have more similar characteristics of apps usage, i.e. how long user would stay could be affected by the category of the content or the original length of the video or news. Additionally, the underlying motivation for engagement prediction of these services is also the same as our work. They consider popularity and engagement as different measures of online behaviour. Although popularity describes the human behaviour of choosing one particular item, it does not describe how users would engage with this item. i.e., popularity is characterized as the willingness to click a video, whereas engagement is the video watching pattern after clicking. By knowing how long user would stay, we could be able to provide users with more satisfying content/services that increase long term user engagement and as a side-benefit. It also allows the service providers to optimize the user experience along with its business goals. Wu et al. \cite{wu2018beyond} conducted a large-scale measurement study of engagement on 5.3 million videos over a two-month period and measured a set of engagement metrics (e.g., watch time, watch percentage) for online videos. They predicted engagement from video context, topics, and channel reputation, etc. Seki et al. \cite{seki2018analysis} and Homma et al. \cite{homma2018analysis} all clarified the characteristics of relationships between dwell time on news/non-news pages reading in order to discover which features are effective for predicting the dwell time, including (1) Dwell time by Device: desktops and mobies; (2) Dwell time by access time; (3) Dwell time by if users visited from inside or outside the site; (4) Dwell time by click and non-click: if the user clicked links in the page; (5) Dwell time by scroll depth. Vasiloudis et al. \cite{vasiloudis2017predicting} explored the prediction of session length in a mobile-focused music streaming service. They predicted the length of a session using contextual and user-based features including gender, age, subscription status, device, network type, duration of the user's last session, and time elapsed since the last session. Given the task similarity between these engagement prediction studies and our focus (app engagement prediction), we selected two of them \cite{vasiloudis2017predicting, wu2018beyond} with the most features that could be extracted from our dataset as the baselines for comparing the performance of our proposed model regarding the app engagement prediction. We all have similar engagement characteristics and the motivation for engagement prediction, e.g., the engagement (dwell time) is originally correlated with the content category and more exploratory or exploitative service could be provided based on the expected length of the usage. In summary, for the traditional next app prediction task, we selected four models from previous works that could be fitted to our dataset as baselines, include three works \cite{tan2012prediction, shin2012understanding,zou2013prophet} based on the temporal pattern and contextual features and one recent work based on neural approach (LSTM) \cite{xu2020predicting}. For the joint prediction problem of predicting the next app and engagement level together, since there is no existing similar joint prediction work (app dwell time has a high dependency on which app user is engaging), we added those two recent works \cite{vasiloudis2017predicting,wu2018beyond} for predicting dwell time as baselines. The only difference is they solely predict how long a user will stay based on the specific item, without predicting on which item the user will engage with. In order to make them comparable baselines to our work, we assumed the ground truth of the next app is known for those two prior works \cite{wu2018beyond, vasiloudis2017predicting} and leveraged them specifically for predicting engagement (dwell time) of the known next app. This demonstrates the upper bound of those approaches (oracle performance) regarding the joint prediction problem. \section{Data and Descriptive Analysis} We start by describing the data used in this study, followed by some fundamental analysis that demonstrates the characteristics of our data. \subsection{Dataset} \label{sec:dataset} \begin{table} \scriptsize \setlength{\tabcolsep}{3pt} \caption{Overall statistics of the dataset.} \label{tab:demog_info} \scalebox{1}{\begin{tabular}{lll|lll} \toprule \textbf{OS}&\textbf{\%Logs}&\textbf{\%Users}&\textbf{Device}&\textbf{\%Logs}&\textbf{\%Users}\\ \midrule android&78.0\%&57.5\%&Phone&94.3\%&90.0\%\\ ios&22.0\%&42.5\%&Tablet&5.7\%&10.0\%\\ \midrule \textbf{Age}&\textbf{\%Logs}&\textbf{\%Users}& \textbf{Gender}&\textbf{\%Logs}&\textbf{\%Users}\\ \midrule 13-17&5.7\%&9.0\%&female&44.1\%&51.8\%\\ 18-24&13.9\%&18.4\%&male&55.9\%&48.2\%\\ 25-34&32.2\%&30.3\%\\ 35-54&43.2\%&36.5\%\\ 55+&5.0\%&5.8\%\\ \bottomrule \end{tabular}} \end{table} The dataset used in our paper is collected from a mobile advertising company, a library that mobile developers integrate into their apps to measure app usage and allow in-app advertising. We collected a sample of logs from a week in March 2017 of more than 1.3 million logs with over 9K different apps and 12K users from the United States. Each log consists of the user’s general app usage information, such as demographics, timestamp, app category, app id and time spent. Each app belongs to one of 45 categories ranging from social, communication to business, etc. The definition of these app categories is consistent with the Google Play App taxonomy \cite{GooglePlayAppCat}. Table~\ref{tab:demog_info} shows various statistics of our dataset. Either Android or iOS operates the devices. 51.8\% of app users are female, and most logs (over 70\%) are generated by users between 25 and 54 years old.\footnote{Users have been classified into five age ranges in our dataset: 13-17,18-24,25-34,35-54 and 55+.} \begin{figure} \centering \includegraphics[width=0.8\textwidth]{pictures//Session_Definition.jpg} \caption{Visualisation of app usage logs and the corresponding app usage duration. Five minutes of inactivity is used for segmenting mobile sessions.} \label{fig:session} \end{figure} Following previous work \cite{carrascal2015situ}, we consider a five-minute range of inactivity as the signal of ending a session as shown in Figure~\ref{fig:session}. If the user leaves an app but revisits any app within 5 minutes the \emph{session} continues; otherwise, the \emph{session} ends. In our work, we aim to predict which app the user will use next and how long the user will stay with that app. The app usage duration we aim to predict is calculated as follows (as shown in Figure~\ref{fig:session}): we aggregate the consecutive app usage duration of the same app within each session. The app usage duration can be also referred to as app \emph{dwell time}. We adopt this definition as the unit of our analysis for the rest of the paper. Note that we only consider user-triggered events; i.e.~we do not include events that are triggered by background refresh when conducting our analysis. To reduce bias from users with a low level of engagement, we restricted our sample to those users who interacted with apps from at least five different categories. All the data was anonymized by removing all personally identifiable data prior to processing. \subsection{Distributions of App Usage} \begin{table} \scriptsize \centering \caption{Top 10 popular app categories.} \label{tab:top_app_category} \scalebox{1}{\begin{tabular}{lll} \toprule \textbf{App Categories}&\textbf{\%Sessions}&\textbf{App Function Examples}\\ \midrule productivity&28.6\%&mail, calendar, notepad\\ social&10.6\%&SNS, dating\\ tools&8.3\%&caculator, screen lock, light\\ communication&6.8\%&SMS, IM, free video calls\\ entertainment&5.1\%&TV player, streaming video\\ utilities&3.3\%&network, cleaner\\ sports&3.1\%&live sports, sports news\\ music&2.7\%&music player\\ lifestyle&2.5\%&diary, discount, recipe\\ arcade&2.4\%&games\\ \bottomrule \end{tabular}} \end{table} \label{engagment_level_definition} \begin{figure} \centering \includegraphics[width = 0.75\textwidth]{pictures//engagement_levels_box.jpg} \caption{Overall average app usage duration for different app categories.} \label{fig:engagement_duration} \end{figure} \begin{figure} \centering \subfloat[PDF (Probability Density Function)]{ \label{fig:session_duration_pdf} \includegraphics[height = 1.9in]{pictures//Session_duration_distribution_pdf.jpg} } \subfloat[CDF (Cumulative Distribution Function)]{ \label{fig:session_duration_cdf} \includegraphics[height = 1.9in]{pictures//Session_duration_distribution_cdf.jpg} } \caption{PDF and CDF of app usage duration across all apps.} \label{fig:session_duration} \end{figure} We start by presenting the distributions of the popularity of apps. The popularity of an app category can be measured using the total number of sessions. Table~\ref{tab:top_app_category} shows the most popular app categories in our dataset. Generally, users are more likely to interact with app categories like productivity, social, tools, communication, and entertainment apps nowadays. We also illustrate several examples of the most popular functionalities of the corresponding apps within each category. Additionally, we show the average app usage duration for different app categories in Figure~\ref{fig:engagement_duration}, which ranges from less than 1 minute to over 10 minutes. We find that users always spend longer time when they are engaging with some app categories for relaxation, such as comics and games apps (i.e., card, word, puzzle, and board). It also states that different app categories initially have different lengths of app usage duration, e.g., game apps have a much longer duration than communication apps. On average for all the app categories, our users' app dwell time lasted about 2.5 minutes. In Figure~\ref{fig:session_duration}, we show the probability density function (PDF) and cumulative distribution function (CDF) of app usage duration. We can find that most of the app usage (93.7\%) is less than 10 minutes and 80\% of them only last less than 2 minutes. We then look at how users engage with their apps throughout the day. Figure~\ref{fig:hour_distribution} plots the scaled amount of sessions (using min-max normalization) and average app usage duration each hour. We can find that the total app usage (in terms of session amount) is at its maximum in the afternoon and evening, peaking at around 7 PM. This aligns with findings reported in~\cite{van2017describing,bohmer2011falling}. Figure~\ref{fig:hour_distribution} also shows the average app dwell time regarding the different hours of the day. Generally, the average app usage duration across the day is between 2 minutes and 3 minutes. The duration increases after 6 PM and drops after 1 AM. This might be due to people have more leisure time during the non-working hours. We indeed find that the app categories associated with longer duration at late night are game and tool (system cleaner/VPN) apps. \begin{figure} \centering \includegraphics[width=0.65\textwidth]{pictures//New_Hour_Distribution.jpg} \caption{App usage patterns across a day.} \label{fig:hour_distribution} \end{figure} \subsection{Engagement Level Definition} \label{engagment_level_definition} To evaluate the performance of app usage duration prediction more intuitively, we propose to represent the time length of each duration as a discrete value, i.e., we classify the app usage duration into three engagement levels: light, medium, and intensive. Additionally, as we have found in Figure~\ref{fig:engagement_duration} that different app categories initially have different lengths of app usage duration, so it may not be reasonable to label the engagement levels without differentiating app categories. Specifically, to assign the corresponding engagement level of each app usage duration: (1) we first calculate the quantiles (33\% and 67\%) of the duration for different app categories respectively; (2) then we assign the level label to each duration based on their corresponding app category quantiles. For example, the 33\% and 67\% quantiles of weather apps are 6 seconds and 23 seconds respectively. If the current usage duration of the weather app is 10 seconds, then its engagement level is medium. For the game apps whose 33\% and 67\% quantiles are 1.3 minutes and 5.4 minutes respectively. When a game app usage duration is longer than 5.4 minutes, its engagement level is intensive. \section{Experimental Results} In this section, we measure the performance of our proposed prediction models (\S\ref{sec:models}). Experiments are conducted on a real-world app usage log data (\S\ref{sec:dataset}). We use 70\% of the data for each user as training data and the remaining 30\% as test data. We first evaluate the performance of our proposed prediction model on the classic prediction problem, predicting the next app (\S\ref{app_prediction}). Then the three joint learning strategies for predicting the next app and engagement level simultaneously (\S\ref{sec:jointmodels}) are thoroughly evaluated from different perspectives. \subsection{Evaluation} In our proposed prediction models, we measure the performance of all prediction problems based on four metrics: accuracy, precision, recall and F1 score: The accuracy in our problem is defined as the fraction of correctly classified samples; The precision is defined as the ratio: \begin{equation} \frac{tp}{(tp + fp)} , \end{equation} where $tp$ is the number of true positives and $fp$ the number of false positives. The precision is intuitively the ability of the classifier not to label as positive a sample that is negative. The recall is the ratio: \begin{equation} \frac{tp}{tp+fn} , \end{equation} where $fn$ is the number of false negatives. The recall is intuitively the ability of the classifier to find all the positive samples; The F1 score can be interpreted as a weighted average of the precision and recall, where an F1 score reaches its best value at 1 and worst score at 0. The relative contribution of precision and recall to the F1 score is equal. The formula for the F1 score is: \begin{equation} F1 = 2*\frac{precision *accuracy}{precision + accuracy}. \end{equation} Please note that in our multi-class case, all the precision, recall, and f1 scores are the weighted averages of scores for each class. In order to account for label imbalance, metrics are calculated for each label, and their averages are weighted by support (the number of true instances for each label). For the next app prediction results, we will count the item as correctly predicted when the predicted app is exactly the same as the ground truth app. While evaluating the joint prediction problem (both next app and engagement level), a correctly classified sample indicates that both the predicted app and predicted engagement level are correct. If either of the prediction is wrong, it will not be counted as a correct classification. \subsection{Baselines} \subsubsection{Next App Usage Prediction} In order to comprehensively measure the performance of our proposed hybrid next app prediction model (\S\ref{app_prediction}), we compare it with state-of-the-art counterparts. \rebuttal{Based on the available sources of evidence in our dataset, we first select the two common baseline methodologies: MFU (Most Frequently Used) and MRU (Most Recently Used) \cite{shin2012understanding, xu2013preference, zou2013prophet}. We then tested additional three methodologies from previous works which conducted the next app prediction by combining app usage history and contexts in a unified manner: SVM+Context \cite{shin2012understanding}, CPD \cite{tan2012prediction} and BN \cite{zou2013prophet}. Recently, the neural approaches are popular in solving the time sequence problems, we also investigated the performance of app usage prediction based on LSTM \cite{xu2020predicting} as the baseline:} \begin{itemize} \item \textit{MFU}: the predicted app is the most frequently used app. \item \textit{MRU}: the predicted app is the most recently used app. \item \textit{SVM+Context}: Shin et al. \cite{shin2012understanding} used a SVM classifier \cite{bishop2006pattern} and context information (i.e., day of week, hour of day, last used app and time since last app usage) to predict the next app user will use. \item \textit{CPD}: Tan, et al. \cite{tan2012prediction} proposed a prediction framework: Prediction Algorithm with Fixed Cycle Length (PAFCL). They hypothesized that each application has different usage probabilities in the different time slots of a cycle. CPD (Cumulative Probability Distribution) is the method used to choose applications with higher probability as the candidates based on computing the probabilities of each used app in the specific time slot. \item \textit{BN}: Zou et al. \cite{zou2013prophet} proposed a Bayes Network (BN) model which is a linear combination of $p(a_n = A|a_{n-1} = A_{n-1})$ (based on last used app $A_{n-1}$) and $p(a_n = A|a_{n-2} = A_{n-2})$ (second last used app $A_{n-2}$). \rebuttal{\item \textit{LSTM}: Xu et al. \cite{xu2020predicting} proposed a generic prediction model based on Long Short-term Memory (LSTM), which is an enhancement of the recurrent neural network (RNN) model. The proposed model converts the temporal-sequence dependency and contextual information into a unified feature representation for the next app prediction.} \end{itemize} \subsubsection{Next App and Engagement Level Joint Prediction} Since we are the first work proposed to predict which app user will use and how long the user will stay on that app simultaneously, where the time spent has a high dependency with which app user is engaging, no previous related work could be identified as our baseline methodologies. Therefore, we propose the baselines from two kinds of approaches. Firstly, by following the classic baselines (MFU and MRU) in the next app prediction problem, we present two naive prediction methods as the baselines for our proposed joint prediction problem. Secondly, two recent works on dwell time prediction of online services (e.g., video \cite{wu2018beyond} and media streaming \cite{vasiloudis2017predicting}) are selected as baselines. Similar to our work, how long a user stays with an item in these services originally have associations with the content category, and could also be affected by user characteristics and contextual features. The only difference is that they solely predict how long a user will stay based on the specific item, whereas no prediction on which item the user will engage is required. In order to make them comparable baselines, we assumed the ground truth of the next app is known and leveraged those two prior works \cite{vasiloudis2017predicting,wu2018beyond} for predicting engagement (dwell time) of the oracle app. This demonstrates the upper bound of those approaches (oracle performance) within the joint prediction task. \begin{itemize} \item \textit{MFU}: In our joint prediction problem, we discuss the usage frequency of the two fields together: the next app and engagement level. Then the MFU baseline states that every time we recommend the tuple $\left(a, e\right)$ as the app $a$ and engagement level $e$ based on the popularity of the tuples. \item \textit{MRU}: Similar to the MRU in next app prediction, we hypothesize that a correlation between two sequential tuples of app and engagement level may exist. For example, a user may always like to access the weather app for 10 seconds and then access the news app for 5 minutes. Therefore we generate a correlation-based baseline approach for our joint prediction problem, which aims to predict the next app and engagement level based on the correlation between two sequential tuples $(a', e')$ and $(a, e)$. We first calculate all the transition probabilities from one tuple to another. When we know the last usage tuple is $(a', e')$, we could recommend the tuple $(a, e)$ that has the highest probability to be used next. \rebuttal{\item \textit{CSP}: Wu et al. \cite{wu2018beyond} conducted a large-scale measurement study of engagement on videos. They predicted engagement from video context, topics, and channel reputation, etc. They used linear regression with L2-regularization to predict engagement metrics and state that the Channel Specific Predictor (CSP) performs best, which is to train a separate predictor for each channel instead of using the shared predictor. To fit into our scenario, we generate the same CSP for each app category with their proposed features available in our dataset (e.g., the one-hot encoding of category, mean number of daily usage, mean, std and five points summary of past engagement (dwell time), etc.). The performance of the joint prediction problem is reported based on the oracle app and the predicted dwell time (which would be transformed to engagement levels according to our definition in Sec. \ref{engagment_level_definition}.)} \rebuttal{\item \textit{Aggregated}: Vasiloudis et al. \cite{vasiloudis2017predicting} presented the first analysis of session length in a mobile-focused online service (i.e. music streaming service). They showed that the time length of sessions can differ significantly between users. They used gradient boosted trees with appropriate objectives to predict the length of a session using contextual and user-based features. Their experiment results showed that the aggregated model trained with all the data performed better than the personalized models trained on each user's data. To fit into our prediction problem, we also trained the aggregated model based on all data with their proposed features available in our dataset (e.g., gender, age, device, duration of the user's last session and time elapsed since the last session, etc.). As we mentioned before, the performance of the joint prediction problem is reported based on the oracle app and the predicted dwell time (which would be transformed to engagement levels according to our definition in Sec. \ref{engagment_level_definition}).} \end{itemize} \subsection{Hybrid Next App Prediction Model} \label{app_usage_prediction_evaluate} Our analysis starts with the hybrid next app prediction results given it is the unified component leveraged by all the three different joint learning strategies. It is used at the first step for inferring the next app user will use before predicting its engagement level (Figure~\ref{fig:sequential_stacking}). Table~\ref{tab:personalized_classifier} shows the performance of baseline methodologies and our proposed hybrid next app prediction model. We test our model with a set of state-of-the-art classification models, including Random Forests \cite{breiman2001random}, L2-regularized Logistic Regression \cite{hosmer2013applied}, K Nearest Neighbours \cite{cover1967nearest} and Support Vector Machines \cite{burges1998tutorial}. These models construct different prediction functions for the data from different aspects, and they can provide more robust results for our prediction. Since our proposed hybrid next app prediction model (\S\ref{app_prediction}) involves the prediction results of two predictive components (Eq. (13)), we select the best classifiers for both of them within the hybrid model, which combines the results of generic app category prediction with Random Forest classifier and the results of personalized next app prediction with SVM classifier. \begin{table}[t] \centering \scriptsize \caption{Performance comparison of next app prediction models ($\ast$ indicates statistical significant (p$\leq$0.01) using two-tailed T-test when compared our hybrid next app prediction model to the best baseline model (LSTM).} \label{tab:personalized_classifier} \scalebox{1}{\begin{tabular}{ l c c c c} \toprule \multirow{2}{*}{\textbf{Method}}&\multicolumn{4}{c}{\textbf{Measurement}}\\ \cline{2-5} &\textbf{Accuracy}&\textbf{Precision}&\textbf{Recall}&\textbf{F1}\\ \midrule MFU &0.486&0.489&0.486&0.486\\ MRU &0.518&0.521&0.518&0.518\\ CPD \cite{tan2012prediction}&0.424&0.419&0.424&0.369\\ BN \cite{zou2013prophet}&0.453&0.483&0.453&0.467\\ SVM+Context \cite{shin2012understanding}&0.606&0.563&0.606&0.572\\ \rebuttal{LSTM \cite{xu2020predicting}} &\rebuttal{0.525}&\rebuttal{0.660}&\rebuttal{0.525}&\rebuttal{0.576}\\ \midrule Our Hybrid Model $^\ast$&\textbf{0.640}&\textbf{0.607}&\textbf{0.640}&\textbf{0.613}\\ \bottomrule \end{tabular}} \end{table} From Table~\ref{tab:personalized_classifier}, we can find that our proposed hybrid next app prediction model could significantly improve the performance of the best baseline model (LSTM) by 6.4\% on the F1 measure. The worse performance of LSTM is expected since it could not incorporate any user characteristics and contexts (e.g., access time, device type, etc.) during the prediction. While our proposed hybrid next app prediction model not only takes the user characteristics and contextual information into consideration but also learn from users’ common patterns to overcome important sources of prediction errors resulting from insufficient training data. It also states that through the use of community similarity and common usage patterns learned based on different app categories, we can improve the next app usage prediction by identifying the generic usage patterns present in similar users - rather than relying solely on the specific app usage patterns. This is also consistent with the findings from previous studies \cite{do2014and, zhao2019appusage2vec} which claim that the generic model can improve the predictive performance of models solely based on individual's logs. Therefore, our proposed hybrid next app prediction model is adopted to apply to further engagement level prediction for different joint learning strategies. \subsection{Next App Usage and App Engagement Level Joint Prediction Strategies} \label{joint_prediction_evaluate} We first evaluate how different models perform for solving our proposed joint prediction problem: which app user will use next and how long the user will stay with this app? Then we further investigate the predictive ability of features in the two prediction problems respectively and the prediction effectiveness of our proposed different joint prediction strategies. As mentioned, our hybrid next app prediction model is applied to the first stage prediction on the next app for all the joint learning strategies (Figure~\ref{fig:sequential_stacking}). For the prediction of engagement level, the predicted app will be represented in different ways based on different joint prediction strategies. For the sequential and stacking based joint model, the predicted app will be used to select the specific engagement level classifier with the corresponding app category (Eq. (14)). For the boosting based joint model, the predicted app coming from the first stage of next app prediction could only be treated as the input feature for the next step prediction of engagement level (Eq. (12)). Table~\ref{tab:ensembling} shows the ultimate performance of different joint prediction strategies and all baselines. \begin{table}[t] \centering \scriptsize \caption{Performance comparison of joint learning prediction models ($\ast$ indicates statistical significant (p$\leq$0.01) using two-tailed T-test compared to the best baseline (CSP)).} \label{tab:ensembling} \scalebox{1}{\begin{threeparttable} \begin{tabular}{l c c c c } \hline \multirow{2}{*}\textbf{Model}&\multicolumn{4}{c}{\textbf{Measurement}}\\ \cline{2-5} &\textbf{Accuracy}&\textbf{Precision}&\textbf{Recall}&\textbf{F1}\\ \midrule MFU &0.286&0.286&0.286&0.286\\ MRU &0.308&0.307&0.308&0.308\\ \rebuttal{Aggregated \cite{vasiloudis2017predicting} $^\triangleright$} &\rebuttal{0.347}&\rebuttal{0.742}&\rebuttal{0.347}&\rebuttal{0.448}\\ \rebuttal{CSP \cite{wu2018beyond} $^\triangleright$}&\rebuttal{0.339}&\rebuttal{0.729}&\rebuttal{0.339}&\rebuttal{0.467}\\ \midrule Sequential$^\ast$&0.375&0.382&0.375&0.369\\ Stacking$^\ast$&0.374&0.381&0.374&0.365\\ Boosting$^\ast$&\textbf{0.485}&\textbf{0.483}&\textbf{0.485}&\textbf{0.483}\\ \bottomrule \end{tabular} \begin{tablenotes} \item $\triangleright$: We assumed the ground truth of the next app is known and leveraged these baselines for predicting engagement (dwell time) of the oracle app. The performance reported in table demonstrates the upper bound of those approaches (oracle performance) regarding the joint prediction problem. \end{tablenotes} \end{threeparttable}} \end{table} We can find that all our proposed joint prediction models are better than the \rebuttal{two classic baselines: MFU and MRU. For another two baselines, we can observe that even we assumed the ground truth of the next app is known, the upper bound performance of these approaches could not beat our proposed best joint prediction model based on boosting strategy. To be specific, it states that we assume the predicted app is exactly the same as the ground truth and only evaluate the engagement level prediction performance, these baselines have performed worse than our boosting-based joint prediction model. It mostly because they didn't model the engagement with comprehensive characteristics as our proposed model, where we take the user characteristics, short/long-term usage patterns all into consideration. Therefore, if the next app prediction task is added, the worse performance of the joint prediction problem should also be expected for these baselines.} Among all the three proposed joint prediction strategies, stacking and boosting based strategies are two advanced approaches originally proposed to improve the performance with the most straightforward strategy, sequential based strategy. However, we find that the stacking based strategy does not improve the performance when compared with the benchmark sequential based strategy. This might be due to that, in our scenario, the base learners within stacking are not trained for the same target (we have two different prediction tasks: app and engagement level) where the stacking principles do not apply. On the other hand, the boosting strategy works best compared to all other joint models. It respectively outperforms the baseline models over 56\% and the sequential/stacking models about 31\% on F1 measure. We mainly focus on investigating the boosting and sequential strategies in the later sections about how boosting helps in the joint prediction. Firstly, besides the overall performance reported in Table~\ref{tab:ensembling}, we look into the detailed prediction results. It demonstrates that the accuracy of next app prediction and engagement level prediction respectively are: 64\% (app) and 58.6\% (engagement level) for sequential strategy, 85.6\% (app) and 56.7\% (engagement level) for boosting strategy, where the accuracy of engagement level is calculated only based on the data with right predicted apps. So we can find that the improvement of overall performance for boosting strategy is mainly because of the "error-correction" step which corrects the app prediction results. In the following sections, we will first analyze the feature importance within the two prediction problems respectively, especially focus on exploring the predictive ability of the newly proposed features. Then we will dig into how is the effectiveness of boosting based strategy compared to the sequential based strategy. \subsubsection{Feature Analysis} \label{sec:feature_importance} \begin{table}[t] \centering \scriptsize \caption{Feature importance (MDI) of app category prediction. } \label{tab:randome_forest_feature_importance} \scalebox{1}{\begin{tabular}{|l|c|c|} \hline \textbf{Feature}&\textbf{Feature Type}&\textbf{Importance (MDI)}\\ \hline Total$\_$App$\_$Usage$\_$Frequency&User&0.023\\ Hour&Temporal&0.011\\ Periodic$\_$Feature&Long-term&0.011\\ Total$\_$App$\_$Usage$\_$Duration&User&0.010\\ Historical$\_$App$\_$Preference&Long-term&0.005\\ Total$\_$Unique$\_$App$\_$Amount&User&0.005\\ Age&User&0.004\\ App$\_$Preference$\_$Last$\_$Day&Short-term&0.003\\ Weekday&Temporal&0.002\\ Gender&User&0.002\\ App$\_$Preference$\_$Last$\_$Hour&Short-term&0.002\\ Device$\_$Type&User&0.001\\ App$\_$Preference$\_$Last$\_$Session&Short-term&0.001\\ \hline \end{tabular}} \end{table} The sequential based strategy is implemented by conducting the app prediction and the engagement level prediction sequentially, where the app prediction is absolutely independent with the further engagement level prediction. Therefore, we discuss the analysis of the most impactful features for those two tasks respectively. The next app prediction within the sequential strategy is implemented as same as our proposed hybrid next app prediction model, which would infer what app category the user will use and then select the specific app given this predicted app category. To make the comparison more intuitively, we conduct the analysis within the app category level. As we mentioned above, the random forest is selected as the best classifier for the app category prediction problem. The random forest can be used to rank features by their importance in the classifier, which provides useful insights about the discriminative power of the features in the considered problem setting. \textit{Mean Impurity Decrease (MDI)} is the most common way to obtain feature importance from random trees \cite{breiman2001random}. It is computed by averaging across all the trees in the forest the amount of impurity removed by each feature while traversing down the tree, weighted by the proportion of samples that reached that node during training. Using this method, we obtained the feature importance for all features in the app category prediction, as listed in Table~\ref{tab:randome_forest_feature_importance}. We find that besides the critical temporal feature \emph{hour}, the most important categories of features are mostly user and long-term context features. Compared to user characteristics features such as demographics and devices, the total usage (frequency, duration, and unique app amount) maintain higher impacts on the next app category prediction. The hour of day feature has been used to identify the salient pattern within app usage behaviour in many previous works \cite{huang2012predicting, shin2012understanding, liao2012mining}, e.g. the user usually set an alarm at around 23:00. The popularity of app usage (historical app preference) is also a famous feature that has been established by previous works \cite{liao2013mining, do2014and}. Additionally, our finding of the periodic pattern is consistent with the previous works on next app prediction, where the periodic patterns have been identified as the effective feature for inferring the app usage pattern \cite{tan2012prediction,liao2012mining,liao2013mining}. Liao et al. \cite{liao2013mining} also stated that the periodical usage feature is the most difficult one to be substituted by other features. \begin{table}[t] \centering \scriptsize \caption{Top feature weights (standardized coefficients $\geq$ 0.001) for logistic regression model of engagement level prediction. $\ast$ indicates p-value $\leq$ 0.001 using Chi-Squared test.} \label{tab:Feature_Importance_Specified} \scalebox{1}{\begin{tabular}{|l|c|c|} \hline \textbf{Feature}&\textbf{Feature Type}&\textbf{Weight}\\ \hline Historical$\_$Level$\_$Light$^\ast$&Long-term&0.571\\ Historical$\_$Level$\_$Medium$^\ast$&Long-term&0.197\\ Total$\_$App$\_$Usage$\_$Duration$^\ast$&User&0.175\\ Historical$\_$Level$\_$Intensive$^\ast$&Long-term&0.112\\ Periodic$\_$Feature$^\ast$&Long-term&0.070\\ Age$^\ast$&User&0.032\\ Last$\_$Used$\_$App$^\ast$&Short-term&0.019\\ Hour$^\ast$&Temporal&0.008\\ Weekday&Temporal&0.002\\ Last$\_$Engagement$\_$Level$^\ast$&Short-term&0.001\\ \hline \end{tabular}} \end{table} The engagement level prediction is the novel problem proposed in our work and we extracted many different predictive features from user\&device characteristics, temporal pattern, and short/long-term context (\S\ref{infering_features}) to infer how long the user will stay with an app. Similarly, since the engagement level prediction within the sequential strategy can be studied separately, we discuss the impacts brought by different features for engagement level prediction within the sequential based strategy. We opt to build a classifier for predicting users' engagement with three levels: \emph{light}, \emph{Medium} and \emph{Intensive}. Hence, the problem of modelling user engagement turns into a multi-class classification problem. Similar to the next app prediction, we test and empirically compare the performance of a wide range of classification techniques, including Random Forests (RF), L2-regularized Logistic Regression (LR), K Nearest Neighbours (KNN), and Support Vector Machines (SVM), for predicting the app engagement level, where the Logistic Regression classifier performs best. Then we examine the contribution of each feature based on the feature coefficients in the logistic regression model. To compare the importance of different features, we divide each numeric variable by two times its standard deviation~\cite{gelman2008scaling}. Through this way, the resulting coefficients are directly comparable for both binary variables (e.g.,~categorical dummy variable) and numerical features. Table~\ref{tab:Feature_Importance_Specified} reports the top feature weights (standardized coefficients $\geq$ 0.001) of the Logistic Regression model for the engagement level prediction. We can find that most of the top features are originated from the long-term context features: historical engagement level preference and periodic pattern. It is not surprising that the historical pattern has more influence on how long a user will stay with an app. If the user always prefers to play games for a longer time, then he may still spend more time in the game app this time. The periodic feature has more impacts on users' engagement level than the temporal context, hour, and weekday. This demonstrates that no matter when the user uses this app, the time since the last use of this app is more important for inferring how long the user will engage with this app. Additionally, the last used app has more impacts on predicting the engagement level compared to all short-term context features. This could provide more insights for the app developers to recommend the contents of different time lengths according to the last used app to improve the user experience. Another finding is that we observe age is the most important signal among all demographics and device characteristics when inferring the app usage duration. \subsubsection{How Effective are Boosting-based vs. Sequential-based Strategies?} We have shown the boosting based strategy outperforms the benchmark sequential based strategy by the performance margin of 31\% on the F1 measure. Therefore we further conduct some error analysis to understand the underlying reasons. Firstly, for the novel prediction problem on engagement level, the sequential and boosting based strategies achieve similar performance, which are 58.6\% and 56.7\% respectively on accuracy. It demonstrates that even the boosting based strategy gets better overall performance in our joint prediction problem, it cannot improve the engagement level prediction results. We further analyze the prediction ability on app engagement level prediction with our proposed sequential strategy. We select only the engagement level prediction results when the next app is correctly predicted. Figure~\ref{fig:engagement_level_error_heatmap} shows the confusion matrix of the app engagement level prediction results. For the wrongly predicted results of all engagement levels, we can find that they have higher probabilities to be predicted into the adjacent level. For example, for the intensive engagement level, 19\% of them are misclassified as a medium level, which covers about 95\% of the wrongly predicted results. Similarly, for the light engagement level, 25\% of them are misclassified as a medium level, which is higher than those that are misclassified as intensive. The engagement level prediction results of boosting based strategy also get a similar confusion matrix as shown in Figure~\ref{fig:engagement_level_error_heatmap}. We now focus on exploring how boosting is more effective in the next app prediction as follows. \begin{figure} \centering \includegraphics[height = 1.8in]{pictures//engagement_level_error_analysis.jpg} \caption{The confusion matrix of our prediction model on the engagement level.} \label{fig:engagement_level_error_heatmap} \end{figure} For the next app prediction, we have reported that the boosting based strategy improves the accuracy from 64\% to 85.6\%, which is resulted from the "error-correction" step. We then compare the app prediction results of sequential based and boosting based strategies. For the sequential based strategy, we found that the incorrect results are mainly generated from three reasons: \begin{table}[t] \centering \scriptsize \caption{\rebuttal{Illustration of Case Studies in Next App Prediction}} \label{tab:case_study} \scalebox{0.85}{\begin{tabular}{p{2.2cm}|p{2cm}p{2cm}p{2cm}p{6cm}} \toprule \textbf{Error Reason Type}&\textbf{Predicted Result}&\textbf{Ground Truth}&\textbf{Correction while Boosting}&\textbf{Correction/Uncorrection Reason}\\ \midrule Global Popularity&productivity&widgets, medical, transportation&widgets, medical, transportation&The "pesudo-residuals" are applied as ground truth in boosting makes the model less impacted by the global popularity of app categories within the dataset.\\ \midrule Short Usage Interval&card&casino&casino&Additional information are provided by the engagement features added in the boosting strategy. Last engagement of casino is longer than the card app, so these cases are corrected from card to casino.\\ \cmidrule{2-5} &arcade&adventure&No&No additional information could be provided based on engagement.\\ \midrule Similar App Usage Frequency&lifestyle&food-and-drinks&food-and-drinks&Boosting helps when the engagement pattern provides additional information. Specifically, the results are corrected by boosting since the historical engagement pattern of food-and-drink apps usage of this user is longer than lifestyle apps. \\ \cmidrule{2-5} &health-and-fitness&medical&No&None of them are corrected by boosting since no difference exists in the historical engagement pattern of these two apps of the user.\\ \bottomrule \end{tabular}} \end{table} \noindent (a) \textit{\textbf{Global popularity}}. \rebuttal{We find that for 66.7\% (30/45) of the app categories, the top category they were misclassified as is \emph{productivity}. For example, 37.4\% of widgets apps are wrongly predicted as productivity, 31,7\% of medical apps are wrongly predicted as productivity, and 27.2\% of transportation apps are also wrongly predicted as productivity.} This could be easily explained since the productivity apps have the highest global popularity among all the app categories. It results in our generic app category classifier inferring that the user has a higher probability to use the productivity apps given all users' data. By analysing these cases, we find that the boosting strategy resolves most of the issues resulted from global popularity. For example, 25.4\% of widgets apps and 12.8\% of transportation apps are corrected by boosting from being misclassified into the productivity apps. This is because that the prediction model in the boosting step does not involve the global popularity of app categories. Since the "pseudo-residuals" (Figure~\ref{fig:Boosting}) are applied as the ground truth, this makes the model more sensitive for predicting users' app usage based on the context and user characteristics, rather than the global popularity of app categories within the dataset. \noindent (b) \textit{\textbf{Short usage interval}}. Another important factor that accounts for the misclassification within the sequential based strategy is the time interval (periodic feature) between app usage. We observe that for those users whose historical app preference deviates from an average user (e.g., productivity is not the top preferred app), the periodic feature (time since the last usage) would have stronger impacts. \rebuttal{For example, 30.8\% of the adventure apps are wrongly predicted as arcade apps given the time from the last usage of arcade app is short.} Since the model learned that the shorter the time interval, the higher probability the same app would be used again. In these cases, even the adventure has a higher usage frequency in the user's historical app usage pattern, it would be wrongly predicted as arcade since arcade has a higher probability to be re-accessed in a short period of time. \noindent (c) \textit{\textbf{Similar app usage frequency}}. The third major reason for the misclassified cases is that when two app categories are all recently used with a similar frequency, the one with the higher personalized historical usage frequency would be selected. \rebuttal{For example, 11.4\% of medical apps are wrongly predicted as health-and-fitness apps because that the medical app and health-and-fitness app are always used in the same session,} the health-and-fitness app is predicted as the result since it has higher popularity within the user's historical app usage pattern. For the latter two error analysis in the sequential based strategy (described above as (b) and (c)), we find that the boosting strategy only helps some of the cases when the engagement information could provide additional insights. For example, among the wrongly predicted 30.8\% adventure apps, only 5\% of adventure apps are corrected from arcade by boosting since the last engagement level of adventure is longer than arcade. For those cases without this additional information from engagement, they are still wrongly predicted. However, for some specific cases, e.g., 7.8\% of casino apps are predicted as card apps for the same reason as adventure\&arcade apps, but all of these 7.8\% cases are corrected to casino with boosting. This is because for all the cases the last engagement of casino is longer than the card app. Similarly, for the cases which are wrongly predicted because they have similar recent usage patterns, the boosting only helps when the engagement pattern provides additional info. For example, 3.7\% of food-and-drink apps are corrected by boosting from lifestyle apps. This is because the historical engagement pattern of food-and-drink apps usage of this user is longer than lifestyle apps. However, for the 11.4\% wrongly predicted medical apps, none of them is corrected by boosting since no difference exists in the historical engagement level pattern of these two apps. To make the benefits brought by boosting strategy clearer, we also added a summary table of the case studies as Table~\ref{tab:case_study}, where we can find the corresponding reasons about why some of the cases are corrected by boosting but some others are not. \section{Conclusion} In this paper, we propose to predict both users' next app and the engagement level at the same time. For the first time - to the best of our knowledge - a comprehensive analysis of users' app dwell time is conducted based on the large-scale commercial mobile logs, especially focusing on inferring the correlations between different predictive features and users' app usage duration. We find that the users' historical engagement pattern, periodic behaviour pattern, and the recent usage pattern have more impacts when inferring users' app dwell time. To solve our joint prediction problem on the next app and app engagement level, we propose three strategies, where the boosting based joint prediction model works best. Our experimental results demonstrate that users' next app and engagement level could be effectively predicted at the same time, and our proposed prediction method outperforms all baseline experiments by a large margin. Our work can help for providing more satisfying services to users for improving users' experience on mobile devices. \section{App Usage and Engagement Prediction} \label{sec:models} Based on the statistical analysis in Section~\ref{infering_features} of app usage duration, we further focus on answering the important question: could we predict which app user will use and how long the user will stay on this app simultaneously? In this section, we start by formulating the next app usage and app dwell time prediction problem, followed by presenting several joint learning strategies for solving these two prediction problems simultaneously. \subsection{Problem Formulation} \label{sec:problem_formula} For the next app prediction, many previous researchers have extracted the predictive features and proposed methods to solve it \cite{huang2012predicting,shin2012understanding, zou2013prophet,yan2012fast}. Similar to Ricardo et al. \cite{baeza2015predicting}, we model the prediction of the next app as a supervised classification problem. For the novel prediction problem proposed in our work, which is to infer users' app dwell time, we also model it as a multi-class classification problem and the continuous dwell time (app usage duration) is represented as the discrete engagement levels illustrated in Section \ref{engagment_level_definition}. More specifically, given the current context $c$ and a user $u$, we need to predict which app $a$ the user $u$ will use next and the engagement level $e$ (light/medium/intensive) for measuring how long the user will stay with this app. We formulate our prediction problem as quaternion, i.e., $\{c,u,a,e\}$. In contrast to a traditional next app usage prediction formulation as $a^* = \operatorname*{argmax}_a \mathcal{F}(a|c,u)$, we formulate the joint learning task for predicting next app and engagement level as follows: \begin{equation} (a,e)^* = \operatorname*{argmax}_{a,e} \mathcal{F}((a,e)|c,u). \end{equation} Note that the $a$ is in the condition for $e$ since the engagement level is defined based on their corresponding app $a$ (\S~\ref{engagment_level_definition}). \subsection{Joint Learning Prediction Model} \label{sec:jointmodels} We propose three methods to solve the prediction problem formulated in \S~\ref{sec:problem_formula}: sequential based model (\S~\ref{sequential}), stacking based model (\S~\ref{sec:stacking}) and boosting based model (\S~\ref{sec:boosting}). \begin{comment} We decompose the joint learning task into subtasks: \textbf{Subtask 1} (NEXT APP PREDICTION) \emph{Given a user $u$ and the current context $c$, we predict the app $a$ will be used.} undoubtedly, the next app usage prediction is a key issue to the joint learning task. If a predicted app is not the one user will use next, the entire task might become meaningless. Subtask 1 aims at modelling app usage. Here we could apply a supervised next app prediction model to measure which app user will use next. \begin{equation} a^* = \operatorname*{argmax}_a P(a|c,u). \end{equation} \textbf{Subtask 2} (ENGAGEMENT LEVEL PREDICTION) \emph{Given a user $u$, the current context $c$, and a candidate app $a$, we predict which engagement level $e$ (light/medium/intensive) user will have within this app.} This subtask characterizes another key issue for our task, which is to model how long a user will stay with an app. We can apply another supervised learning model to infer which engagement level the user will have. \begin{equation} e^* = \operatorname*{argmax}_e P(e|a,c,u). \end{equation} Yet, these two subtasks should not be isolated. Since the choice of the app and the engagement level are provided as a pair, moreover, the result of the second subtask (engagement level prediction) will be influenced by the first subtask (next app prediction). So we propose three different strategies for solving these two subtasks jointly. \end{comment} \subsubsection{\textbf{Sequential based Joint Prediction}} \label{sequential} The most straightforward method for solving this joint learning problem is to perform these two prediction problems (next app and engagement level prediction) sequentially. It is undoubted that the next app usage prediction is a key issue to the joint learning task. If a predicted app is not the one user will use next, the engagement level prediction might become meaningless. Therefore, we first apply a supervised next app prediction model to measure which app user will use next: \begin{equation} a^* = \operatorname*{argmax}_a P(a|c,u). \end{equation} Since the engagement level is dependent on which app the user will use next, therefore, another supervised learning model is applied to infer which engagement level the user will have given the predicted app user will use: \begin{equation} e^* = \operatorname*{argmax}_e P(e|a,c,u). \end{equation} Therefore, the sequential based joint prediction could be formulated as follows: \begin{equation} (a,e)^* = \operatorname*{argmax}_{a,e}P(a|c,u)P(e|a,c,u). \end{equation} As shown in Figure~\ref{fig:sequential_stacking} (in the green circle), in this sequential-based joint prediction strategy, a next app prediction model is needed to find the proper app $a^*$ user will use and then an engagement level prediction model is needed to infer the engagement level $e^*$ based on $a^*$. However, the predicted app $a^*$ is not guaranteed to be the right app; moreover, if the app is not the user will use next, the inferred engagement level based on this app would become meaningless. To this end, we propose two other joint learning methods for predicting these two problems more effectively. \begin{figure} \centering \includegraphics[width =0.85\textwidth]{pictures//Sequential_Stacking_Boosting_App.jpg} \caption{Overview of three joint learning strategies: (1) Sequential based joint prediction; (2) Stacking based joint prediction adds a "meta"-classifier to the final stage after we have the prediction results of next app and engagement level sequentially; (3) Boosting based joint prediction has an "error-correction" of next app prediction in the second step for learning of engagement level prediction.} \label{fig:sequential_stacking} \end{figure} \subsubsection{\textbf{Stacking based Joint Prediction}} \label{sec:stacking} Stacking \cite{syarif2012application} is an ensemble learning technique that combines multiple classification or regression models via a meta-classifier or a meta-regressor. The base-level models are trained based on a complete training set, then the meta-model is trained on the outputs of the base level models as features. So the main idea for our stacking based joint prediction model is to add a "meta"-classifier to the final stage after we got the prediction results on app and engagement level respectively from the sequential based model (\S~\ref{sequential}). Then we may improve the performance by adding this "meta-correction" step at the end of the prediction. In our scenario, the stacking consists of two levels which are base learner as level-0 and stacking model leaner as level-1, as shown in Figure~\ref{fig:sequential_stacking} (in the orange circle). So the base learners (level-0) are composed of the next app usage prediction model (Eq. (2)) and engagement level prediction model (Eq. (3)), which are the same as in sequential based joint prediction shown in Figure~\ref{fig:sequential_stacking}. The outputs of each of the sequential classifiers ($a'$ and $e'$) are collected to create a new dataset. Then the new dataset is used for stacking model learner (level-1) to provide the final output ($a^*$ and $e^*$). In this way, the predicted classifications from the two base classifiers at level-0 can be used as input variables into a meta-classifier as a stacking model learner, which will attempt to learn from the data on how to combine the predictions from the base models to achieve the best classification accuracy. The stacking based joint prediction in our scenario could be formulated as: \begin{align} (a,e)' &= \operatorname*{argmax}_{a,e}P(a|c,u)P(e|a,c,u),\\ (a,e)^*&= \operatorname*{argmax}_{a,e}P((a,e)|(a,e)'). \end{align} \subsubsection{\textbf{Boosting based Joint Prediction Model}} \label{sec:boosting} \begin{figure} \centering \includegraphics[width = \textwidth]{pictures//Boosting.jpg} \caption{Boosting based Joint Prediction} \label{fig:Boosting} \end{figure} Boosting \cite{drucker1994boosting} is another ensemble method for improving the prediction model of any given learning algorithms. The idea of boosting is to train weak learners sequentially, each trying to correct its predecessor. According to this idea, we aim to fit our two learners (next app and engagement level) iteratively such that the training of the model at a given step depends on the models fitted at the previous steps. Then we can improve the predictions from our first learner of app prediction by adding the "error-correction" prediction in the second learner of engagement level prediction. This is shown in Figure~\ref{fig:sequential_stacking} (in the blue circle). We firstly introduce how boosting method works in the supervised learning problem. For a given data set with $n$ samples and $m$ features $D = \{(x, y)\}(|D| = n, x \in R^m)$, the goal is to find an approximation $\hat{\mathcal{F}}(x)$ to a function $\mathcal{F}(x)$ that minimizes the expected value of some specified loss function $L(y, \mathcal{F}(x))$. The boosting method assumes a real-valued $y$ and seeks an approximation in the form of a weighted sum of $K$ additive functions (called base/weak learners) $h_k(x)$: \begin{equation} \hat{\mathcal{F}}(x) = \sum^K_{k = 1}\gamma_kh_k(x). \end{equation} So the model tries to find an approximation $\mathcal{F}(x)$ that minimizes the loss function $L$, and the model is updated as follows. \begin{equation} \gamma_k = \operatorname*{argmin}_{\gamma}\sum^{n}_{i = 1} L(y_i, \mathcal{F}_{k-1}(x_i) + \gamma h_k(x_i)). \end{equation} \begin{algorithm}[t] \SetAlgoLined{ \textbf{Input:} Training data $D=\{x_i = (c_i, u_i), y_i = (a_i, e_i) \}^n_{i=1}$.\\ \textbf{Output:} Boosting based joint classifier $ \mathcal{F}(x) = \mathcal{F}((a,e)|c,u) = \sum^K_{k = 1}\gamma_kh_k(x)$.\\ \emph{\textbf{Step 1:} Initialize the model with next app prediction}\\ Learn $h_1(x_i) = P(a_i|c_i, u_i)$ based on $D$.\\ \emph{\textbf{Step 2:} Improve the predictions from next app prediction by adding "error-correction" prediction in the second learner of engagement level prediction.}\\ 1. Compute so-called pseudo-residuals: $r_i = y_i-h_1(x_i)$.\\ 2. Fit the second learner $h_2(x_i)$ to pseudo-residuals. Train it using the training set $\{(x_i, r_i)\}^n_{i=1}$.\\ 3. Compute multiplier $\gamma$ by solving the following one-dimensional optimization problem: $\gamma = \operatorname*{argmin}\sum^n_{i=1}L(y_i, \mathcal{F}_1(x_i)+\gamma h_2(x_i))$.\\ \emph{\textbf{Step 3:} }Update the model:\\ $\mathcal{F}(x_i)= \mathcal{F}_1(x_i)+\gamma h_2(x_i)$. \caption{Boosting based Joint Training} \label{alg:boosting} } \end{algorithm} To be specific, in our scenario, the dataset $D$ include features $x = (c, u)$ and label $y = (a, e)$. We have two ($K = 2$) base learners in our prediction, where $h_1(x)$ is the next app usage learner and $h_2(x)$ is the engagement level leaner. The steps for applying the boosting method in our scenario are as shown in Figure~\ref{fig:Boosting} in details: \begin{enumerate} \item Fit a model to the data, $h_1(x_i) = P(a_i|c_i,u_i)$ for predicting the next app $a_i$. \item Compute the pseudo-residuals between the current predicted app $a_i'$ and the ground truth of finalized results: app with the corresponding engagement level together ($a_i, e_i$). Since the engagement level is defined based on different app categories, additionally, to avoid the sparsity issue caused by using a specific app in comparison, we calculate the "residual" of app prediction results within the app category level. The app category and engagement level are all represented by one-hot vectors and concatenated together during the "residual" calculation as shown in Figure~\ref{fig:Boosting}. \item Then we fit a model to the residuals, $h_2(x_i) = y_i - h_1(x_i) = r_i$. As the boosting based joint prediction process shown in Figure~\ref{fig:Boosting}, if the first learner output the right predicted app, then the "residual" for the second learner to learn is still only the engagement level ($r_i = e_i$). On the other side, if the first learner output a wrong predicted app, then the residual for the second learner to learn is not only about the engagement level, it also needs to correct the previous results on app prediction. \item Update the new model $\mathcal{F}(x_i) = \mathcal{F}_1(x_i) + \gamma h_2(x_i)$. Since the "residual" is calculated based on app category level, the finalized output of app prediction results is also on the category level. We will introduce how to infer the specific app from the predicted app category based on our next app prediction model in \S~\ref{sec:estimating}. \end{enumerate} The boosting joint prediction algorithm is shown in Alg. \ref{alg:boosting}. Finally, the boosting based joint prediction could be formulated as: \begin{equation} \begin{split} (a, e)^*& = \gamma_1h_1(x) + \gamma_2h_2(x)\\ & = a' + r \\ & = a' + [a_r, e]\\ & = \operatorname*{argmax}_{a} P(a|c,u) + \operatorname*{argmax}_{r} P([a_r, e]|a',c, u), \end{split} \end{equation} where $r$ is the "pseudo-residuals" when comparing the current predicted app with the ground truth (next app and engagement level), and $a_r$ is the difference between the first time predicted app $a'$ and the target app $a$. \subsection{Estimating Components within Joint Prediction Strategies} \label{sec:estimating} After introducing the three strategies for building the joint prediction model, we can find that the next app prediction and engagement level prediction are two main components for all three strategies. Furthermore, some of these components could be reusable across different strategies, e.g., the next app prediction of sequential-based strategy could also be used by stacking and boosting based strategies at the first stage of app prediction as shown in Figure~\ref{fig:sequential_stacking}. In the following sections, we discuss how to construct these two components, i.e., the next app prediction (Eq. (2)) and engagement level prediction (Eq. (3)), adaptively for each strategy with our proposed predictive features. \subsubsection{Next App Usage Prediction} \label{app_prediction} Many previous researchers \cite{zou2013prophet, huang2012predicting, baeza2015predicting} have proposed different methodologies to solve the next app usage prediction problem based on personalized mechanism. Additionally, some researchers \cite{do2014and,zhao2019appusage2vec} indicated that the generic (user-independent) model can improve the predictive performance of personalized models when the data is not sufficient. A generic model is trained using data from all available users. Inspired by the work of \citet{do2014and}, which achieved the best performance by combining the generic model with the personalized model together, we also propose a hybrid next app prediction model with generic and personalized models combined. When building a generic model, the main challenge lies in the fact that the dimensionality of context and output varies depending on all of the users. To learn a generic model and apply it for a given user, generic features and output are needed. In our work, the engagement level is defined based on different app categories. Additionally, the "residual" calculating in boosting based joint prediction strategy (Figure.~\ref{fig:Boosting}) is also based on app category. Therefore, to ensure the generalization of the generic model and to benefit the further prediction of engagement level, the output of the generic model corresponds to the app category. We infer the specific app user will use based on the user's personalized logs given the predicted app category. Specifically, our proposed hybrid next app prediction model could be formulated as the following function: \begin{equation} \begin{split} a^* &= \operatorname*{argmax}_{a}{P(a|c,u)} \\ &= \operatorname*{argmax}_{a}\{P_{g}(a_c|c,u)P_{p}(a|c,u), a \in a_c\}, \end{split} \end{equation} where $P_{g}(a_c|c,u)$ is the probability that user $u$ will use app category $a_c$ based on our generic app category prediction model; and $P_{p}(a|c,u)$ is the probability that user $u$ will use the app $a$ based on their own personalized app prediction model and we will limit the $a$ to the apps belonged to the predicted app category $a_c$. It means we firstly get the app category $a_c$ user will use based on all users' logs and then further rank the apps belonging to this app category based on the personalized logs of user $u$. Through this way, we can have the intermediate output of the app category, which could be used for benefiting the later engagement level prediction. What is more, this generic category-level prediction model could alleviate the cold-start problems with new apps/users resulted from user-specific prediction models, which may be trained on a limited quantity of logs. For the generic app category prediction model, we extracted all the features that have correlation with app usage patterns, which have been validated by previous works \cite{do2014and,zhao2019appusage2vec} and also available in our dataset (\S~\ref{sec:dataset}): User characteristics (age, gender, country, device type, operation system) \cite{zhao2016discovering,kooti2017iphone,li2017mining}, temporal features (hour of day, day of week) \cite{huang2012predicting, shin2012understanding, liao2012mining}, historical preferences \cite{do2014and}, last one/two apps used \cite{zou2013prophet} and periodic features \cite{tan2012prediction,liao2012mining,liao2013mining}. To enrich our predictive features, we further expand users' characteristics by adding their total app usage duration, total app usage frequency, and unique app amount as user characteristic features. To ensure the generalization of the generic model, users' historical preferences are represented based on the total access frequency of each app category. Moreover, we also add users' app preferences on the last day, the last hour and the last session to expand the context features. In summary, we extracted 14 features related to app usage patterns from 4 aspects: user characteristics, temporal features, short-term context features, and long-term context features. All the features used for next app prediction are described in Table \ref{tab:app_general_features}. Then the personalized next app prediction model is generated based on the predictive features proposed in previous works \cite{shin2012understanding,zou2013prophet,baeza2015predicting}: hour of day, day of weekday, most recently used apps (the last one/two apps), and periodic feature. \begin{table}[ht] \centering \scriptsize \caption{\rebuttal{All the features used in our next app prediction model related to users characteristics and context}} \begin{threeparttable} \scalebox{1}{\begin{tabular}[t]{|p{2cm}|lp{7cm}|} \hline \textbf{Feature Type}&\textbf{Feature}&\textbf{Description}\\ \hline \multirow{6}{*}{\textbf{User and Device}}&Age*&Users' age group: 13-17, 18-24, 25-34, 35-54 and 55+\\ &Gender*&Users' gender: male and female\\ &Device Type*&Users' device type: phone and tablet\\ &Total App Usage Duration*&Users' total app usage duration for all apps\\ &Total App Usage Frequency*&Users' total access frequency for all apps\\ &Total Unique App Amount*&The amount of unique apps the user has accessed\\ \hline \multirow{12}{*}{\textbf{Context}}&Temporal Features&\\ \cline{2-3} &Hour of the Day*&Different hours of a day: 0 - 23\\ &Day of the Week*&Different days of a week: Monday to Sunday\\ \cline{2-3} &Short-term Context Features&\\ \cline{2-3} &App Preference in the Last Day&Access frequency of each app category in the last day\\ &App Preference in the Last Hour&Access frequency of each app category in the last hour\\ &App Preference in the Last Session&Access frequency of each app category in the last session\\ &Last Used App*&The last used app in the same session\\ &Last Used Two Apps&The last used two apps in the same session\\ \cline{2-3} &Long-term context Features&\\ \cline{2-3} &Periodic Feature&Time intervals between the current time and the last usage of each app category\\ &Historical App Preference&Total access frequency for each app category\\ \hline \end{tabular}} \begin{tablenotes} \item *: The features marked with * are the common predictive features also used in app engagement level prediction. \end{tablenotes} \end{threeparttable} \label{tab:app_general_features} \end{table}% \subsubsection{App Engagement Level Prediction} \label{sec:app_engagement_prediction} In this subsection, we further explore the app engagement level prediction models that could fit in the different joint prediction strategies. As we mentioned before, we model the novel prediction problem of app engagement level as a multi-class classification problem, where the engagement level is defined based on different app categories. In the sequential based joint prediction strategy (\S~\ref{sequential}) and the level-0 classifiers of the stacking based joint prediction strategy (\S~\ref{sec:stacking}) (Figure~\ref{fig:sequential_stacking}), the engagement level prediction model could be trained for each app category respectively. For example, if we have predicted that the user will use the news app $a^*$ next, we just select the classifier which has been trained specifically based on the logs of using news apps. Then we use this classifier to predict the engagement level. So the engagement level prediction model for sequential-based and stacking-based joint learning strategies could be formulated as: \begin{equation} \begin{split} e^* & = \operatorname*{argmax}_e P(e|a,c,u)\\ & = \operatorname*{argmax}_e \{P_{a_c}(e|c,u), a^* \in a_c\}, \end{split} \end{equation} where $a_c$ is the corresponding app category of the predicted app $a^*$ based on the next app prediction model. It states that we select the engagement level classifier exactly based on the prediction results coming from the next app prediction results. For each app category, we extract the predictive features based on the analysis in section~\ref{infering_features}: demographic features, device features, hour of day, day of week, last used app, last engagement level, last engagement level of the same app category, periodic feature and historical engagement level feature. Besides the common user characteristic features and some of the context features that have been listed in Table~\ref{tab:app_general_features}, we describe the additional features for the app engagement level prediction model in Table~\ref{tab:app_engagement_features}. These features are all established to have impacts on users' app dwell time in \S~\ref{infering_features}, and we will further analyze the feature importance in the following experimental results section \S~\ref{sec:feature_importance}. Different from the engagement level prediction model $P(e|a,c,u)$ in sequential (Eq. (4)) and stacking (Eq. (5)) based strategies, the boosting strategy need to infer the "residual" with $P(r|a,c,u)$ (Eq. (11)) and then sum it to the first app prediction result for getting the finalized app and engagement level together. During this process, the next app user will use would be re-inferred during the engagement level prediction, we cannot select a specific classifier based on the first predicted app. Therefore the engagement level prediction model of the boosting-based strategy can only be constructed as a generic model which could be applied to all apps instead of a specific app category. Specifically, the first predicted app $a'$ from the next app prediction model would be treated as an input feature in the following engagement level prediction, which is represented as a one-hot vector as shown in Figure~\ref{fig:Boosting}. Additionally, to ensure the generalization of the input in the engagement level prediction model within boosting-based joint prediction, all the predictive features will also need to be expanded for representing the behaviour pattern coming from all the different app categories (e.g., the feature of historical engagement level for predicted app category need to be extended to historical engagement level for all different app categories). In this model, no matter which app category is predicted to be used next, the same engagement level prediction model will be applied. Since the finalized app and engagement level would be inferred together within the boosting strategy, the formulation of engagement level prediction could not be decomposed, which has been shown in \S~\ref{sec:boosting}. \begin{table}[ht] \centering \scriptsize \caption{\rebuttal{Additional features used in our app engagement level prediction models related to user characteristics and context}} \begin{threeparttable} \scalebox{1}{\begin{tabular}[t]{|p{1.5cm}|p{5cm}p{6cm}|} \hline \textbf{Feature Type}&\textbf{Feature}&\textbf{Description}\\ \hline \multirow{12}{*}{\textbf{Context}}&Short-term Context Features&\\ \cline{2-3} &Last Engagement Level&The last engagement level of all app categories\\ &Last Engagement Level of Predicted App Category& The last engagement level of the usage on predicted app category\\ \cline{2-3} &Long-term Context Features&\\ \cline{2-3} &Periodic Feature&Time intervals since the last use of all app categories\\ &Periodic Feature of Predicted App Category&Time intervals since the last use of predicted app category\\ &Historical Engagement Levels&Historical sum of engagement levels for all app categories\\ &Historical Engagement Levels of Predicted App Category&Historical count of each engagement level for predicted app categories\\ \hline \end{tabular}} \end{threeparttable} \label{tab:app_engagement_features} \end{table}% \section{Introduction} \begin{figure} \centering \includegraphics[width = 0.7\textwidth]{pictures//TOIS_Next_App_Engagement_Prediction.jpg} \caption{Next app and app dwell time prediction.} \label{overview_image} \end{figure} Mobile devices have become an increasingly ubiquitous part of our everyday life. People access mobile apps to fulfil their information needs or accomplish their daily tasks. Users are generally engaged with an app when they appreciate the mobile app content to which they have given their attention. Properly monitoring user engagement is one of the key ingredients of success to improve user experience and retention. One way user engagement has been measured at a large scale is by tracking how long users spend with content, e.g., the time spent on a webpage. Studies on user engagement in the contexts of desktop-based systems \cite{van2007realism} and websites \cite{diaz2014predicting, yom2013measuring} have shown that simple metrics such as dwell time are meaningful and robust in modelling user engagement. More importantly, these studies have shown that with an awareness of engagement, users' experience with a system can be substantially improved which in turn leads to user growth, user retention, and increasing revenue streams. However, even many past works in mobile computing have investigated how individuals download, install and use different apps on their mobile devices \cite{zhang2012nihao, pan2011composite, shin2012understanding, huang2012predicting}, to our knowledge, few studies have examined how to effectively predict how long users would stay with a mobile app. Real-world mobile app usage behaviour is a complex phenomenon driven by a number of competing factors. Game apps, in general, have a higher probability to be used for a long period, whereas weather app is, not surprisingly, shorter. Intuitively, there are certain times in a day when a user might be more likely to engage with certain mobile apps: John might be more likely to engage with game apps for a longer time at night after work. User characteristics could also make a difference: female users may spend longer time with shopping apps than male users \cite{quinlan2003just}. Despite that the averaged total time spent on different app categories were reported in \cite{bohmer2011falling, xu2011identifying, li2015characterizing}, there is little research that comprehensively analyzes the dwell time of mobile apps. This motivates our first research question \textbf{(RQ1)}: \begin{itemize} \item \textit{What are the factors (user characteristics and contexts) that influence the dwell time a user spends on an app?} \end{itemize} As far as we know, there have been many works conducted for modelling users' behaviour on choosing one particular app under different contexts. However, they do not describe how users engage with that app. Attention is a scarce resource in the modern world. For instance, a user may become immersed in the video watching or quickly abandon it – the distinction of which will be clear if we know how much time the user spent interacting with this app given different contexts. Next app prediction is characterised as the willingness to use an app, whereas engagement is the usage pattern after accessing the app. Though most researchers have focused on measuring which app user will use \cite{liao2013feature, liao2013mining, baeza2015predicting, xu2020predicting}, the engagement of apps is still not well understood. Hence, we consider which app user will use and the engagement level of how long the user will stay with this app an aggregated measure of users' app usage behaviour. Furthermore, app engagement (dwell time) is much dependent on the app content itself. As we mentioned above, checking the weather app is always shorter than playing games. Therefore, it is meaningless to predict how long a user will stay regardless of which app user is engaging. Given the inter-dependency between an app and app dwell time, we aim to predict the next app as well as app engagement (dwell time) as shown in Figure~\ref{overview_image}. Therefore our second research question \textbf{(RQ2)} is: \begin{itemize} \item \textit{Can we simultaneously predict which app user will use next and how long the user will stay on this app?} \end{itemize} Answers to these questions have a profound impact on the success of an app, as engagement awareness can radically improve users' experience with digital services \cite{revels2010understanding}. To answer \textbf{RQ1}, we first demonstrate how different factors affect users' app dwell time by presenting the first population-level analysis of how different contexts affect the app usage duration. The analysis is based on a large-scale mobile app usage dataset with more than 1.3 million logs from over 9K unique apps and 12K users. The data was collected from a mobile advertising company over a period of one week. Specifically, we consider the influential factors from two aspects: user characteristics (e.g., age, gender, device type, historical preferences) and context (e.g., hour, weekday, last used app, periodic pattern). We find that, for example, users between 20 and 40 years old are more likely to have a shorter dwell time than teenagers and older people. Both the demographics and device type have an influence on how long user stay with mobile apps. Furthermore, we also establish that the app dwell time differs significantly across different time in a day. More importantly, we observe that users' app dwell time maintains periodic patterns and follows historical trends. For example, some users spend a similar length of time to regularly check the shopping apps every day (i.e., after every 24 hours). Additionally, users have different historical engagement habits on their app usage duration. For example, some users always prefer staying long on social apps, while others tend to only check for a short while. Based on the comprehensive analysis of users' app dwell time, we are able to conduct the study of how users' app dwell time can be inferred from these features. We then set to answer \textbf{RQ2} -- how to predict the next app and how long the user will stay on this app simultaneously? Based on past work on next app prediction \cite{liao2013feature, liao2013mining, baeza2015predicting}, we propose several joint prediction models (sequential, stacking, and boosting) for such app engagement prediction, whereas the dwell time is represented as discrete levels (light, medium, and intensive) defined based on different app categories. Additionally, different from personalized models in prior work \cite{liao2013feature, liao2013mining, baeza2015predicting}, our models leverage the community-behaviour patterns by extracting predictive features from the entire user population. To summarize, our main contributions are two-folds: \begin{itemize} \item We conduct the first empirical analysis of mobile app engagement based on dwell time with a large-scale data set collected from thousands of users. \item Our research investigates a novel problem on simultaneously predicting which app user will use and how long the user will stay on that app. An effective boosting based prediction model is proposed, which outperforms 56.8\% over the baseline approaches. \end{itemize} To the best of our knowledge, this is the first empirical study on inferring predictive features at the scale of millions of logs for app dwell time, assessing how user characteristics and context features impact the dwell time with a mobile app. Our proposed predictive models are empirically validated to be effective for this novel task. The rest of the paper is organized as follows. We first review the prior literature in Section 2. Section 3 describes the dataset and presents a descriptive analysis of the app usage logs. Section 4 introduces all the features we extracted from our dataset and provides insights on how these features could impact app dwell time prediction. Section 5 presents our methodology for predicting the next app and app dwell time simultaneously, and we propose three joint prediction strategies to solve this problem. We then show the experimental results of our proposed models and analyze the effectiveness of different models in Section 6. We discuss the implications and potential limitations of our work in Section 7 and conclude in Section 8.
{'timestamp': '2021-06-04T02:06:06', 'yymm': '2106', 'arxiv_id': '2106.01490', 'language': 'en', 'url': 'https://arxiv.org/abs/2106.01490'}
arxiv
\section*{Acknowledgments} This material is based on research supported by IARPA BETTER program via Contract No. 2019-19051600007. The views and conclusions contained herein are those of the authors and should not be interpreted as necessarily representing the official policies or endorsements, either expressed or implied, of IARPA or the U.S. Government. \section*{Ethical Considerations} Our corpus is collected from Wikipedia. The content of personal life description, career description, and demographic information is all public to the general audience. Note that our collected corpus might be used for malicious purposes. For example, it can serve as a source by text generation tools to generate text highlighting gender stereotypes. This work is subject to several limitations: First, it is important to understand and analyze the event gender bias for gender minorities, missing from our work because of scarce resources online. Future research can build upon our work, go beyond the binary gender and incorporate more analysis. Second, our study focuses on the Wikipedia pages for celebrities for two additional reasons besides the broad impact of Wikipedia: 1) celebrities' Wikipedia pages are more accessible than non-celebrities. Our collected Wikipedia pages span across 8 occupations to increase the representation of our study; 2) Wikipedia contributors have been extensively updating celebrities' Wikipedia pages every day. Wikipedia develops at a rate of over 1.9 edits every second, performed by editors from all over the world~\cite{wikistats}. The celebrities' pages get more attention and edits, thus better present how the general audience perceives important information and largely reduce the potential biases that could be introduced in personal writings. Please note that although we try to make our study as representative as possible, it cannot represent certain groups or individuals' perceptions. Our model is trained on TB-Dense, a public dataset coming from news articles. These do not contain any explicit detail that leaks information about a user's name, health, negative financial status, racial or ethnic origin, religious or philosophical affiliation or beliefs, trade union membership, alleged or actual crime commission. \bibliographystyle{acl_natbib} \section{Related Work} \violet{It's fine for a short paper to not have a related work section, as long as you covered the citations in the intro. that can probably save you some space.} \paragraph{Faireness in NLP.} NLP researchers have been conducted model-level and corpus-level fairness studies, especially in gender bias. At the model level, ~\citet{Stanovsky2019EvaluatingGB} evaluate the gender bias in machine translation, ~\citet{Zhao2018GenderBI} examine the gender bias in coreference resolution models. At the corpus level, ~\citet{biasemnlp} finds significant gender bias in datasets used for visual recognition tasks. There are also other corpus-level fairness studies in addition to gender bias research. For example, ~\citet{Sap2019TheRO} investigated how annotator's insensitivity to differences in dialect can lead to racial bias in hate speech detection. All the previous works focus on entity analysis. Our work examines the gender bias on events for the first time at the corpus level. \paragraph{Event Extraction.} Researchers have been paying great attention to event extraction tasks. Neural methods~\cite{Han2019JointEA, lin2020oneie} have shown great improvement compared to conventional machine learning models (e.g., ~\cite{chambers-2013-navytime}). Our work is the first to use the event extraction model as a strength to study bias at the event level. \section{Conclusion and Future Work} Gender bias of events in career description will potentially lead to discrimination towards females in various professions. In our work, we collected a large-scale career description corpus across 10 occupations from Wikipedia. Via a set of thorough analyses, we found that it is more likely to mix personal life events with career events for females but not for males. To the best of our knowledge, our work is the first to analyze gender bias at the event level. We will make open-source our code and collected dataset together with partially event annotation publicly to facilitate future research. Besides the corpus level for events, we also find the event detection model performs differently when we only replace the name placeholder with female or male names during the calibration process, which indicates the potential gender bias at the event detection model level. We will leave this to the future work. Our work is also subject to several limitations. First, it is important to understand and analyze career events for gender minorities (LGBTQ+), missing from our work because of scarce resources online. Future research can build upon our work and go beyond the binary gender, incorporating more experiments on analyzing LGBTQ+ populations' career events. Second, we did not train the event detection model because of the annotation unavailability, so the model may be missing some events. We hope that our work can inspire more researchers to study the fairness for events in general, and introduce more resource to the community. \section{Introduction} Researchers have been using NLP tools to analyze corpora for various tasks on online platforms. For example, ~\citet{Pei2020QuantifyingII} found that female-female interactions are more intimate than male-male interactions on Twitter and Reddit. Different from social media, open collaboration communities such as Wikipedia have slowly won the trust of public~\cite{Young2016ItsNW}. Wikipedia has been trusted by many, including professionals in work tasks such as scientific journals~\cite{Kousha2017AreWC} and public officials in powerful positions of authority such as court briefs~\cite{Gerken2010HowCU}. Implicit biases in such knowledge sources could have a significant impact on audiences' perception of different groups, thus propagating and even amplifying societal biases. Therefore, analyzing potential biases in Wikipedia is imperative. \begin{table}[t] \small \centering \begin{tabular}{@{ }p{1cm}@{ } | @{ }p{6.1cm}@{ }} \toprule \textbf{Name}& \ \textbf{Wikipedia Description} \\ \midrule Loretta Young ({\color{lightorange}{F}}) & \ \begin{tabular}[c]{@{}p{6.1cm}@{}} \textbf{{\color{lightorange}Career}}: In 1930, when she was 17, she \colorbox{yellow!50}{eloped} with 26-year-old actor \underline{Grant Withers}; they were \colorbox{yellow!50}{married} in Yuma, Arizona. The \colorbox{yellow!50}{marriage} was \colorbox{yellow!50}{annulled} the next year, just as their second movie together (ironically entitled Too Young to Marry) was \colorbox{yellow!50}{released}. \end{tabular} \\ \midrule Grant Withers ({\color{lightblue}M}) & \ \begin{tabular}[c]{@{}p{6.1cm}@{}} \textbf{{\color{lightblue}Personal Life}}: In 1930, at 26, he \colorbox{yellow!50}{eloped} to Yuma, Arizona with 17-year-old actress Loretta Young. The \colorbox{yellow!50}{marriage} ended in \colorbox{yellow!50}{annulment} in 1931 just as their second movie together, titled Too Young to Marry, was \colorbox{yellow!50}{released}. \end{tabular} \\ \bottomrule \end{tabular} \caption{The marriage events are under the \emph{Career} section for the female on Wikipedia. However, the same marriage is in the \emph{Personal Life} section for the male. \colorbox{yellow!50}{yellow} background highlights events in the passage.} \label{table:wiki} \end{table} In particular, studying events in Wikipedia is important. An event is a specific occurrence under a certain time and location that involves participants~\cite{ACE}; human activities are essentially sequences of events. Therefore, the distribution and perception of events shape the understanding of society. ~\citet{Rashkin2018Event2MindCI} discovered implicit gender biases\violet{can you be more specific? What type of gender bias? } in film scripts using events as a lens. For example, they found that events with female agents are intended to be helpful to other people, while events with male agents are motivated by achievements. However, they focused on the intentions and reactions of events rather than events themselves. In this work, we propose to use events as a lens to study gender biases and demonstrate that events are more efficient for understanding biases in corpora than raw texts. We define \emph{gender bias} as the asymmetric association of events with females and males,\footnote{In our analysis, we limit to binary gender classes, which, while unrepresentative of the real-world diversity, allows us to focus on more depth in analysis.} which may lead to gender stereotypes. For example, females are more associated with domestic activities than males in many cultures~\cite{Leopold2018GenderDI,Jolly2014GenderDI}. To facilitate the study, we collect a corpus that contains demographic information, personal life description, and career description from Wikipedia.\footnote{\tiny\url{https://github.com/PlusLabNLP/ee-wiki-bias}}\violet{please put this under pluslab} We first detect events in the collected corpus using a state-of-the-art event extraction model~\cite{Han2019JointEA}. Then, we extract gender-distinct events with a higher chance to occur for one group than the other. Next, we propose a calibration technique to offset the potential confounding of gender biases in the event extraction model, enabling us to focus on the gender biases at the corpus level. Our contributions are three-fold: \begin{itemize} \item We contribute a corpus of 7,854 fragments from 10,412 celebrities across 8 occupations including their demographic information and Wikipedia \emph{Career} and \emph{Personal Life} sections. \item We propose using events as a lens to study gender biases at the corpus level\violet{add a brief description of what biases we found in the corpus.}, discover a mixture of personal life and professional life for females but not for males, and demonstrate the efficiency of using events in comparison to directly analyzing the raw texts. \item We propose a generic framework to analyze event gender bias, including a calibration technique to offset the potential confounding of gender biases in the event extraction model. \end{itemize} \section{Experimental Setup} \violet{add a transitional paragraph here to explain that you'll introduce the dataset and models you use for your study.} In this section, we will introduce our collected corpus and the event extraction model in our study. \paragraph{Dataset.} \violet{give an general overview of the dataset -- although you've mentioned this in the intro, reiterate it here will make the flow more natural.} Our collected corpus contains demographics information and description sections of celebrities from Wikipedia. Table~\ref{table:statistics} shows the statistics of the number of celebrities with \emph{Career} or \emph{Personal Life} sections in our corpora, together with all celebrities we collected. In this work, we only explored celebrities with \emph{Career} or \emph{Personal Life} sections, but there are more sections (e.g., \emph{Politics} and \emph{Background and Family}) in our collected corpus. We encourage interested researchers to further utilize our collected corpus and conduct studies from other perspectives. In each experiment, we select the same number of female and male celebrities from one occupation for a fair comparison. \begin{table}[t] \small \centering \resizebox{0.48\textwidth}{!}{% \begin{tabular}{@{}lllllll@{}} \toprule \multicolumn{1}{c}{} & \multicolumn{2}{c}{Career} & \multicolumn{2}{c}{Personal Life} & \multicolumn{2}{c}{Collected} \\ \midrule Occ & F & M & F & M & F & M \\ \midrule Acting & 464 & 469 & 464 & 469 & 464 & 469 \\ Writer & 455 & 611 & 319 & 347 & 1,372 & 2,466 \\ Comedian & 380 & 655 & 298 & 510 & 642 & 1,200 \\ Artist & 193 & 30 & 60 & 18 & 701 & 100 \\ Chef & 81 & 141 & 72 & 95 & 176 & 350 \\ Dancer & 334 & 167 & 286 & 127 & 812 & 465 \\ Podcaster & 87 & 183 & 83 & 182 & 149 & 361 \\ Musician & 39 & 136 & 21 & 78 & 136 & 549 \\ \midrule All & \multicolumn{2}{c}{4,425} & \multicolumn{2}{c}{3,429} & \multicolumn{2}{c}{10,412} \\ \bottomrule \end{tabular} } \caption{Statistics showing the number of celebrities with \emph{Career} section or \emph{Personal Life} section, together with all celebrities we collected. Not all celebrities have \emph{Career} or \emph{Personal Life} sections. } \label{table:statistics} \end{table} \paragraph{Event Extraction.} There are two definitions of events: one defines an event as the trigger word (usually a verb)~\cite{timebank}, the other defines an event as a complex structure including a trigger, arguments, time, and location~\cite{broad}.\violet{add citations} The corpus following the former definition usually has much broader coverage, while the latter can provide richer information. For broader coverage, we choose a state-of-the-art event detection model that focuses on detecting event trigger words by~\citet{Han2019JointEA}.\footnote{We use the code at \url{https://github.com/rujunhan/EMNLP-2019} and reproduce the model trained on the TB-Dense dataset.} We use the model trained on the TB-Dense dataset \cite{pustejovsky2003timeml} for two reasons: 1) the model performs better on the TB-Dense dataset; 2) the annotation of the TB-Dense dataset is from the news articles, and it is also where the most content of Wikipedia comes from.\footnote{According to \citet{fetahu2015automated}, more than 20\% of the references are news articles on Wikipedia.} We extract and lemmatize events $e$ from the corpora and count their frequencies $|e|$. Then, we separately construct dictionaries $\mathcal{E}^m = \{e_1^m:|e_1^m|, ..., e_M^m:|e_M^m|\}$ and $\mathcal{E}^f = \{e_1^f:|e_1^f|, ..., e_F^f:|e_F^f|\}$ mapping events to their frequency for male and female respectively. \paragraph{Event Extraction Quality.} To check the model performance on our corpora, we manually annotated events in 10,508 sentences (female: 5,543, male: 4,965) from the Wikipedia corpus. Table~\ref{table:manual} shows that the model performs comparably on our corpora as on the TB-Dense test set. \begin{table}[t] \centering \begin{tabular}{l l l l l l} \toprule \textbf{Metric} & \textbf{TB-D} & \textbf{S} &\textbf{S-F} & \textbf{S-M} & \\ \midrule Precision & 89.2 & 93.5 & 95.3 & 93.4 \\ Recall & 92.6 & 89.8 & 87.1 & 89.8 \\ F1 & 90.9 & 91.6 & 91.0 & 91.6 \\ \bottomrule \end{tabular} \caption{The performance for off-the-shelf event extraction model in both common event extraction dataset TB-Dense (TB-D) and our corpus with manual annotation. \texttt{S} represents the sampled data from the corpus. \texttt{S-F} and \texttt{S-M} represent the sampled data for female career description and male career description separately.} \label{table:manual} \end{table} \begin{table*}[t] \small \centering \begin{tabular}{l | l | l | l | l} \toprule Occupation & Events in Female Career Description & Events in Male Career Description & WEAT${*}$ & WEAT \\ \midrule Writer & \begin{tabular}[c]{@{}l@{}} \marksymbol{diamond*}{magenta}{\color{magenta}\ divorce}, \marksymbol{diamond*}{magenta}{\color{magenta}\ marriage}, involve, organize,\\ \marksymbol{diamond*}{magenta}{\color{magenta}\ wedding} \end{tabular} & \begin{tabular}[c]{@{}l@{}} argue, \marksymbol{oplus}{violet}{\color{violet} \ election}, \marksymbol{triangle*}{emerald}{\color{emerald}\ protest}, rise, \\ shoot\end{tabular} & -0.17 & 1.51\\ \midrule Acting & \begin{tabular}[c]{@{}l@{}} \marksymbol{diamond*}{magenta}{\color{magenta}\ divorce}, \marksymbol{diamond*}{magenta}{\color{magenta}\ wedding}, guest, name, commit \end{tabular} & \begin{tabular}[c]{@{}l@{}} support, \marksymbol{triangle*}{emerald}{\color{emerald}\ arrest}, \marksymbol{triangle*}{emerald}{\color{emerald}\ war}, \marksymbol{square*}{cyan}{\color{cyan} \ sue}, trial\end{tabular} & -0.19 & 0.88 \\ \midrule Comedian & \begin{tabular}[c]{@{}l@{}} \marksymbol{diamond*}{magenta}{\color{magenta}\ birth}, eliminate, \marksymbol{diamond*}{magenta}{\color{magenta}\ wedding}, \marksymbol{heart}{olive}{\color{olive} \ relocate}, \\ partner \end{tabular} & \begin{tabular}[c]{@{}l@{}} enjoy, hear, cause, \marksymbol{*}{orange}{\color{orange} \ buy}, conceive\end{tabular} & -0.19 & 0.54 \\ \midrule Podcaster &\begin{tabular}[c]{@{}l@{}} \marksymbol{heart}{olive}{\color{olive} \ land}, interview, portray, \marksymbol{diamond*}{magenta}{\color{magenta}\ married}, report \end{tabular} & \begin{tabular}[c]{@{}l@{}} direct, ask, provide, continue, bring \end{tabular} & -0.24& 0.53 \\ \midrule Dancer & \begin{tabular}[c]{@{}l@{}} \marksymbol{diamond*}{magenta}{\color{magenta}\ married}, \marksymbol{diamond*}{magenta}{\color{magenta}\ marriage}, \marksymbol{heart}{olive}{\color{olive} \ depart}, \marksymbol{heart}{olive}{\color{olive} \ arrive}, \\ organize \end{tabular} & \begin{tabular}[c]{@{}l@{}} drop, team, choreograph, explore \\ break \end{tabular} & -0.14 & 0.22\\ \midrule Artist &\begin{tabular}[c]{@{}l@{}} paint, exhibit, include, \marksymbol{heart}{olive}{\color{olive} \ return}, teach \end{tabular} & \begin{tabular}[c]{@{}l@{}} start, found, feature, award, begin \end{tabular} & -0.02 & 0.17 \\ \midrule Chef &\begin{tabular}[c]{@{}l@{}} \marksymbol{oplus}{violet}{\color{violet} \ hire}, \marksymbol{triangle}{darkgray}{\color{darkgray} \ meet}, debut, eliminate, sign \end{tabular} & \begin{tabular}[c]{@{}l@{}} include, focus, explore, award, \marksymbol{*}{orange}{\color{orange} \ raise} \end{tabular} & -0.13 & -0.38 \\ \midrule Musician &\begin{tabular}[c]{@{}l@{}} run, record, \marksymbol{diamond*}{magenta}{\color{magenta}\ death}, found, contribute \end{tabular} & \begin{tabular}[c]{@{}l@{}} sign, direct, produce, premier, open \end{tabular} & -0.19 & --0.41 \\ \midrule \multicolumn{4}{c}{ Annotations: \marksymbol{diamond*}{magenta}{\color{magenta}\ Life} \ \marksymbol{heart}{olive}{\color{olive} \ Transportation}\ \marksymbol{oplus}{violet}{\color{violet}\ Personell} \ \marksymbol{triangle*}{emerald}{\color{emerald}\ Conflict} \ \marksymbol{square*}{cyan}{\color{cyan} \ Justice} \ \marksymbol{*}{orange}{\color{orange} \ Transaction} \ \marksymbol{triangle}{darkgray}{\color{darkgray} \ Contact} \ } \\ \bottomrule \end{tabular} \caption[Caption]{Top 5 extracted events that occur more often for females and males in \emph{Career} sections across 8 occupations. We predict event types by applying EventPlus~\cite{ma2021eventplus} on sentences that contain target events and take the majority vote of the predicted types. The event types are from the ACE dataset.\protect\footnotemark\xspace We calculate WEAT scores with all tokens excluding stop words (WEAT$^{*}$ column) and only detected events (WEAT column) for \emph{Career} sections. } \label{tab:result} \end{table*} \begin{figure*}[t] \centering \subfloat[Male Writers] { \includegraphics[width=0.48\columnwidth, height=0.32\columnwidth]{figures/writers_M.pdf} \label{fig:male_writer} } \subfloat[Female Writers] { \includegraphics[width=0.48\columnwidth, height=0.32\columnwidth]{figures/writers_F.pdf} \label{fig:female_writer} } \subfloat[Actor ] { \includegraphics[width=0.48\columnwidth, height=0.32\columnwidth]{figures/actor_male.pdf} \label{fig:actor} } \subfloat[Actress] { \includegraphics[width=0.48\columnwidth, height=0.32\columnwidth]{figures/actor_female.pdf} \label{fig:actress} } \caption{The percentile of extracted events among all detected events, sorted by their frequencies in descending order. The smaller the percentile is, the more frequent the event appears in the text. The extracted events are among the top 10\% for the corresponding gender (e.g., extracted female events among all detected events for female writers) and within top 40\% percent for the opposite gender (e.g., extracted female events among all detected events for male writers). The figure shows that we are not picking rarely-occurred events, and the result is significant. } \label{fig:percent} \end{figure*} \section{Detecting Gender Biases in Events} \label{sec:detect} \paragraph{Odds Ratio.} After applying the event detection model, we get two dictionaries $\mathcal{E}^m$ and $\mathcal{E}^f$ that have events as keys and their corresponding occurrence frequencies as values. Among all events, we focus on those with distinct occurrences in males and females descriptions (e.g., \texttt{work} often occurs at a similar frequency for both females and males in \emph{Career} sections, and we thus neglect it from our analysis). We use the Odds Ratio (OR)~\cite{Szumilas2010ExplainingOR} to find the events with large frequency differences for females and males, which indicates that they might potentially manifest gender biases. For an event $e_n$, we calculate its odds ratio as the odds of having it in the male event list divided by the odds of having it in the female event list: \begin{equation} \frac{\mathcal{E}^m(e_n)}{\sum_{\substack{e_i^m\ne e_n \\ i \in [1, ..., M]}}^{i} \mathcal{E}^m(e_i^m)} / \frac{\mathcal{E}^f(e_n)}{\sum_{\substack{e_j^f\ne e_n\\j \in [1,..., F]}}^{j} \mathcal{E}^f(e_j^f)} \label{equ:or} \end{equation} The larger the OR is, the more likely an event will occur in male than female sections by Equation~\ref{equ:or}. After obtaining a list of events and their corresponding OR, we sort the events by OR in descending order. The top $k$ events are more likely to appear for males and the last $k$ events for females. \paragraph{Calibration.} The difference of event frequencies might come from the model bias, as shown in other tasks (e.g., gender bias in coreference resolution model~\cite{Zhao2018GenderBI}). To offset the potential confounding that could be brought by the event extraction model and estimate the actual event frequency, we propose a calibration strategy by 1) generating data that contains target events; 2) testing the model performance for females and males separately in the generated data, 3) and using the model performance to estimate real event occurrence frequencies. \footnotetext{ACE dataset: \url{https://www.ldc.upenn.edu/collaborations/past-projects/ace}} We aim to calibrate the top 50 most skewed events in females' and males' \emph{Career} and \emph{Personal Life} descriptions after using the OR separately. First, we follow two steps to generate a synthetic dataset: \begin{enumerate} \item For each target event, we select all sentences where the model successfully detected the target event. For each sentence, we manually verify the correctness of the extracted event and discard the incorrect ones. For the rest, we use the verified sentences to create more ground truth; we call them \emph{template sentences}. \item For each template sentence, we find the celebrity's first name and mark it as a \texttt{Name Placeholder}, then we replace it with 50 female names and 50 male names that are sampled from the name list by \citet{checklist}. If the gender changes during the name replacement (e.g., Mike to Emily), we replace the corresponding pronouns (e.g., he to she) and gender attributes~\cite{Zhao2018GenderBI} (e.g., Mr to Miss) in the template sentences. As a result, we get 100 data points for each template sentence with automatic annotations. If there is no first name in the sentence, we replace the pronouns and gender attributes \end{enumerate} \footnotetext{We did not show the result for the \texttt{artists} and \texttt{musicians} due to the small data size.} After getting the synthetic data, we run the event extraction model again. We use the detection recall among the generated instances to calibrate the frequency $|e|$ for each target event and estimate the actual frequency $|e|^{*}$, following: \begin{equation} |e|^{*} = \frac{|e|}{TP(e) / (TP(e) + FP(e))} \label{equ:recall} \end{equation} Then, we replace $|e|$ with $|e|^{*}$ in Equation~\ref{equ:or}, and get $k$ female and $k$ male events by sorting OR as before. Note that we observe the model performances are mostly unbiased, and we have only calibrated events that have different performances for females and males over a threshold (i.e., 0.05).\footnote{ Calibration details and quantitative result in App.~\ref{appendix:cali}.} \paragraph{WEAT score.} We further check if the extracted events are associated with gender attributes (e.g., \texttt{she and her} for females, and \texttt{he and him} for males) in popular neural word embeddings like Glove~\cite{glove}. We quantify this with the Word Embedding Association Test (WEAT) ~\cite{WEAT}, a popular method for measuring biases in text. Intuitively, WEAT takes a list of tokens that represent a concept (in our case, \emph{extracted events}) and verifies whether these tokens have a shorter distance towards female attributes or male attributes. A positive value of WEAT score indicates that female events are closer to female attributes, and male events are closer to male attributes\violet{and/or male events are closer to male attributes?} in the word embedding, while a negative value indicates that female events are closer to male attributes and vice versa.\footnote{Details of WEAT score experiment in App.~\ref{appendix:weat}.} To show the effectiveness of using events as a lens for gender bias analysis, we compute WEAT scores on the raw texts and detected events separately. For the former, we take all tokens excluding stop words.\footnote{We use spaCy (\url{https://spacy.io/}) to tokenize the corpus and remove stop words.} Together with gender attributes from ~\citet{WEAT}, we calculate and show the WEAT scores under two settings as ``WEAT$^{*}$'' for the raw texts and ``WEAT'' for the detected events. \begin{table*}[h!] \resizebox{\textwidth}{!}{ \small \centering \begin{tabular}{l | l | l | l | l} \toprule Occupation & Events in Female Personal Life Description & Events in Male Personal Life Description & WEAT${*}$ & WEAT \\ \midrule Writer & \begin{tabular}[c]{@{}l@{}} bury, \marksymbol{diamond*}{magenta}{\color{magenta}\ birth}, attend, \marksymbol{triangle*}{emerald}{\color{emerald} \ war}, grow \end{tabular} & \begin{tabular}[c]{@{}l@{}} know, report, come, \marksymbol{square*}{cyan}{\color{cyan} \ charge}, publish\end{tabular} & -0.05 & 0.31\\ \midrule Acting & \begin{tabular}[c]{@{}l@{}} \marksymbol{diamond*}{magenta}{\color{magenta}\ pregnant}, practice, wedding, record, convert \end{tabular} & \begin{tabular}[c]{@{}l@{}} accuse, \marksymbol{heart}{olive}{\color{olive} \ trip}, \marksymbol{heart}{olive}{\color{olive} \ fly}, \marksymbol{triangle*}{emerald}{\color{emerald} \ assault}, endorse\end{tabular} & -0.14 & 0.54 \\ \midrule Comedian & \begin{tabular}[c]{@{}l@{}} feel, \marksymbol{diamond*}{magenta}{\color{magenta}\ birth}, fall, open, decide \end{tabular} & \begin{tabular}[c]{@{}l@{}} \marksymbol{heart}{olive}{\color{olive} \ visit}, create, spend, propose, lawsuit\end{tabular} & -0.07 & 0.07 \\ \midrule Podcaster &\begin{tabular}[c]{@{}l@{}} date, describe, tell, life, come \end{tabular} & \begin{tabular}[c]{@{}l@{}} play, write, \marksymbol{diamond*}{magenta}{\color{magenta} \ born}, release, claim \end{tabular} & -0.13 & 0.57 \\ \midrule Dancer & \begin{tabular}[c]{@{}l@{}} \marksymbol{diamond*}{magenta}{\color{magenta}\ marry}, describe, diagnose, expect, speak \end{tabular} & \begin{tabular}[c]{@{}l@{}} hold, involve, \marksymbol{*}{orange}{\color{orange} \ award}, run, serve \end{tabular} & -0.03 & 0.41\\ \midrule Chef & \begin{tabular}[c]{@{}l@{}} \marksymbol{diamond*}{magenta}{\color{magenta} \ death}, serve, announce, describe, \marksymbol{diamond*}{magenta}{\color{magenta}\ born} \end{tabular} & \begin{tabular}[c]{@{}l@{}} \marksymbol{diamond*}{magenta}{\color{magenta}\ birth}, lose, \marksymbol{diamond*}{magenta}{\color{magenta}\ divorce}, speak, \ \marksymbol{triangle}{darkgray}{\color{darkgray} \ meet} \end{tabular} & -0.02 & -0.80 \\ \midrule \multicolumn{4}{c}{ Annotations: \marksymbol{diamond*}{magenta}{\color{magenta}\ Life} \ \marksymbol{heart}{olive}{\color{olive} \ Transportation}\ \marksymbol{oplus}{violet}{\color{violet}\ Personell} \ \marksymbol{triangle*}{emerald}{\color{emerald}\ Conflict} \ \marksymbol{square*}{cyan}{\color{cyan} \ Justice} \ \marksymbol{*}{orange}{\color{orange} \ Transaction} \ \marksymbol{triangle}{darkgray}{\color{darkgray} \ Contact} \ } \\ \bottomrule \end{tabular} } \caption[Caption]{Top 5 events in \emph{Personal Life} section across 6 occupations.\protect\footnotemark\xspace There are more \texttt{Life} events (e.g., ``birth'' and ``marry'') in females' personal life descriptions than males' for most occupations. While for males, although we see more life-related events than in the \emph{Career} section, there are events like ``awards'' even in the \emph{Personal Life} section. The findings further show our work is imperative and addresses the importance of not intermingling the professional career with personal life regardless of gender during the future editing on Wikipedia. } \label{table:pl_result} \end{table*} \section{Results} \paragraph{The Effectiveness of our Analysis Framework.} Table~\ref{tab:result} and Table~\ref{table:pl_result} show the associations of both raw texts and the extracted events in \emph{Career} and \emph{Personal Life} sections for females and males across occupations after the calibration. The values in WEAT$^{*}$ columns in both tables indicate that there was only a weak association of words in raw texts with gender. In contrast, the extracted events are associated with gender for most occupations. It shows the effectiveness of the event extraction model and our analysis method. \paragraph{The Significance of the Analysis Result.} There is a possibility that our analysis, although it picks out distinct events for different genders, identifies the events that are infrequent for all genders and that the frequent events have similar distributions across genders. To verify, we sort all detected events from our corpus by frequencies in descending order. Then, we calculate the percentile of extracted events in the sorted list. The smaller the percentile is, the more frequent the event appears in the text. Figure~\ref{fig:percent} shows that we are not picking the events that rarely occur, which shows the significance of our result.\footnote{See plots for all occupations in Appendix~\ref{appendix:distribution}.} For example, Figure~\ref{fig:male_writer} and Figure~\ref{fig:female_writer} show the percentile of frequencies for selected male and female events among all events frequencies in the descending order for male and female writers, respectively. We can see that for the corresponding gender, event frequencies are among the top 10\%. These events occur less frequently for the opposite gender but still among the top 40\%. \paragraph{Findings and Discussions.} We find that there are more \texttt{Life} events for females than males in both \emph{Career} and \emph{Personal Life} sections. On the other hand, for males, there are events like ``awards'' even in their \emph{Personal Life} section. The mixture of personal life with females' professional career events and career achievements with males' personal life events carries implicit gender bias and reinforces the gender stereotype. It potentially leads to career, marital, and parental status discrimination towards genders and jeopardizes gender equality in society. We recommend: 1) Wikipedia editors to restructure pages to ensure that personal life-related events (e.g., marriage and divorce) are written in the \emph{Personal Life} section, and professional events (e.g., award) are written in \emph{Career} sections regardless of gender; 2) future contributors should also be cautious and not intermingle \emph{Personal Life} and \emph{Career} when creating the Wikipedia pages from the start. \section{Conclusion} We conduct the first event-centric gender bias analysis at the corpus level and compose a corpus by scraping Wikipedia to facilitate the study. Our analysis discovers that the collected corpus has event gender biases. For example, personal life related events (e.g., \texttt{marriage}) are more likely to appear for females than males even in \emph{Career} sections. We hope our work brings awareness of potential gender biases in knowledge sources such as Wikipedia, and urges Wikipedia editors and contributors to be cautious when contributing to the pages. \section{Appendix} \subsection{Quality Check: Event Detection Model} To test the performance of the event extraction model in our collected corpus from Wikipedia. We manually annotated events in 10,508 (female: 5,543, male: 4,965) sampled sentences from the \emph{Career} section in our corpus. Our annotators are two volunteers who are not in the current project but have experience with event detection tasks. We asked annotators to annotate all event trigger words in the text. During annotation, we follow the definition of events from the ACE annotation guideline.\footnote{\url{https://www.ldc.upenn.edu/sites/www.ldc.upenn.edu/files/english-events-guidelines-v5.4.3.pdf}} We use the manual annotation as the ground truth and compare it with the event detection model output to calculate the metrics (i.e., precision, recall, and F1) in Table~\ref{table:manual}. \subsection{Calibration Details} \label{appendix:cali} To offset the potential confounding that could be brought by the event extraction model and estimate the actual event frequency of $|e|^{*}$, we use the recall for the event $e$ to calibrate the event frequency $|e|$ for females and males separately. Figure~\ref{fig:cali} shows the calibration result for the 20 most frequent events in our corpus. Please note that Figure~\ref{fig:cali} $(a)$-$(h)$ show the quantitative result for extracted events in the \emph{Career} sections across 8 occupations, and Figure~\ref{fig:cali} $(i)$-$(n)$ for the \emph{Personal Life} sections. \paragraph{Example Sentence Substitutions for Calibration.} After checking the quality of selected sentences containing the target event trigger, we use 2 steps described in Section~\ref{sec:detect} \emph{Calibration} to compose a synthetic dataset with word substitutions. Here is an example of using \texttt{Name Placeholder}: for target event trigger ``married'' in \texttt{Carole Baskin}'s \emph{Career} section, we have: \begin{myquote}{0.2in} At the age of 17, \underline{Baskin} worked at a Tampa department store. To make money, \underline{she} began breeding show cats; \underline{she} also began rescuing bobcats, and used llamas for a lawn trimming business. In January 1991, \underline{she} married \underline{her} second husband and joined his real estate business. \end{myquote} First, we mark the first name \underline{Baskin} as \texttt{Name Placeholder} and find all gender attributes and pronouns which are consistent with the celebrity's gender. Then, we replace \underline{Baskin} with 50 female names and 50 male names from \citet{checklist}. If the new name is a male name, we change the corresponding gender attributes (none in this case) and pronouns (e.g., she to he, her to his). Another example is for the context containing the target event trigger ``married'' in \texttt{Indrani Rahman}'s \emph{Career} section, where there is no first name: \begin{myquote}{0.2in} In 1952, although married, and with a child, \underline{she} became the first \underline{Miss} India, and went on to compete in the \underline{Miss} Universe 1952 Pageant, held at Long Beach, California. Soon, \underline{she} was travelling along with \underline{her} mother and performing all over the world... \end{myquote} We replace all pronouns (she to he, her to his) and gender attributes (Miss to Mr). \input{appendix/appendix_big_table} \paragraph{Interpret the Quantitative Calibration Result.} We use the calibration technique to calibrate potential gender biases from the model that could have complicated the analysis. In Figure~\ref{fig:cali}, we can see that there is little gender bias at the model level: the model has the same performance for females and males among most events. Besides, we notice that the model fails to detect and has a low recall for few events in the generated synthetic dataset. We speculate that this is because of the brittleness in event extraction models triggered by the word substitution. We will leave more fine-grained analysis at the model level for future work. We focus on events for which the model performs largely differently for females and males during our calibration. Thus, we select and focus on the events that have different performances for females and males over a threshold, which we take 0.05 during our experiment, to calibrate the analysis result. \subsection{Top Ten Extracted Events} \label{appendix:events} Table~\ref{tab:add} and Table~\ref{tab:add_pl} show the top 10 events and serves as the supplement of top 5 events that we reported for \emph{Career} and \emph{Personal Life} sections. \subsection{Details for Calculating WEAT Score} \label{appendix:weat} The WEAT score is in the range of $-2$ to $2$. A high positive score indicates that extracted events for females are more associated with female attributes in the embedding space. A high negative score means that extracted events for females are more associated with male attributes. To calculate the WEAT score, we input two lists of extracted events for females $E_f$, and males $E_m$, together with two lists of gender attributes $A$ and $B$, then calculate: \begin{equation} \small S(E_f,E_m,A,B) = \sum_{e_f\in E_f} s(e_f, A, B) - \sum_{e_m\in E_m} s(e_m, A, B), \end{equation} where \begin{equation} \small s(w, A, B)=\text{mean}_{a\in A} cos(\vec{w}, \vec{a})-\text{mean}_{b\in B}cos(\vec{w}, \vec{b}). \end{equation} Following \citet{WEAT}, we have ``female, woman, girl, sister, she, her, hers, daughter'' as female attribute list $A$ and ``male, man, boy, brother, he, him, his, son'' as male attributes list $B$. To calculate WEAT$^{*}$, we replace the input lists $E_f$ and $E_m$ with all non-stop words tokens in raw texts from either \emph{Career} section or \emph{Personal Life} section. \subsection{Extracted Events Frequency Distribution} \label{appendix:distribution} We sort all detected events from our corpus by their frequencies in descending order according to Equation 1. Figure~\ref{fig:percent_add} $(a)$-$(l)$ show the percentile of extracted events in the sorted list for another 6 occupations besides the 2 occupations reported in Figure~\ref{fig:percent} for \emph{Career} section. The smaller the percentile is, the more frequent the event appears in the text. These figures indicate that we are not picking events that rarely occur and showcase the significance of our analysis result. Figure~\ref{fig:percent_add} $(m)$-$(x)$ are for \emph{Personal Life} sections across 6 occupations, which show the same trend as for \emph{Career} sections. \input{appendix/appendix_figures}
{'timestamp': '2021-06-04T02:10:47', 'yymm': '2106', 'arxiv_id': '2106.01601', 'language': 'en', 'url': 'https://arxiv.org/abs/2106.01601'}
arxiv
\section{Introduction} Alzheimer's disease (AD) is an irreversible, progressive brain disorder that slowly destroys memory and thinking skills and, eventually, the ability to carry out the simplest tasks. Research into the early assessment of Alzheimer's dementia is becoming increasingly more important, as the proportion of people affected by it grows every year~\cite{cahill2020whoplan}. Changes in cognitive ability due to neurodegeneration associated with AD lead to a progressive decline in memory and language quality. Studies have shown that valuable clinical information indicative of cognition can be obtained from spontaneous speech elicited using pictures~\cite{borod1980normative}. Studies have capitalized on this clinical observation, using speech analysis, natural language processing (NLP), and machine learning (ML) to distinguish between speech from healthy and cognitively impaired participants in datasets of semi-structured speech tasks such as picture description \cite{fraser2016linguistic,balagopalan2018effect,zhu2019detecting}. As such, this approach shows a potential to serve as quick, objective, and non-invasive assessments of an individual's cognitive status. The ADReSSo Challenge \cite{luz2021detecting} aims to generate systematic evidence for these promises towards their clinical implementation. ADReSSo (Alzheimer's Dementia Recognition through Spontaneous Speech \textit{only}) Challenge is a shared task for the systematic comparison of approaches to the detection of cognitive impairment and decline based on spontaneous speech. In 2021, it focuses mainly on acoustic characteristics of speech, requiring the creation of models straight from speech, without manual transcription. In this work, we develop ML models to detect AD from speech using picture description data of the demographically-matched ADReSSo challenge speech dataset. Following the previous work on comparing the linguistic approaches to AD detection from speech~\cite{balagopalan2020bert}, we compare the following \textit{acoustic}-based approaches to detect AD: \begin{enumerate} \item \textbf{Extracting conventional acoustic features from speech:} with this approach, we extract acoustic features from the audio files for binary AD vs non-AD classification. The features extracted are informed by previous clinical and ML research in the space of cognitive impairment detection. \item \textbf{Using pre-trained deep neural models:} with this approach, we embed the raw audio into representations using the last hidden state of the pre-trained wav2vec 2.0 model~\cite{baevski2020wav2vec} and classify audio samples using these embeddings as input to the simple classifiers. \item \textbf{A combination of both approaches.} Here, we combine the two approaches and make use of both engineered fesatures and audio representations generated using a pre-trained deep neural model. \end{enumerate} In this paper, we evaluate performance of the three approaches on both the ADReSSo train dataset, and on the unseen test set. We find that models based on conventional acoustic features are best suited for the AD screening tasks, as they are able to achieve very high precision, while under performing on the rest of evaluation metrics, such as accuracy, recall and F1 score. For the cases when a more balanced performance is required, a combination of conventional acoustic features and pre-trained deep neural models is the most promising method, as it allows to achieve high performance and generalize well to unseen data. The main contributions of our paper are as follows: \begin{itemize} \item We use audio representations extracted from the pre-trained deep neural model wav2vec 2.0 for the task of AD classification from speech. To the best of our knowledge, this method and this model were never applied before for such a task. \item We present the model that combines conventional acoustic features with pre-trained representations of speech and outperforms the ADReSSo baseline model by 2.82\%. \item We carefully compare three different acoustic-based approaches for AD detection, which allows us to draw more general conclusions on performance and generalizability of acoustic models. \end{itemize} \section{Background} \subsection{Extracting conventional acoustic features from speech} Some of the conventional features employed to describe acoustic characteristics of the voice applied to AD detection, include fundamental frequency, jitter and shimmer~\cite{pulido2020alzheimer}. In addition to these features, there is also a range of elements properly accompanying linguistic emissions and which constitute signs and clues but are not verbal. These characteristics of speech are called paralinguistic features and have been used to obtain information from the patient by means of the statistics of e.g. Cepstral Mel-Frequency Components (MFCC), among others~\cite{alonso2015new}. Different combinations of these features were used in multiple previous studies when detecting AD from the speech collected via picture description tasks~\cite{balagopalan2018effect,zhu2019detecting,zhu2018semi,balagopalan2020impact}. These works have provided clear evidence on the potential of using simple spoken tasks and conventional acoustic features to automatically assess early dementia and its progression as well as to demonstrate that technology allows automatic detection of AD. \subsection{Using pre-trained deep neural methods} In the recent years, pre-training of deep neural networks has emerged as an effective approach to overcome the problem of data scarcity~\cite{young2018recent}. The key idea of such a technique, which is also called ``transfer learning", is to learn general representations in a setup where substantial amounts of labeled or unlabeled data is available and to leverage the learned robust representations to improve performance on a downstream task for which the amount of data is limited. In natural language processing, one of the most popular transfer learning models is BERT~\cite{devlin2019bert}, which trains ``contextual embeddings" wherein a representation of a sentence (or transcript) is influenced by the context in which the words occur in sentences. In the field of speech processing, transfer learning models are mainly used for the purpose of automatic speech recognition~\cite{baevski2020wav2vec}. We focus on using pre-trained embeddings from a self-supervised audio representation model, wav2vec 2.0 ~\cite{baevski2020wav2vec}, for the task of AD detection from speech. In the wav2vec 2.0 model, audio is encoded via a multi-layer convolutional neural network and then masks spans of the resulting latent speech representations similar to masked language modeling~\cite{devlin2019bert}. The latent representations are fed to a Transformer network~\cite{vaswani2017attention} to build contextualized representations. For the task of AD detection, transfer learning approach is particularly useful, as it is difficult and costly to collect labelled data. While several prior works have used pre-trained acoustic embeddings such as x-vectors and i-vectors for AD detection from speech~\cite{pompiliinesc,hauptman2019identifying}, to the best of our knowledge, no works have utilized self-supervised representations of speech for AD detection. Hence, we aim to benchmark a self-supervised methodology, with a masked modelling setup similar to BERT, for AD detection. \subsection{A combination of pre-trained and conventional approaches} Incorporating domain-specific external knowledge in neural language representations is a field of research that has been actively explored with both acoustic and linguistic embeddings~\cite{balagopalan2020augmenting,cai2019multi}. However, a large amount of prior work is either focused on linguistic based approaches or using simple acoustic embeddings such as x-vectors~\cite{baevski2020wav2vec}. In contrast, we are using a combination of state-of-the art self-supervised techniques for speech representations and combining these with domain-knowledge informed conventional speech features. \section{Methodology} \subsection{Dataset} The ADReSSo dataset we use in this work primarily consists of set of speech recordings of picture descriptions produced by cognitively normal (or healthy) subjects and patients with an AD diagnosis, who were asked to describe the Cookie Theft picture from the Boston Diagnostic Aphasia Examination. There are speech samples from 237 participants in total, out of which 166 are in the training set, and 71 in the test set ($70/30$ split balanced for demographics). Out of the samples in the training set, 83 were cognitively healthy, while 83 had AD. The dataset used for AD prediction was matched for age and gender so as to minimise risk of bias in the prediction tasks using a propensity score. All standardised mean differences for the age and gender covariates were $<0.001$. \subsection{Feature Extraction} \subsubsection{Using conventional acoustic features from speech} \label{sec:features-eng} We extract 168 acoustic features from the unsegmented speech audio files. Those include mel-frequency cepstral coefficients (MFCCs), jitter, shimmer and statistics related to zero-crossing rate. We only use samples from the audio component provided with the dataset, and do not perform any Automatic Speech Recognition or linguistic analyses. \subsubsection{Using embeddings from pre-trained deep neural models for audio representation} \label{sec:features-embed} In order to create audio representations using this approach, we make use of the huggingface\footnote{https://huggingface.co/models} implementation of the wav2vec~2.0~\cite{baevski2020wav2vec} base model \textit{wav2vec2-base-960h}. This base model is pretrained and fine-tuned on 960 hours of Librispeech on 16kHz sampled speech audio. We first represent each unsegmented audio file as a waveform with librosa\footnote{https://librosa.org/}. We then tokenize waveforms using \textit{Wav2Vec2Tokenizer} and if necessary, divide them into smaller chunks (with the maximum size of 320000 in our case) to fit into memory, afterwards we feed them into the wav2vec~2.0 model. The last hidden state of the model is used as an embedded representation of audio. When tokenized waveforms are divided into several chunks, the mean value of all chunks for each tensor's element is computed to generate the final embedding. \subsubsection{A combination of both approaches} \label{sec:features-combo} In this approach, we study if engineered feature and pre-trained embeddings can augment each other by concatenating the representations at audio sample level. We combine representations from pre-trained models and conventional acoustic features by simply concatenating them. Hence, the dimension of the overall representation is the sum of the individual dimensions (936-dimensional representation vector overall). \begin{table*}[ht!] \caption{10-fold CV abd LOSO-CV results averaged across all the folds on the ADReSSo train set. Bold indicates the best performing approach for each model, bold+italics indicate the best overall performance for the metric.} \label{tab:train-results} \begin{adjustbox}{max width=0.9\textwidth, center} \begin{tabular}{lrrrrrrrr} & \multicolumn{2}{c}{\textbf{Accuracy}} & \multicolumn{2}{c}{\textbf{Precision}} & \multicolumn{2}{c}{\textbf{Recall}} & \multicolumn{2}{c}{\textbf{F1}} \\ \textbf{Model} & \multicolumn{1}{c}{\textbf{10-fold CV}} & \multicolumn{1}{c}{\textbf{LOSO CV}} & \multicolumn{1}{c}{\textbf{10-fold CV}} & \multicolumn{1}{c}{\textbf{LOSO CV}} & \multicolumn{1}{c}{\textbf{10-fold CV}} & \multicolumn{1}{c}{\textbf{LOSO CV}} & \multicolumn{1}{c}{\textbf{10-fold CV}} & \multicolumn{1}{c}{\textbf{LOSO CV}} \\ \hline \hline LR-feat & 0.6084 & 0.6386 & 0.6774 & \textbf{0.7213} & 0.4828 & 0.5057 & 0.5638 & 0.5946 \\ LR-embed & \textbf{0.6867} & \textbf{0.6747} & 0.6882 & 0.6737 & \textit{\textbf{0.7356}} & \textit{\textbf{0.7356}} & \textit{\textbf{0.7111}} & \textbf{0.7033} \\ LR-combo & 0.6807 & 0.6687 & \textbf{0.7024} & 0.6951 & 0.6782 & 0.6552 & 0.6901 & 0.6746 \\ \hline SVM-feat & 0.6265 & 0.6566 & \textit{\textbf{0.8571}} & \textit{\textbf{0.9167}} & 0.3448 & 0.3793 & 0.4918 & 0.5366 \\ SVM-embed & 0.6687 & 0.6566 & 0.6818 & 0.6705 & \textbf{0.6897} & \textbf{0.6782} & 0.6857 & \textbf{0.6743} \\ SVM-combo & \textit{\textbf{0.6928}} & \textbf{0.6807} & 0.7308 & 0.7297 & 0.6552 & 0.6207 & \textbf{0.6909} & 0.6708 \\ \hline NN-feat & 0.6084 & 0.6265 & 0.6833 & 0.6923 & 0.4713 & 0.5172 & 0.5578 & 0.5921 \\ NN-embed & \textbf{0.6747} & 0.6566 & \textbf{0.6774} & 0.6705 & \textbf{0.7241} & 0.6782 & \textbf{0.7000} & 0.6743 \\ NN-combo & 0.6506 & \textit{\textbf{0.6928}} & 0.6706 & \textbf{0.7000} & 0.6552 & \textbf{0.7241} & 0.6628 & \textit{\textbf{0.7119}} \\ \hline DT-feat & 0.5964 & 0.5843 & 0.6190 & 0.6071 & 0.5977 & 0.5862 & 0.6082 & 0.5965 \\ DT-embed & 0.6446 & 0.6807 & 0.6591 & 0.6809 & 0.6667 & \textit{\textbf{0.7356}} & 0.6629 & 0.7072 \\ DT-combo & \textbf{0.6506} & \textbf{0.6867} & \textbf{0.6593} & \textbf{0.6882} & \textbf{0.6897} & \textit{\textbf{0.7356}} & \textbf{0.6742} & \textbf{0.7111} \end{tabular} \end{adjustbox} \end{table*} \begin{table}[ht] \caption{AD detection results on unseen, held-out ADReSS test set. Bold indicates the best result.} \label{tab:test-results} \begin{adjustbox}{max width=0.9\linewidth, center} \begin{tabular}{lrrrr} \textbf{Model} & \multicolumn{1}{c}{\textbf{Accuracy}} & \multicolumn{1}{c}{\textbf{Precision}} & \multicolumn{1}{c}{\textbf{Recall}} & \multicolumn{1}{c}{\textbf{F1}} \\ \hline \hline Acoustic baseline & 0.6479 & \multicolumn{1}{l}{} & \multicolumn{1}{l}{} & \multicolumn{1}{l}{} \\ \hline SVM-feat & 0.6479 & \textbf{0.9167} & 0.3143 & 0.4681 \\ LR-embed & 0.6056 & 0.6000 & 0.6000 & 0.6000 \\ DT-embed & 0.5775 & 0.5714 & 0.5714 & 0.5714 \\ SVM-combo & \textbf{0.6761} & 0.6364 & \textbf{0.8000} & \textbf{0.7089} \\ LR-combo & 0.6056 & 0.6000 & 0.6000 & 0.6000 \end{tabular} \end{adjustbox} \end{table} \subsection{Evaluation Methods} \textbf{Cross-validation on ADReSSo train set:} We use two cross-validation strategies in our work – leave-one-subject-out CV (LOSO CV) and 10-fold CV. We report evaluation metrics with both these strategies for all models for direct comparison between approaches and with challenge baseline. \textbf{Predictions on ADReSSo test set:} We generate predictions from the top-5 performing classifiers -- where these are selected on the basis of highest LOSO-CV accuracy on the training set -- trained on the complete train set. We report performance on the challenge test set, as obtained from the challenge organizers. We evaluate task performance primarily using accuracy scores, since all train/test sets are known to be balanced. We also report precision, recall, specificity and F1 with respect to the positive class (AD). \subsection{Experiments} \subsubsection{Using conventional acoustic features from speech} We classify acoustic features (see Section~\ref{sec:features-eng}) extracted at transcript-level with several conventional linear and non-linear ML models : Logistic regression (LR-feat), Support Vector Machines (SVM-feat), Neural Network (NN-feat), and Decision Tree (DT-feat). We perform feature selection by choosing top-10 number of features, based on ANOVA F-value between label/features. All model hyper-parameters were set to their default values as on the scikit-learn implementation for each of these ~\cite{pedregosa2011scikit}: logistic regression is trained with L2-penalty, SVM-feat is trained with a radial basis function kernel with kernel coefficient $0.001$, and regularization parameter set to $1$, NN-feat used consists of 1 layers of 100 unit, and DT-feat with minimum samples per split set to $2$. \subsubsection{Using embeddings from pre-trained deep neural models for audio representation} In order to leverage information encoded by pre-trained audio representation models, we extract embeddings from a pre-trained audio model, wav2vec 2.0, as a representation for each audio sample (see Section~\ref{sec:features-embed}). We then classify these by training Logistic regression (LR-embed), Support Vector Machines (SVM-embed), Neural Network (NN-embed), and Decision Tree (DT-embed) with default hyper-parameters \subsubsection{Combining conventional features and embeddings from pre-trained deep neural models} Hence, a single representation with length equal to the sum of features and the embedding-dimension is obtained (see Section~\ref{sec:features-combo}). We then classify these by training the following models on these concatenated representations : Logistic regression (LR-combo), Support Vector Machines (SVM-combo), Neural Network (NN-combo), and Decision Tree (DT-combo). All model hyper-parameters were set to their default values as on the scikit-learn implementation for each of these (i.e., same as in previous sections). \section{Results} \subsection{AD detection results on the ADReSSo train set} The results of both LOSO and 10-fold CV evaluation of classification models' performance show that the conventional features-based approach consistently under performs in terms of accuracy, recall and F1 score (see Table~\ref{tab:train-results}). The feature-based approach, however, outperforms all the other approaches in terms of precision with the SVM model. With the neural net and decision tree models, feature-based approach reaches high precision levels, although is not the best performing neural net models (see Table~\ref{tab:train-results}). Embedding-based and combo approaches compete for best performance in terms of accuracy, recall and F1 score. With logistic regression, embedding-based approach outperforms all the other approaches both in terms of accuracy, recall and F1. With the neural net model, the type of cross-validation determines whether it is the embedding-based or the combo approach that performs the best. With decision trees, however, the combination of conventional features and embeddings of speech perform the best in all the cases, even in terms of precision. \subsection{AD detection results on the unseen ADReSSo test set} \begin{table*}[ht!] \caption{Difference between test performance and performance of performance of the model evaluated using 10-fold CV (i.e. \textit{w/ 10-fold}) and LOSO CV (i.e. \textit{w/ LOSO}). Positive results indicate that test performance was higher. Bold indicates the model that outperforms the acoustic baseline.} \label{tab:diff-test} \begin{adjustbox}{max width=0.9\textwidth, center} \begin{tabular}{lcccccccc} & \multicolumn{2}{c}{\textbf{Accuracy}} & \multicolumn{2}{c}{\textbf{Precision}} & \multicolumn{2}{c}{\textbf{Recall}} & \multicolumn{2}{c}{\textbf{F1}} \\ \textbf{Model} & \textbf{w/ 10-fold} & \textbf{w/ LOSO} & \textbf{w/ 10-fold} & \textbf{w/ LOSO} & \textbf{w/ 10-fold} & \textbf{w/ LOSO} & \textbf{w/ 10-fold} & \textbf{w/ LOSO} \\ \hline \hline SVM-feat & \multicolumn{1}{l}{2.14\%} & -0.87\% & \multicolumn{1}{l}{5.96\%} & 0.00\% & -3.05\% & -6.50\% & -2.37\% & -6.85\% \\ LR-embed & -8.11\% & -6.91\% & -8.82\% & -7.37\% & -13.56\% & -13.56\% & -11.11\% & -10.33\% \\ DT-embed & -6.71\% & -10.32\% & -8.77\% & -10.95\% & -9.53\% & -16.42\% & -9.15\% & -13.58\% \\ \textbf{SVM-combo} & -1.67\% & -0.46\% & -9.44\% & -9.33\% & \multicolumn{1}{l}{14.48\%} & \multicolumn{1}{l}{17.93\%} & \multicolumn{1}{l}{1.80\%} & \multicolumn{1}{l}{3.81\%} \\ LR-combo & -7.51\% & -6.31\% & -10.24\% & -9.51\% & -7.82\% & -5.52\% & -9.01\% & -7.46\% \end{tabular} \end{adjustbox} \end{table*} \begin{table}[t] \caption{Difference between LOSO and 10-fold CV classification performance. Positive results indicate that LOSO CV performance was higher than that of 10-fold CV.} \label{tab:diff-loso-10fold} \begin{adjustbox}{max width=0.9\linewidth, center} \begin{tabular}{lllll} \textbf{Model} & \multicolumn{1}{c}{\textbf{Accuracy}} & \multicolumn{1}{c}{\textbf{Precision}} & \multicolumn{1}{c}{\textbf{Recall}} & \multicolumn{1}{c}{\textbf{F1}} \\ \hline \hline LR-feat & 3.02\% & 4.39\% & 2.29\% & 3.08\% \\ SVM-feat & 3.01\% & 5.96\% & 3.45\% & 4.48\% \\ NN-feat & 1.81\% & 0.90\% & 4.59\% & 3.43\% \\ DT-feat & \multicolumn{1}{r}{-1.21\%} & \multicolumn{1}{r}{-1.19\%} & \multicolumn{1}{r}{-1.15\%} & \multicolumn{1}{r}{-1.17\%} \\ \hline LR-embed & \multicolumn{1}{r}{-1.20\%} & \multicolumn{1}{r}{-1.45\%} & \multicolumn{1}{r}{0.00\%} & \multicolumn{1}{r}{-0.78\%} \\ SVM-embed & \multicolumn{1}{r}{-1.21\%} & \multicolumn{1}{r}{-1.13\%} & \multicolumn{1}{r}{-1.15\%} & \multicolumn{1}{r}{-1.14\%} \\ NN-embed & \multicolumn{1}{r}{-1.81\%} & \multicolumn{1}{r}{-0.69\%} & \multicolumn{1}{r}{-4.59\%} & \multicolumn{1}{r}{-2.57\%} \\ DT-embed & 3.61\% & 2.18\% & 6.89\% & 4.43\% \\ \hline LR-combo & \multicolumn{1}{r}{-1.20\%} & \multicolumn{1}{r}{-0.73\%} & \multicolumn{1}{r}{-2.30\%} & \multicolumn{1}{r}{-1.55\%} \\ SVM-combo & \multicolumn{1}{r}{-1.21\%} & \multicolumn{1}{r}{-0.11\%} & \multicolumn{1}{r}{-3.45\%} & \multicolumn{1}{r}{-2.01\%} \\ NN-combo & 4.22\% & 2.94\% & 6.89\% & 4.91\% \\ DT-combo & 3.61\% & 2.89\% & 4.59\% & 3.69\% \end{tabular} \end{adjustbox} \end{table} Five models were selected based on their performance on the train set to submit to the ADReSSo challenge - SVM-feat to represent the feature-based approach, LR-embed and DT-embed to represent the embedding-based approach, and the LR-combo and SVM-combo to represent the combined approach. Out of these five models, SVM-feat reached the best performance in terms of precision (see Table~\ref{tab:test-results}). The SVM-combo model achieved the best performance in terms of accuracy, recall and F1, and was able to beat the baseline acoustic model by 2.82\%. \section{Discussion} \subsection{Classification performance} The models employing the feature-based approach are performing the best on the train data in terms of precision, when evaluated using LOSO CV. Both the highest achieved precision level (91.67\% with SVM-feat) and the second-best result (72.13\% with LR-feat) are achieved by the models that make use of conventional acoustic features. The test results reinforce the precision capability of the feature-based model, with the SVM-feat model achieving more than 28\% higher precision on the unseen test set than any other model. However, feature-based models perform very poorly in terms of recall. As such, feature-based models could be a good candidate in a real-life deployment of AD screening models, when high precision is much more important than recall or overall accuracy. There is no clear difference in train performance between the embedding-based and combo approaches. Combo models tend to perform better when evaluated using LOSO CV method, while embedding-based models often outperform combo models when evaluated using 10-fold CV. The test results show that the SVM-combo model has the best result, but the more detailed analysis of generalizability of the three approaches is necessary. \subsection{Generalizability} In order to assess generalizability of the models, we first calculate the difference in performance of the five submitted models on the test and the train sets (see Table~\ref{tab:diff-test}). Feature-based model (SVM-feat) has no gap between test and train performance in terms of precision, and even surpasses the 10-fold CV precision on the test set. This model also achieves the highest precision levels both on the train and test sets, which allows us to conclude that feature-based approach is potentially the best candidate for the models when precision is the most important metric. This is not surprising, as conventional acoustic features were engineered based on substantial domain knowledge in the area of AD detection. Multiple previous studies~\cite{balagopalan2018effect,zhu2019detecting,zhu2018semi,balagopalan2020impact} were using these features as the ones that characterize the speech of patients with AD the best. Both embedding-based models (LR-embed and DT-embed) a substantial gap between the test performance and the cross-validated performance on the train set (6.7-13.6\% difference, with the test performance always being lower). The combination approaches on average, however, result in a smaller gap, especially in terms of accuracy, recall and F1 score. The SVM-combo model even performs better on the test set, when evaluated using recall and F1 metrics. In terms of accuracy, the SVM-combo model shows only 0.46\% lower performance on the test set than on the train set, when cross-validated using the LOSO method. Such a slight difference confirms that the combination approach in general is a more generalizable method to train the AD detection system, comparing to using the embedding-based representations of speech alone (i.e. embedding-based models). We also aim to understand whether 10-fold or LOSO CV is the best approach to evaluate the model in order to achieve the result that is close to the expected test performance. For this, we additionally compare performance of each model between LOSO and 10-fold CV (see Table~\ref{tab:diff-loso-10fold}). With the feature-based approach, LOSO CV results are usually higher than those of 10-fold CV. As these models are most suitable for precision-focused cases (as we discussed above) and given test precision does not differ much from the LOSO CV results, the best solution would be to use LOSO CV evaluation when training these models on the data similar in size to the ADReSSo dataset. With embedding-based and combo models, 10-fold CV mostly tends to outperform LOSO CV. However, test performance is in most cases closer to the LOSO CV performance. So with these approaches, similarly as with the feature-based approach, relying on the LOSO CV would be a more reliable strategy, when data is similar to the ADReSSo dataset. \section{Conclusions and Future Work} In this paper we study the performance of conventional acoustic feature-based and pre-trained embedding-based classification approaches on Alzheimer's Disease detection from speech on the ADReSSo challenge dataset. We observe that feature-based approaches have a higher precision in general, and hence might be well-suited for screening AD via speech analysis. However, a more balanced performance across multiple-metrics is achieved by embedding-based approaches both while cross-validating on the train set and when tested on the unseen test set. Finally, we observe that a representation combining embeddings and conventional features outperforms both individual approaches, and attains an accuracy 2.8\% higher that the best acoustic baseline in the challenge. With our careful comparisons, we hope to contribute to principled evaluations of the performance and generalizability different classification strategies on the important task of Alzheimer's Disease detection from speech. In future work, we will focus on different strategies to combine and fine-tune embeddings and feature-based models. \bibliographystyle{IEEEtran}
{'timestamp': '2021-06-04T02:08:54', 'yymm': '2106', 'arxiv_id': '2106.01555', 'language': 'en', 'url': 'https://arxiv.org/abs/2106.01555'}
arxiv
\section{Introduction} Sparse regression (SR) codes were introduced and studied by Barron and Joseph \cite{Joseph2012} and were shown to achieve the capacity of the additive white Gaussian noise (AWGN) channel when the code length and the rate of non-zero symbols go to infinity \cite{Rush2017,Barbier2015, Barbier2017}. Furthermore, the code rate can be easily changed by adjusting the matrix size directly rather than rebuilding the parity check matrix carefully as in low density parity check (LDPC) codes \cite{Gallager1962} because there is no sparse/tree-like requirement on the measurement matrix. The low-complexity fast Fourier transform (FFT) algorithm can be used to reduce the complexity and efficient approximate message passing (AMP) type algorithms can be used for decoding to guarantee a Bayes-optimal solution, i.e., the minimum mean square error (MMSE) solution \cite{Rush2017,Barbier2015,Barbier2017}. However, SR codes have a weakness at finite code length. When the code length and the compression rate are finite, the performance of SR codes is far from the capacity, and much worse than the widely used LDPC codes. To improve the performance and competitiveness of SR codes, several techniques have been introduced. Spatial-coupling, originally introduced for LDPC codes, was used in SR codes \cite{Barbier2017} to obtain a Bayes-optimal decoding performance for any compression rate. Recently, it was found that regular clipping, a technique that is generally used to reduce the peak-to-average-power ratio (PAPR), can also improve the section error rate (SER) performance of SR codes significantly \cite{Liang_cl2017}. When a signal is clipped, we compensate by scaling the clipped signal to maintain a fixed transmit power; the intuition of clipped SR codes is that this scaling is more beneficial than the penalty of distortion due to clipping. Therefore, there exists a tradeoff between the clipping distortion and noise distortion. An optimal clipping threshold can bring a significant gain in SER performance for SR codes at finite code length, sometimes achieving 4 dB in SNR at code length $10^4$. However the performance is still not very close to the capacity (about 2 dB at code length $10^4$). This paper considers irregular clipping of SR codes. In addition, a permuted discrete cosine transform (DCT) matrix is used for the SR code measurement matrix, rather than an i.i.d. Gaussian matrix as in previous work. Thus, low-complexity fast DCT and inverse DCT (IDCT) algorithms can be applied to reduce the encoding and decoding complexity of SR codes. Orthogonal AMP (OAMP) algorithm \cite{Ma2016} (see also closely-related earlier works in \cite{MaSPL2015a, Ma_SPL2015b}) is exploited for the decoding of the clipped SR codes. It was shown in \cite{Rangan2016, Takeuchi2017} that state evolution (SE) can asymptotically characterize the performance of OAMP algorithm, similar to extrinsic information transfer (EXIT) chart in iterative decoding \cite{Brink2001, Brink2004}. In this paper, the main contributions are summarized as follows. \begin{itemize} \item To further improve the SER performance of regularly clipped SR codes, we propose an irregularly clipped SR code. In irregularly clipped SR codes, a new irregular clipping method applies different clipping thresholds to different symbols, which provides a larger optimization space and thus results in better SER performance. \item Based on the SE analysis for the OAMP decoding, the distribution of irregular clipping thresholds is optimized to minimize the SER of irregularly clipped SR codes, which is a concave optimization and thus can be solved by standard convex optimization tools. \item We provide numerical results to demonstrate the efficiency of irregularly clipped SR codes. Specifically, comparing with the existing regularly clipped SR codes, the proposed irregularly clipped SR codes achieve about 0.4 dB gain in signal-to-noise-ratio (SNR) at code length $\approx\! 2.5\!\times\! 10^4$ and SER $\approx10^{-5}$. Furthermore, the irregularly clipped SR codes are robust in a wide range of code rates, e.g., from 0.2 (low rate) to 1 (high rate). \end{itemize} The findings in this paper provide a promising direction to significantly enhance the performance of SR codes. \section{ {Preliminaries}} {In this section, we briefly introduce SR codes, regularly clipped SR codes and OAMP decoding.} {Consider an AWGN channel: \begin{equation}\label{equ.recovery_model} \bm{y}=\bm{c}+\bm{n} \vspace{1.5mm}, \end{equation} where $\bf{c}\in \mathbb{R}^{M}$ is an encoded vector and $\bf{n}\sim \mathcal{N}(\bf{0},\sigma_n^2\bf{I}_{M})$ is a Gaussian noise vector. We define ${\rm SNR}=\sigma_n^{-2}$. The goal is to recover $\bm{c}$ via the received signal vector $\bm{y}$.} \subsection{ {Sparse Regression (SR) Codes}} {An SR code is generated by \cite{Rush2017,Barbier2017}: \begin{equation}\label{equ.linear_system} \bm{c} = \bm{Ax}, \end{equation} where ${\bm A}\!\in\! \mathbb{R}^{M\!\times\! N}$ is a measurement matrix with compression rate $\delta\!=\!M/N\!\leq \!1$, and ${\bm x}$ is an information-carrying sparse vector that contains $L$ sections. Each section is of length $B$ and has a single non-zero entry with amplitude $\sqrt{B}$. An example of ${\bm x}$ is as follows: \begin{equation}\label{Eqn:block_sparse} \!\!\!\!\Phi\!: \bf{x}^{\mathrm{T}}\!\!=\![\overbrace{0,\dots,0,\!\sqrt{\!B}}^{\mathrm{section}\; 1}|\overbrace{\dots,0,\!\sqrt{\!B},0}^{\mathrm{section}\;2}|\dots,|\overbrace{\!\sqrt{\!B},0,\dots,0}^{\mathrm{section}\;L}]. \end{equation} The positions of the non-zero symbols in $\bf{x}$ carry the information. In this code, the code length is $M$ and the amount of information is $L{\rm log}B$. Thus, the code rate is given by $R={L{\rm log}B}/{M}$.} {For theoretical analysis in \cite{Rush2017,Barbier2017}, ${\bm A}\in \mathbb{R}^{M\times N}$ in \eqref{equ.linear_system} is assumed to have independent identically distributed Gaussian (IIDG) entries over $\mathcal{N}(0, N^{-1})$. In this paper, ${\bm A}$ is generated by randomly selecting $M$ rows from the $N \times N$ DCT matrix. Hence, the low-complexity fast DCT algorithm can be used in encoding and decoding. In addition, OAMP \cite{Ma2016} can be applied to such non-IID sensing matrices. Furthermore, it is shown that the performance of partial DCT matrices is better than IID Gaussian matrices \cite{Ma_SPL2015b}. Apart from that, it was proved that the OAMP decoding is potential Bayes optimal and obtains the maximum \emph{a posteriori} (MAP) solution of \eqref{equ.recovery_model}. } SR codes work well at a very large length but are not as good as expected in more practical scenarios (e.g., limited code length and high code rates). Therefore a new method to improve the performance is needed. \subsection{ {Regularly Clipped SR Code }}\label{Sec:RC_SRC} Clipping is normally applied to reduce PAPR. It sets the signals whose absolute value is larger than a given threshold to the threshold and then normalizes the transmitted signals to keep the same power. {Let ${\mathrm{clip}}(\cdot)$ be a symbol-by-symbol clipping given by \begin{equation}\label{Eqn:clip} {\mathrm{clip}}_{\epsilon}\left( z \right) =\left\{ \begin{array}{l} \epsilon, \qquad \;z>\epsilon\\ z, \qquad |z| \leq \epsilon\\ -\epsilon, \quad\;\; z<-\epsilon \end{array} \right. \end{equation} The clipping ratio (CR) of ${\mathrm{clip}}(\cdot)$ in \eqref{Eqn:clip} is defined as ${\rm CR} = 10\rm{log}_{10}(\epsilon^2/E\{z^2\})$. Then, the codeword ${\bm c}$ is given by a normalized clipping function defined as \cite{Liang_cl2017} \begin{equation}\label{Eqn:C_SRC} {\bm c} = \alpha \, {\mathrm{clip}}_{\epsilon}(\bf{Ax}) \end{equation} where $ \alpha= \frac{1}{\sqrt{{\rm E} \{\|{\mathrm{clip}}(\bf{Ax})\|^2\}/M}}$ is a normalizing factor. We call \eqref{Eqn:C_SRC} a regularly clipped SR code since all the elements in $\bf{Ax}$ are clipped with the same threshold $\epsilon$. Intuitively, $\alpha$ makes a power compensation for the clipping operation, which introduces a tradeoff between the clipping distortion and channel noise distortion.} \begin{figure}[t \includegraphics[width =8.5cm]{clippedSR.pdf} \caption{ {Graphical illustrations of (a) clipped SR codes and AWGN channel, (b) OAMP decoding and (c) state evolution of OAMP. Functions $\gamma$ and $\phi$ in (b) are respectively corresponding to $\Gamma$ and $\Phi$ in (a). $\bf{F}$ and $\bf{F}^{-1}$ are DCT and inverse DCT (IDCT) corresponding to the transfer $\bf{F}$ in (a). Orthogonalization ``orth" is used to solve the correlation problem in iterative process.}} \label{Fig.SR_block} \end{figure} {For simplicity, we rewrite the problem as: \begin{subequations}\label{equ.clipped_SR} \begin{align} &\Gamma:\quad\bm{y}= \alpha \, {\rm clip}_{\epsilon}(\bm{z})+\bm{n}, \vspace{1.5mm}\label{equ.clipped_SR_a}\\ & \Psi:\quad\bm{z} = \bm{Fx}, \label{equ.clipped_SR_b} \\ &\Phi:\quad \bf{x}_l \sim P(\bm{x}_l),\;\; \forall l, \label{equ.clipped_SR_c} \end{align} \end{subequations} where $\Gamma$ contains a symbol-by-symbol clipping and an AWGN channel, $\Psi$ is a DCT process ($\bm{F}$ is a DCT matrix), $\bm{x}_l$ denotes the $l$-th section in $\bf{x}$, and $\Phi$ the block sparse modulation in \eqref{Eqn:block_sparse}. Fig. \ref{Fig.SR_block}(a) gives a graphical illustration of the clipped SR codes.} {Optimized clipping can significantly improve the SER performance of SR codes \cite{Liang_cl2017}. For example, as shown in Fig. \ref{Fig.simulation_result}, when code length $=10^{4}$ and $R=0.5$, the clipped SR code with optimal clipping threshold achieves 4dB gain in SNR at SER $=10^{-5}$ comparing the un-clipped case. However, it is still 2dB away from the Shannon limit (0 dB for $R=0.5$) of the system in \eqref{equ.recovery_model} \subsection{ {OAMP Decoding}} {Fig. \ref{Fig.SR_block}(b) gives an illustration of the OAMP decoding process, which consists of the following modules: \begin{itemize} \item De-clipping process $\gamma(\cdot)$ solves the clipping-and-AWGN constraint $\Gamma$ in \eqref{equ.clipped_SR_a}. \item De-modulation process $\phi(\cdot)$ for the sparse modulation constraint $\Phi$ in \eqref{equ.clipped_SR_c}. \item $\bf{F}$ and $\bf{F}^{-1}$ correspond to the transfer constraint in \eqref{equ.clipped_SR_a}. \item The orthogonalization ``orth" solves the correlation problem in iterative process and ensures the correctness of state evolution \cite{Ma2016}. \end{itemize} Their expressions are given by \begin{subequations}\label{equ.OAMP} \begin{align} \!\!\!\!&{\rm Declip:}& \bm{z}_{\rm post}&=\gamma_\epsilon(\bm{z}_{\rm pri})={\rm E} \{\bm{z}|\Gamma,\bm{z}_{\rm pri},v_{z_{\rm pri}}\},\label{equ.OAMP.Declip} \\ && v_{\rm post}&=\! \gamma_\epsilon^{\rm SE}(v_{z_{\rm pri}})\!=\!{\rm var} \{ \bm{z}|\Gamma\!,\bm{z}_{\rm pri},v_{z_{\rm pri}}\}, \label{equ.OAMP.Declip_v} \\ \nonumber\\ & {\rm Orth:}& v_{z_{\rm orth}} &\!=\!{\cal O}_{\rm SE}\big(\delta v_{z_{\rm post}}\!\!+\!(1\!-\!\delta)v_{z_{\rm pri}},v_{z_{\rm pri}}\big),\\ & & \bm{z}_{\rm orth} &= {\cal O}(\bm{z}_{\rm post},v_{z_{\rm post}};\bm{z}_{\rm pri},v_{z_{\rm pri}}), \\ \nonumbe \\ &{\rm IDCT:} & \bm{x}_{\rm pri} &= \bm{F}^{-1}\bm{z}_{\rm orth},\quad v_{x_{\rm pri}} = v_{z_{\rm orth}}, \label{equ.OAMP.IFFT} \\\nonumber\\ &{\rm Demod:} & \bm{x}_{\rm post} &= \phi(\bm{x}_{\rm pri})= {\rm E} \{ \bm{x}|\Phi,\bm{x}_{\rm pri},v_{x_{\rm pri}}\}, \\ && v_{\rm post}& =\!\phi^{\rm SE}\!(v_{x_{\rm pri}}) \!=\!{\rm var} \{ \bm{x}|\Phi,\bm{x}_{\rm pri},v_{x_{\rm pri}}\!\},\\ \nonumber \\ &{\rm Orth:}& v_{x_{\rm orth}} &= {\cal O}_{\rm SE}(v_{x_{\rm post}},v_{x_{\rm pri}}),\\%(v_{x_{\rm post}}^{-1}-v_{x_{\rm pri}}^{-1})^{-1},\\ && \bf{x}_{\rm orth} &={\cal O}(\bm{x}_{\rm post},v_{x_{\rm post}};\bm{x}_{\rm pri},v_{x_{\rm pri}}),\\\nonumber \\ &{\rm DCT:} & \bm{z}_{\rm pri} &= \bm{F} \bm{x}_{\rm orth},\quad v_{z_{\rm pri}} = v_{x_{\rm orth}}, \label{equ.OAMP.FFT} \end{align} \end{subequations} where orthogonalization is defined as \begin{subequations}\label{Eqn:orth} \begin{align} v_{\rm orth} &= {\cal O}_{\rm SE}(v_{\rm post},v_{\rm pri}) \nonumber\\ &\equiv \left(v_{\rm post}^{-1}-v_{\rm pri}^{-1}\right)^{-1},\\ \bm{u}_{\rm orth}&={\cal O}(\bm{u}_{\rm post},v_{\rm post};\bm{u}_{\rm pri},v_{\rm pri})\nonumber\\ & \equiv v_{\rm orth}\left(v_{\rm post}^{-1}\bm{u}_{\rm post}-v_{\rm pri}^{-1}\bm{u}_{\rm pri}\right), \end{align} \end{subequations} and the symbol-by-symbol de-clipping and the section-by-section de-modulation are calculated by \begin{subequations}\label{1} \begin{align} &\gamma_\epsilon(z_{\rm pri})=\!\!\int\!\! zP(z|\Gamma,z_{\rm pri},v_{z_{\rm{pri}}})dz,\\ &\gamma_\epsilon^{\rm SE}(v_{z_{\rm{pri}}})=\!\!\int\!\! z^2P(z|\Gamma,z_{\rm pri},v_{z_{\rm{pri}}})dz-\gamma^2(z_{\rm pri}),\\ &\phi(\bm{x}_{\rm s}^{\rm pri})=\!\!\int\!\! \bm{x}_{\rm s}P(\bm{x}_{\rm s}|\Phi,\bm{x}_{\rm s}^{\rm pri},v_{x_{\rm{pri}}})d\bm{x}_{\rm s},\\ &\phi^{\rm SE}(\!v_{x_{\rm pri}}\!)\!=\!\tfrac{1}{B}\!\!\!\int\!\! \left\|\bm{x}_{\rm s}\!\!-\!\phi(\bm{x}_{\rm s}^{\rm pri})\right\|^2\!\!P(\bm{x}_{\rm s}|\Phi\!,\bm{x}_{\rm s}^{\rm pri},v_{x_{\rm{pri}}})d\bm{x}_{\rm s}. \end{align} \end{subequations} The subscript ``$\rm s$'' denotes a section of the corresponding variance vector (see \eqref{Eqn:block_sparse}).} \underline{\textbf{State Evolution (SE):}} SE has been strictly proven to be a numerical tool \cite{Rangan2016, Takeuchi2017} that can asymptotically characterize the performance of OAMP decoding with any unitarily-invariant matrices. {For simplicity, we let $v_z=v_{z_{\rm pri}}=v_{x_{\rm orth}}$ and $v_x=v_{x_{\rm pri}}=v_{z_{\rm orth}}$. The transfer curves of the orthogonal de-clipping and orthogonal demodulation are given by \begin{subequations}\label{Eqn:SE} \begin{align} \!\!\!& v_x \!= \!\gamma_{\rm orth}^{\rm SE}(v_z,\epsilon, \lambda)\!\equiv \! {\cal O}_{\rm SE}\!\left(\delta\gamma_\epsilon^{\rm SE}(v_z)+(1\!-\!\delta)v_z,v_z\right)\\ \!\!\!& \hspace{2.6cm}=\!v_z\! \big[ \delta^{-1}\big(1\!- \! \lambda \gamma_{\epsilon}^{\rm SE}(v_z)/ v_z\big)^{\!-1}\!\!\! -1 \big],\label{equ.SE.declip}\\ \!\!\!& v_z = \phi_{\rm orth}^{\rm SE}(v_x)\equiv {\cal O}_{\rm SE}\left(\phi^{\rm SE}(v_x),v_x\right).\label{equ.SE.demod} \end{align} \end{subequations} where ${\cal O}_{\rm SE}(\cdot)$ is given in \eqref{Eqn:orth}. In practice, the local transfer curves $\gamma_{\rm orth}^{\rm SE}(\cdot)$ and $\phi_{\rm orth}^{\rm SE}(\cdot)$ can be obtained by local Monte Carlo simulations, using the IID Gaussian property of OAMP. } \section{ {Irregularly clipped SR Code}} {In this section, we propose an irregular clipping technique to further improve the SER performance of the clipped SR codes. Using SE, we optimize the distribution of irregular clipping thresholds to minimize the SER of SR codes.} \subsection{ {Irregular Clipping}}\label{Gamma'} {In the regular clipping in Section \ref{Sec:RC_SRC}, all the elements are clipped based on the same threshold. Differently, in irregular clipping, different clipping thresholds can be applied to different symbols, which provides more optimization space for the SR codes and thus results in better performance.} {Define the irregular clipping function as \begin{equation}\label{Eqn:Irr_clip} \bm{c}={\rm clip}^{\rm Irr}_{\bm{\epsilon },\bf{\lambda}}(\bm{z}). \end{equation} where $\bf{\epsilon}=[\epsilon_1 \cdots\epsilon_K]$. Specifically, $\bm{z}$ is partitioned into $K$ subvectors $\{\bm{z}_1 \cdots\bm{z}_K\}$, where $\bm{z}_k$ is clipped with threshold $\epsilon_k$ and has length $\lambda_kM$. $\bf{\lambda}=[\lambda_1 \cdots\lambda_K]$ denotes the threshold distribution of $\bf{\epsilon}$ with $0\leq\lambda_k\leq1$ and $\sum_{k=1}^K\lambda_k=1$. Therefore, the codeword length is still $M$. Similarly, $\bm{c}$ is partitioned into $\{\bm{c}_1 \cdots\bm{c}_K\}$. Then, the irregular clipping function in \eqref{Eqn:Irr_clip} is given by \begin{equation}\label{equ.irr_clipping} \bm{c}_k = \alpha_k \, {\rm clip}_{\epsilon_k}(\bm{z}_k),\quad k=1,\dots,K, \end{equation} where ${\rm clip}_{\epsilon_k}(\cdot)$ is defined in \eqref{Eqn:clip} and $\alpha_k$ is a power compensation parameter for clipping function ${\rm clip}_{\epsilon_k}(\cdot)$. Similarly to \eqref{equ.clipped_SR}, we define an irregularly clipped SR code as \begin{subequations}\label{eqn:Ic_SR} \begin{align} &\tilde{\Gamma}:\quad\bm{y}={\rm clip}^{\rm Irr}_{\bm{\epsilon },\bf{\lambda}}(\bm{z})+\bm{n}, \vspace{1.5mm}\label{eqn:Ic_SR_a}\\ & \Psi:\quad\bm{z} = \bm{Fx}, \label{eqn:Ic_SR_b} \\ &\Phi:\quad \bf{x}_l \sim P(\bm{x}_l),\;\; \forall l, \label{eqn:Ic_SR_c} \end{align} \end{subequations} where ${\rm clip}^{\rm Irr}_{\bm{\epsilon },\bf{\lambda}}(\cdot)$ is given in \eqref{equ.irr_clipping}, and \eqref{eqn:Ic_SR_b} and \eqref{eqn:Ic_SR_c} are the same as those in \eqref{equ.clipped_SR}.} \subsection{ {OAMP Decoding for Irregularly Clipped SR codes}} Let $\bm{z}_{\rm post}=[\bm{z}^{\rm post}_1 \cdots, \bm{z}^{\rm post}_K]$, $\bm{z}_{\rm pri}=[\bm{z}^{\rm pri}_1 \cdots, \bm{z}^{\rm pri}_K]$ and $\bm{z}_{\rm orth}=[\bm{z}^{\rm orth}_1 \cdots, \bm{z}^{\rm orth}_K]$. In the decoding of irregularly clipped SR codes, the de-clipping is performed for each subvector. Thus, the de-clipping in \eqref{equ.OAMP} is replaced by: $ \forall k$, \begin{subequations} \begin{align} &\!\!\! {\rm Irr\!-\!declip}: &\!\!\! \bm{z}_k^{\rm post} &= {\gamma}_{\epsilon_k}(\bm{z}_k^{\rm pri}), \label{Eqn:irr_declip}\\ &\!\!\!& \!\!\!\!\!v_{z_{\rm post}} &= \sum\limits_{k=1}^{K} \lambda_k {\gamma}_{\epsilon_k}^{\rm SE}(v_{z_{\rm pri}}), \label{Eqn:irr_declip_v} \end{align} \end{subequations} where $\gamma_{\epsilon_k}(\cdot)$ and $\gamma_{\epsilon_k}^{\rm SE}(\cdot)$ are respectively given in \eqref{equ.OAMP.Declip} and \eqref{equ.OAMP.Declip_v}. The other parts (e.g. demodulation, orthogonalization and DCT/IDCT) of the OAMP decoding of irregularly clipped SR codes are the same as those in \eqref{equ.OAMP}. \underline{\textbf{State Evolution (SE):}} In irregularly clipped SR codes, the transfer curve of orthogonal irregular de-clipping is given by \begin{subequations}\label{Eqn:SE_irr} \begin{align} v_x &= \tilde{\gamma}_{\rm orth}^{\rm SE}(v_z,\bf{\epsilon},\bf{\lambda})\\ &\equiv \Big[\Big(\delta \! \sum\limits_{k=1}^{K} \! \lambda_k \gamma_{\epsilon_k}^{\rm SE}(v_z) + (1-\delta) v_z\Big)^{-1} - v_z^{-1}\Big]^{\!-1} \\ &= v_z \Big[ \delta^{-1}\Big(1-\sum\limits_{k=1}^{K} \! \lambda_k \gamma_{\epsilon_k}^{\rm SE}(v_z)/ v_z\Big)^{-1} -1 \Big], \end{align} \end{subequations} where $\gamma_{\rm orth}^{\rm SE}(v_z,\epsilon)$ is given in \eqref{equ.SE.declip}. The transfer curve of orthogonal demodulation is the same as the regularly clipped SR codes in \eqref{equ.SE.demod}. \underline{\textbf{Complexity:}} It is easy to see that the computational complexity of irregularly clipped SR codes is almost the same as that of regularly clipped SR codes, dominated by DCT/IDCT with complexity $\mathcal{O}(N\log N)$ per iteration. \subsection{ {Optimization of Irregular Clipping Thresholds}}\label{opt} {In this subsection, given the irregular clipping threshold vector $\bf{\epsilon}$, we will discuss the optimization $\bf{\lambda}=[\lambda_1 \cdots \lambda_K]$. Intuitively, the distribution vector $\bf{\lambda}$ controls the contribution of the different clipping thresholds. Therefore, we can optimize $\bf{\lambda}$ to minimize the SER performance of irregularly clipped SR codes. Equivalently, given ${\rm SNR}$, we can maximize the minimal gap between the transfer curves $\tilde{\gamma}_{\rm orth}^{\rm SE}$ and $\phi_{\rm orth}^{\rm SE}$ in $[v_{\min}, 1]$, where $v_{\min}$ is a small enough positive number to obtain the desired SER performance. Hence, the optimization problem can be described as \begin{subequations}\begin{align} {\mathcal P}_1: \;\; \mathop{\rm{max}}_{\bm{ \lambda}} \mathop{\rm{min}}_{v\in[v_{\min},1]} \;\;& {\phi_{\rm orth}^{{\rm SE}^{-1}}}\!(v)- \tilde{\gamma}_{\rm orth}^{\rm SE}(v,\bf{\epsilon},\bm{\lambda}),\\ {\rm s.t.}\;& \; \sum\limits_{k=1}^{K} \lambda_k = 1,\\ & \; 0\leq \lambda_k\leq 1, \end{align}\end{subequations} where $\tilde{\gamma}_{\rm orth}^{\rm SE}(v,\bf{\epsilon},\bm{\lambda})$ is given in \eqref{Eqn:SE_irr}, and ${\phi_{\rm orth}^{{\rm SE}^{-1}}}(\cdot)$ is an inverse function of ${\phi_{\rm orth}^{{\rm SE}}}(\cdot)$ in \eqref{equ.SE.demod}. } Notice that the objective function in ${\mathcal P}_1$ is a complicated function of $v$. Given $\bf{\lambda}$, it is very difficult to find the analytical solution of ${\mathcal P}_1$ on the continuous region ${v\in[v_{\min},1]}$. To overcome this problem, we consider minimization on the uniformly sampling points $\mathcal{V}=\{v_i\}$ on $[v_{\min},1]$ in log domain. In general, we set $v_{\min}=10^{-6}$ and the number of sampling points as 100, i.e., $|\mathcal{V}|=100$. Therefore, following \eqref{Eqn:SE_irr}, ${\mathcal P}_1$ can be rewritten to the following optimization problem: \begin{subequations}\begin{align} \!\! {\mathcal P}_2: \;\; \mathop{\rm{max}}_{\bm{ \lambda}} \; \mathop{\rm{min}}_{v_i\in{\mathcal{V}}} &\quad {\phi_{\rm orth}^{{\rm SE}^{-1}}}(v_i) - \tilde{\gamma}_{\rm orth}^{\rm SE}(v_i,\bf{\epsilon},\bm{\lambda}),\\ {\rm s.t.}& \quad \sum\limits_{k=1}^{K} \lambda_k = 1,\\ & \quad 0\leq \lambda_k\leq 1. \end{align}\end{subequations} Note that $\delta, v_i, \gamma_{\epsilon_k}^{\rm SE}(v_i)$ are all positive. It is easy to verify that $\{\tilde{\gamma}_{\rm orth}^{\rm SE}(v_i,\bf{\epsilon},\bm{\lambda}), \forall i\}$ (see \eqref{Eqn:SE_irr}) are concave functions of $\bf{\lambda}$. The minimization of concave functions is also concave \cite{Boyd2004}. In addition, the constraints in ${\mathcal P}_2$ are linear. Therefore, ${\mathcal P}_2$ is a concave problem of $\bf{\lambda}$ and thus it can be solved using standard convex optimization tools. \subsection{ {Transfer Chart Comparison of Regularly Clipped and Irregularly Clipped SR codes}}\label{SE_ana} \begin{figure}[t] \centering \includegraphics[width = 8.8cm]{SE_new.pdf} \caption{ {SE transfer charts of (a) the optimized regularly clipped SR code with ${\rm SNR}=2$ dB and (b) the optimized irregularly clipped SR codes with ${\rm SNR}=1.3$ dB. $B=64$, $L=2048$ and $R=0.5$. The optimal CR of regular clipping for regularly clipped SR codes is $-13$ dB.}} \label{Fig.SE} \end{figure} {Fig. \ref{Fig.SE} compares the SE transfer charts of the optimized regularly clipped SR codes and the optimized irregularly clipped SR codes. As illustrated in Fig. \ref{Fig.SE}, to ensure the OAMP decoding converges to the target SER, the key is to create a decoding tunnel between the curves of demodulation and de-clipping. Let $v_{\min}$ be the target performance. There should be no fixed point in the region $v\leq v_{\min}$, since otherwise the tunnel will be closed at $v > v_{\min}$. It is shown that the tunnel is opened at ${\rm SNR}=2$ dB for regularly clipped SR codes (see Fig. \ref{Fig.SE}(a)), and at ${\rm SNR}=1.3$ dB for irregularly clipped SR codes (see Fig. \ref{Fig.SE}(b)). In other words, following the SE transfer chart analysis, irregularly clipped SR codes achieve about $0.7$ dB gain in ${\rm SNR}$ comparing with regularly clipped SR codes for the target performance $v_{\min}=10^{-5}$.} \section{Simulation Results} {Fig. \ref{Fig.simulation_result} gives the SERs of non-clipped SR code, optimized regularly clipped SR code and optimized irregularly clipped SR code. The parameters are set as $B=64$, $L=2048$, $R = 0.5$ (code rate), $M = 24,576$ (code length) and ${\rm SNR}=\sigma^{-2}_n$. The optimal CR of regularly clipped SR codes is $-13$ dB. The irregularly clipped SR codes involve 19 candidate CRs for irregular clipping. For the irregularly clipped SR codes in Fig. \ref{Fig.simulation_result}, the CRs and corresponding distribution vector $\lambda$ are optimized for each simulated SNR (see the concave optimization in Section \ref{opt}). The maximum number of iterations is 120. As we can see in Fig.~\ref{Fig.simulation_result}, the proposed irregularly clipped SR codes achieve better SER performance than regularly clipped and non-clipped. Comparing with regularly clipped SR codes \cite{Liang_cl2017}, irregularly clipped SR codes achieve about 0.4 dB gain in ${\rm SNR}$ at SER=$10^{-5}$.} \begin{figure}[t] \centering \includegraphics[width =8.8cm]{clip.pdf} \caption{ {SER comparison between the non-clipped SR codes, optimized regularly clipped SR codes and optimized irregularly clipped SR codes. $B=64$, $L=2048$, $R = 0.5$ (code rate), $M = 24,576$ (code length) and ${\rm SNR}=\sigma^{-2}_n$. The CRs and its distribution $\bm{\lambda}$ are given in Table \ref{tab.lambda}. The maximum number of iterations is 120. The optimal CR of regular clipping for regularly clipped SR codes is $-13$ dB.}} \label{Fig.simulation_result} \end{figure} Fig.~\ref{Fig.rates} gives the SERs of optimized irregularly clipped SR codes with code rates $R=\{0.2, 0.4, 0.6,0.8, 1\}$. The parameters are set as $B=64$, $L=2048$, and $M = \{61440, 30720, 20480, 15360, 12288\} $ (code lengths). The maximum number of iterations is 100. As can be seen, the optimized irregularly clipped SR codes exhibit characteristic waterfall behavior for a range of rate from 0.2 (low rate) to 1 (high rate). Every point in Fig.~\ref{Fig.rates} uses different CRs and $\bm{\lambda}$. Table~\ref{tab.lambda} shows the $\bm{\lambda}$ of each code rate for the points whose SER is close to $10^{-5}$. \begin{figure}[t] \centering \includegraphics[width =8.75cm]{Rates.pdf} \caption{ SERs of the optimized irregularly clipped SR codes with different code rates. $B=64$, $L=2048$, $R=\{0.2, 0.4, 0.6,0.8, 1\}$ (code rates), $M = \{61440, 30720, 20480, 15360, 12288\} $ (code lengths) and ${\rm SNR}=\sigma^{-2}_n$. CRs and the distribution are given in Table~\ref{tab.lambda}. The maximum number of iterations is 100.} \label{Fig.rates} \end{figure} \begin{table}[] \centering \caption{optimized coefficient CRs and $\bm{\lambda}$ }\footnotesize \begin{tabular}{ccc} \hline R &SNR (dB)&CR (dB) and $\bm{\lambda}$ \\ \hline \multirow{2}*{0.2} & \multirow{2}*{-3.6} &\!\!-300 \qquad -12 \qquad\;-10 \qquad\;-8\\ &&0.04460\; 0.27394\; 0.38313\; 0.29831\\ \hline \multirow{4}*{0.4} & \multirow{4}*{0.2} &\!\!-300 \quad\;\;\;-30 \qquad\;\;-16 \qquad\;-10 \qquad\;\;-8 \ \\ &&0.02590\; 0.05297\; 0.00756\; 0.00145\; 0.17107\\ &&\!\!-6 \ \ \qquad -2 \qquad\ \;0 \qquad\ \ \;4\\&&0.51890\; 0.13035\; 0.00790\; 0.08390\\ \hline\multirow{4}*{0.5} & \multirow{4}*{1.6} &-300 \qquad\;\;-24\qquad\;\;-22\qquad\;\;-18\qquad\;\;-6\\ &&0.01251\; 0.12000\; 0.00027\; 0.00293\; 0.00031\\ &&-5\qquad\;\;-4\qquad\;\;-3\qquad\;\;-2\\ &&0.07169\; 0.56832\; 0.16883\; 0.05508\\ \hline \multirow{4}*{0.6} & \multirow{4}*{2.8}&-300\ \ \qquad-30\ \ \qquad-19\ \ \qquad-16\\&&0.02048\; 0.01288\; 0.13391\; 0.00462\\&&-12\ \ \qquad-4 \ \ \ \qquad-2\ \ \ \qquad0\\&&0.00034\; 0.19962\; 0.26163\; 0.36647\\ \hline \multirow{4}*{0.8} & \multirow{4}*{4.8}&-300 \qquad-30\ \qquad -22\ \ \qquad-16 \ \qquad-14 \ \ \\&&0.01207\; 0.02881\; 0.01619\; 0.07276 \ 0.04741\\&&-10 \quad \qquad0 \quad \qquad2 \quad \qquad6 \quad \qquad8\\&& 0.07536\; 0.06970\; 0.43372\ 0.17212\; 0.07178\\ \hline \multirow{4}*{1.0} & \multirow{4}*{6.4}&-300\ \qquad-30\ \ \qquad-22\ \qquad-20 \ \ \\&&0.00899\; 0.03115\; 0.00010\; 0.00380\\&& -16\ \ \qquad-14\ \ \qquad-6\ \qquad300\ \ \\&&0.00037\; 0.16628\; 0.00015\; 0.78912 \\ \hline \end{tabular} \label{tab.lambda} \end{table} \section{Conclusion} This paper investigated irregular clipping for SR codes with OAMP decoding. Using SE analysis, we constructed a convex optimization problem to minimize the SER of irregularly clipped SR codes by optimizing the distribution of the clipping thresholds. As a result, the proposed irregularly clipped SR codes achieve a better SER performance than the existing regularly clipped SR codes. When compared with regularly clipped SR codes, irregularly clipped SR codes achieve about 0.4 dB gain in SNR at code length $\approx 2.5\times 10^4$ and ${\rm SER}\approx 10^{-5}$. Furthermore, irregularly clipped SR codes are robust in a wide range of code rates, e.g., from 0.2 (low rate) to 1 (high rate). \section*{Acknowledgment} The authors thank Shansuo Liang for the discussions that have improved the quality of this work greatly.
{'timestamp': '2021-06-04T02:09:58', 'yymm': '2106', 'arxiv_id': '2106.01573', 'language': 'en', 'url': 'https://arxiv.org/abs/2106.01573'}
arxiv
\section{Introduction} \vspace{-0.5ex} Deep neural networks (DNNs) usually exhibit excellent generalization ability in pattern recognition tasks, despite their sufficient capacity to overfit or \emph{memorize} the entire training set with completely random labels \citep{zhang2017understanding}. The memorization behavior in deep learning has aroused tremendous attention to identifying the differences between learning on true and random labels \citep{arpit2017closer,neyshabur2017exploring}, and examining what and why DNNs memorize \citep{feldman2020does,feldman2020neural,maennel2020neural}. This phenomenon has also motivated a growing body of works on model capacity \citep{arpit2017closer,belkin2019reconciling}, convergence \citep{allen2019convergence,du2019gradient,zou2020gradient}, and generalization \citep{neyshabur2017exploring,bartlett2017spectrally}, which consequently provide a better understanding of the DNN working mechanism. In this paper, we explore the memorization behavior for a different learning algorithm---\textbf{adversarial training (AT)}. Owing to the security threat of adversarial examples, i.e., maliciously generated inputs by adding imperceptible perturbations to cause misclassification \citep{szegedy2013intriguing,goodfellow2014explaining}, various defense methods have been proposed to improve the adversarial robustness of DNNs \citep{kurakin2016adversarial,madry2017towards,liao2018defense,wong2018provable,cohen2019certified,zhang2019theoretically,pang2019improving,pang2019rethinking,dong2020adversarial}. AT is arguably the most effective defense technique \citep{Athalye2018Obfuscated,dong2020benchmarking}, in which the network is trained on the adversarially augmented samples instead of the natural ones \citep{madry2017towards}. \begin{figure}[t] \vspace{-3.5ex} \centering \includegraphics[width=0.9\columnwidth]{figures/demo.pdf}\vspace{-1ex} \caption{A conceptual illustration of decision boundaries learned via standard training and adversarial training with true and random labels, respectively. The model needs a significantly more complicated decision boundary to memorize adversarial examples of training data with random labels.}\vspace{-2.5ex} \label{fig:demo} \end{figure} Despite the popularity, the memorization behavior in AT is less explored. \citet{schmidt2018adversarially} show that a model is able to fully (over)fit the training set against an adversary, i.e., reaching almost $100\%$ robust training accuracy, while the performance on test data is much inferior, witnessing a significant generalization gap. The overfitting phenomenon in AT is further investigated in \cite{rice2020overfitting}. However, it is not clear \emph{whether DNNs could memorize adversarial examples of training data with completely random labels}. Answering this question could help to examine the effects of memorization in AT under the ``extreme'' circumstance and facilitate a deeper understanding of capacity, convergence, generalization, and robust overfitting of the adversarially trained models. In general, it is difficult for a classifier to memorize adversarial examples with random labels since the model entails a much more complicated decision boundary, as illustrated in Fig.~\ref{fig:demo}. Even though the networks have sufficient capacity, AT may not necessarily converge. Therefore, we aim to comprehensively study this problem and explore how the analysis can motivate better algorithms. \textbf{Our contributions.} We first empirically investigate the memorization behavior in AT by performing \textbf{PGD-AT} \citep{madry2017towards} and \textbf{TRADES} \citep{zhang2019theoretically} with random labels sampled uniformly over all classes. Different from standard training (ST) that can easily memorize random labels \citep{zhang2017understanding}, AT may \emph{fail to converge}, with PGD-AT being a typical example. Nevertheless, TRADES can converge under this circumstance. It demonstrates that DNNs have \emph{sufficient capacity} to memorize adversarial examples of training data with completely random labels. This phenomenon is commonly observed on multiple datasets, network architectures, and threat models. The memorization analysis has further implications for understanding the \emph{convergence} and \emph{generalization} of AT. We conduct a convergence analysis on gradient magnitude and stability to explain the counter-intuitive different convergence properties of PGD-AT and TRADES with random labels since they behave similarly when trained on true labels \citep{rice2020overfitting}. We corroborate that PGD-AT suffers from a gradient instability issue while the gradients of TRADES are relatively stable thanks to its adversarial loss. Moreover, by considering models trained on random labels, our generalization analysis indicates that several recently suggested complexity measures are inadequate to explain robust generalization, which is complementary to the findings in ST \citep{neyshabur2017exploring}. Accordingly, an appropriate explanation of robust generalization remains largely under-addressed Lastly, but most importantly, we identify a significant drawback of memorization in AT that it could result in \emph{robust overfitting} \citep{rice2020overfitting}. We argue that the cause of robust overfitting lies in the memorization of one-hot labels in the typical AT methods. The one-hot labels can be inappropriate or even \emph{noisy} for some adversarial examples because some data naturally lies close to the decision boundary, and the corresponding adversarial examples should be assigned low predictive confidence \citep{stutz2020confidence,cheng2020cat}. To solve this problem, we propose a new mitigation algorithm that impedes over-confident predictions by regularization for avoiding the excessive memorization of adversarial examples with possibly noisy labels. Experiments validate that our method can eliminate robust overfitting to a large extent across multiple datasets, network architectures, threat models, and AT methods, achieving better robustness under a variety of adversarial attacks than the baselines. \vspace{-1ex} \section{Background} \vspace{-1ex} \subsection{Adversarial training}\label{sec:2-1} \vspace{-0.7ex} Let $\mathcal{D}=\{(\vect{x}_i,y_i)\}_{i=1}^n$ denote a training dataset with $n$ samples, where $\vect{x}_i \in \mathbb{R}^d$ is a natural example and $y_i\in\{1,...,C\}$ is its true label often encoded as an one-hot vector $\mathbf{1}_{y_i}$ with totally $C$ classes. Adversarial training (AT) can be formulated as a robust optimization problem \citep{madry2017towards}: \begin{equation} \label{eq:at} \min_{\vect{\theta}}\sum_{i=1}^{n} \max_{\vect{x}_i'\in\mathcal{S}(\vect{x}_i)}\mathcal{L}(f_{\vect{\theta}}(\vect{x}_i'), y_i), \end{equation} where $f_{\vect{\theta}}$ is a DNN classifier with parameters $\vect{\theta}$ that predicts probabilities over all classes, $\mathcal{L}$ is the classification loss (i.e., the cross-entropy loss as $\mathcal{L}(f_{\vect{\theta}}(\vect{x}), y)=-\mathbf{1}_{y}^{\top}\log f_{\vect{\theta}}(\vect{x})$), and $\mathcal{S}(\vect{x}) = \{{\vect{x}'}: \|\vect{x}'-\vect{x}\|_p\leq\epsilon\}$ is an adversarial region centered at $\vect{x}$ with radius $\epsilon>0$ under the $\ell_p$-norm threat models (e.g., $\ell_2$ and $\ell_\infty$ norms that we consider). The robust optimization problem~(\ref{eq:at}) is solved by using adversarial attacks to approximate the inner maximization and updating the model parameters $\vect{\theta}$ via gradient descent. A typical method uses projected gradient descent (PGD) \citep{madry2017towards} for the inner problem, which starts at a randomly initialized point in $\mathcal{S}(\vect{x}_i)$ and iteratively updates the adversarial example under the $\ell_\infty$-norm threat model by \begin{equation} \vect{x}_i'=\Pi_{\mathcal{S}(\vect{x}_i)}\big(\vect{x}_i' + \alpha\cdot\mathrm{sign}(\nabla_{\vect{x}}\mathcal{L}(f_{\vect{\theta}}(\vect{x}_i'),y_i))\big),\label{eq:pgd} \end{equation} where $\Pi(\cdot)$ is the projection operator and $\alpha$ is the step size. Besides PGD-AT, another typical AT method is TRADES \citep{zhang2019theoretically}, which balances the trade-off between robustness and natural accuracy by minimizing a different adversarial loss \begin{equation \min_{\vect{\theta}}\sum_{i=1}^{n}\left\{ \mathcal{L}(f_{\vect{\theta}}(\vect{x}_i), y_i)+ \beta\cdot\max_{\vect{x}_i'\in\mathcal{S}(\vect{x}_i)}\mathcal{D}(f_{\vect{\theta}}(\vect{x}_i)\Vert f_{\vect{\theta}}(\vect{x}_i'))\right\}, \label{eq:trades} \end{equation} where $\mathcal{L}$ is the clean cross-entropy loss on the natural example, $\mathcal{D}$ is the Kullback–Leibler divergence, and $\beta$ is a balancing parameter. The inner maximization of TRADES is also solved by PGD. Recent progress of AT includes designing new adversarial losses \citep{mao2019metric,qin2019adversarial,pang2019rethinking,wang2020improving,dong2020adversarial} and network architecture \citep{xie2019feature}, training acceleration \citep{shafahi2019adversarial,zhang2019you,wong2020fast}, and exploiting more training data \citep{hendrycks2019using,alayrac2019labels,carmon2019unlabeled,zhai2019adversarially}. Recent works highlight the training tricks in AT \citep{gowal2020uncovering,pang2020bag}. \vspace{-0.5ex} \subsection{Related work on DNN memorization} \vspace{-0.5ex} It has been observed that DNNs can easily memorize training data with random labels \citep{zhang2017understanding}, which requires ``rethinking'' of conventional techniques (e.g., VC dimension) to explain generalization. \citet{arpit2017closer} identify qualitative differences between learning on true and random labels. Further works attempt to examine what and why DNNs memorize \citep{feldman2020does,feldman2020neural,maennel2020neural}. Motivated by the memorization phenomenon in deep learning, convergence of training has been analyzed in the over-parameterized setting \citep{allen2019convergence, du2019gradient,zou2020gradient}, while generalization has been studied with numerous theoretical and empirical complexity measures \citep{neyshabur2015norm,neyshabur2017exploring,bartlett2017spectrally,novak2018sensitivity,arora2018stronger,cao2019generalization,jiang2019fantastic,chen2020much}. In contrast, the memorization behavior in AT has been less explored. The previous works demonstrate that DNNs can fit training data against an adversary \citep{madry2017towards,schmidt2018adversarially,rice2020overfitting}, e.g., achieving nearly $100\%$ robust training accuracy against a PGD adversary, but this behavior is not explored when trained on random labels. This paper is dedicated to investigating the memorization in AT under the extreme condition with random labels, while drawing connections to capacity, convergence, generalization, and robust overfitting, with the overarching goal of better understanding the AT working mechanism. \vspace{-1ex} \section{Memorization in AT and implications}\label{sec:3} \vspace{-0.5ex} In this section, we first explore the memorization behavior in AT through an empirical study. Our analysis raises new questions about the convergence and generalization of AT, many of which cannot be answered by existing works. Thereafter, we provide further analytical studies on the convergence and generalization of AT by considering models trained on random labels particularly. \vspace{-0.5ex} \subsection{AT with random labels}\label{sec:3.1} \vspace{-0.5ex} We explore the memorization behavior of PGD-AT \citep{madry2017towards} and TRADES \citep{zhang2019theoretically} as two studying cases. The experiments are conducted on CIFAR-10 \citep{krizhevsky2009learning} with a Wide ResNet model \citep{zagoruyko2016wide} of depth 28 and widen factor 10 (WRN-28-10). Similar to \cite{zhang2017understanding}, we train a network on the original dataset with true labels and on a copy of the dataset in which the true labels are corrupted by random ones. For training and robustness evaluation, a 10-step $\ell_\infty$ PGD adversary with $\epsilon=8/255$ and $\alpha=2/255$ is adopted. For TRADES, the PGD adversary maximizes the KL divergence during training, while maximizes the cross-entropy loss for robustness evaluation, as common practice \citep{zhang2019theoretically}. We set $\beta=6.0$. In the sequel, we denote accuracy of a classifier against the 10-step PGD adversary as ``\textbf{robust accuracy}'', and accuracy on natural examples as ``\textbf{natural accuracy}''. \begin{figure}[t] \vspace{-2.5ex} \centering \begin{subfigure}[b]{0.30\linewidth} \centering \includegraphics[width=\textwidth]{figures/plot-pgd.pdf} \vspace{-3ex}\caption{PGD-AT} \label{fig:1a} \end{subfigure}\hspace{1.5ex} \begin{subfigure}[b]{0.30\linewidth} \centering \includegraphics[width=\textwidth]{figures/plot-trades.pdf} \vspace{-3ex}\caption{TRADES} \label{fig:1b} \end{subfigure}\hspace{1.5ex} \begin{subfigure}[b]{0.30\linewidth} \centering \includegraphics[width=\textwidth]{figures/plot-gap.pdf} \vspace{-3ex}\caption{Generalization gap growth} \label{fig:1c} \end{subfigure}\vspace{-1.2ex} \caption{(a) and (b) show the natural and robust training accuracies of PGD-AT and TRADES, respectively, when trained on true or random labels. (c) shows the generalization gap under varying levels of label noise.}\vspace{-2.5ex} \label{fig:fitting} \end{figure} Fig.~\ref{fig:1a} and Fig.~\ref{fig:1b} show the learning curves of PGD-AT and TRADES without explicit regularizations. Both methods achieve almost $100\%$ natural and robust training accuracies when trained on true labels. When the labels are random, we observe the totally different behaviors between PGD-AT and TRADES---PGD-AT fails to converge while TRADES still reaches nearly $100\%$ training accuracies. This phenomenon is somewhat striking because PGD-AT and TRADES perform similarly on true labels \citep{rice2020overfitting}. We find that the different memorization behaviors between PGD-AT and TRADES when trained on random labels can commonly be observed across a variety of datasets, model architectures, and threat models (shown in Appendix \ref{app:a1}), indicating that it is a general phenomenon of memorization in the two AT methods. Therefore, our finding is: \emph{DNNs have sufficient capacity to memorize adversarial examples of training data with completely random labels, but the convergence depends on the AT algorithms.} \textbf{Partially corrupted labels.} We then inspect the behavior of AT under varying levels of label noise from $0\%$ (true labels) to $100\%$ (completely random labels). The generalization gap (i.e., difference between training and test accuracies) presented in Fig.~\ref{fig:1c} grows steadily as we increase the noise rate before the network fails to converge. The learning curves are provided in Appendix \ref{app:a1}. \textbf{Explicit regularizations.} We study the role of common regularizers in AT memorization, including data augmentation, weight decay, and dropout \citep{srivastava2014dropout}. We train TRADES on true and random labels with several combinations of regularizers. We observe the explicit regularizers do not significantly affect the model’s ability to memorize adversarial examples, similar to the finding in ST \citep{zhang2017understanding,arpit2017closer}. The detailed results are provided in Appendix \ref{app:a1}. \vspace{-0.5ex} \subsection{Convergence analysis of AT with random labels}\label{sec:3-2} \vspace{-0.5ex} Since we have observed a counter-intuitive fact that PGD-AT and TRADES exhibit different convergence properties with random labels, it is necessary to perform a convergence analysis to understand this phenomenon. Note that our finding can hardly be explained by previous works \citep{gao2019convergence,wang2019convergence,zhang2020over}. We first study the effects of different training settings on PGD-AT with random labels. We conduct experiments to analyze each training factor individually, including network architecture, attack steps, optimizer, and perturbation budget. We find that tuning the training settings cannot make PGD-AT converge with random labels (Appendix \ref{app:a2} details the results). Based on the analysis, we think that the convergence issue of PGD-AT could be a result of the adversarial loss function in Eq.~(\ref{eq:at}) rather than other training configurations. Specifically, TRADES in Eq.~(\ref{eq:trades}) minimizes a clean cross-entropy (CE) loss on natural examples, making DNNs memorize natural examples with random labels before fitting adversarial examples. As seen in Fig.~\ref{fig:1b}, at the very early stage of TRADES training (the first 25 epochs), the natural accuracy starts to increase while the robust accuracy does not. However, PGD-AT in Eq.~(\ref{eq:at}) directly minimizes the CE loss on adversarial samples with random labels, which can introduce unstable gradients with large variance, making it fail to converge. To corroborate the above argument, we analyze the gradient magnitude and stability below. \textbf{Gradient magnitude.} First, we calculate the average gradient norm of the adversarial loss in Eq.~(\ref{eq:at}) w.r.t. model parameters over each training sample for PGD-AT, and similarly calculate the average gradient norm of the clean CE loss (the first term) and the KL loss (the second term) in Eq.~(\ref{eq:trades}) w.r.t. parameters for TRADES to analyze their effects, respectively. We present the gradient norm along with training in Fig.~\ref{fig:2b}. We can see that at the initial training epochs, the gradient norm of the KL loss in TRADES is much smaller than that of the CE loss, which indicates that the CE loss dominates TRADES training initially. With the training progressing, the KL loss has a larger gradient norm, making the network memorize adversarial examples. However, it is still unclear why PGD-AT does not rely on a similar learning tactic for convergence. To make a direct comparison with TRADES, we rewrite the adversarial loss of PGD-AT in Eq.~(\ref{eq:at}) as \begin{equation*} \max_{\vect{x}_i'\in\mathcal{S}(\vect{x}_i)}\mathcal{L}(f_{\vect{\theta}}(\vect{x}_i'), y_i) = \mathcal{L}(f_{\vect{\theta}}(\vect{x}_i), y_i) + \mathcal{R}(\vect{x}_i, y_i, \vect{\theta}), \end{equation*} where $\mathcal{R}(\vect{x}_i, y_i, \vect{\theta})$ denotes the difference between the CE loss on adversarial example $\vect{x}_i'$ and that on natural example $\vect{x}_i$. Hence we can separately calculate the gradient norm of $\mathcal{L}(f_{\vect{\theta}}(\vect{x}_i), y_i)$ and $\mathcal{R}(\vect{x}_i, y_i, \vect{\theta})$ w.r.t. parameters $\vect{\theta}$ to find out the effect of $\mathcal{R}(\vect{x}_i, y_i, \vect{\theta})$ on training. Specifically, we measure the relative gradient magnitude, i.e., in PGD-AT we calculate the ratio of the gradient norm $\frac{\|\nabla_{\vect{\theta}}\mathcal{R}(\vect{x}_i, y_i, \vect{\theta})\|_2}{\|\nabla_{\vect{\theta}}\mathcal{L}(f_{\vect{\theta}}(\vect{x}_i), y_i)\|_2}$; while in TRADES, we similarly calculate the ratio of the gradient norm of the KL loss to that of the CE loss. Fig.~\ref{fig:2a} illustrates the ratio of PGD-AT and TRADES during the first 1000 training iterations. The ratio of PGD-AT is consistently higher than that of TRADES, meaning that $\mathcal{R}(\vect{x}_i, y_i, \vect{\theta})$ has a non-negligible impact on training. \begin{figure}[t] \vspace{-2.5ex} \centering \begin{minipage}{.494\textwidth} \begin{subfigure}[b]{0.49\columnwidth} \centering \includegraphics[width=\textwidth]{figures/pgd_g1.pdf} \vspace{-3ex}\caption{} \label{fig:2b} \end{subfigure}\hspace{0.2ex} \begin{subfigure}[b]{0.48\columnwidth} \centering \includegraphics[width=\textwidth]{figures/plot-norm.pdf} \vspace{-3ex}\caption{} \label{fig:2a} \end{subfigure} \vspace{-1ex} \caption{(a): Gradient norm of PGD-AT and TRADES along the training process. (b): The ratio of the gradient norm of PGD-AT and TRADES during the first 1000 training iterations.} \label{fig:norm} \end{minipage}\hspace{0.5ex} \begin{minipage}{.494\textwidth} \begin{subfigure}[b]{0.49\columnwidth} \centering \includegraphics[width=\textwidth]{figures/plot-stability.pdf} \vspace{-3ex}\caption{} \label{fig:3a} \end{subfigure}\hspace{0.2ex} \begin{subfigure}[b]{0.49\columnwidth} \centering \includegraphics[width=\textwidth]{figures/pgd_g2.pdf} \vspace{-3.4ex}\caption{} \label{fig:3b} \end{subfigure} \vspace{-3.7ex} \caption{(a): The $\ell_2$ distance between the gradients at $\vect{\theta}$ and $\vect{\theta}+\lambda\vect{d}$ of different losses, where $\vect{\theta}$ are initialized, $\lambda\in[-0.05,0.05]$. (b): The cosine similarity between the gradients in each two successive epochs.} \end{minipage} \vspace{-2.5ex} \end{figure} \textbf{Gradient stability.} Then, we analyze the gradient stability to explain why PGD-AT cannot converge. We denote the adversarial loss of PGD-AT as $\mathcal{J}(\vect{x}, y, \vect{\theta}) = \max_{\vect{x}'\in\mathcal{S}(\vect{x})}\mathcal{L}(f_{\vect{\theta}}(\vect{x}'), y)$ with the subscript $i$ omitted for notation simplicity. We have a theorem on gradient stability. \begin{theorem}\label{thm:1} Suppose the gradient of the clean cross-entropy loss is locally Lipschitz continuous as \begin{equation}\label{eq:ass} \|\nabla_{\vect{\theta}}\mathcal{L}(f_{\vect{\theta}}(\vect{x}'), y) - \nabla_{\vect{\theta}}\mathcal{L}(f_{\vect{\theta}}(\vect{x}), y)\|_2 \leq K\|\vect{x}'-\vect{x}\|_p, \end{equation} for any $\vect{x}\in\mathbb{R}^d$, $\vect{x}'\in \mathcal{S}(\vect{x})$, and any $\vect{\theta}$, where $K$ is the Lipschitz constant. Then we have \begin{equation}\label{eq:smooth} \|\nabla_{\vect{\theta}}\mathcal{J}(\vect{x}, y, \vect{\theta}_1) - \nabla_{\vect{\theta}}\mathcal{J}(\vect{x}, y, \vect{\theta}_2) \|_2 \leq \|\nabla_{\vect{\theta}}\mathcal{L}(f_{\vect{\theta}_1}(\vect{x}), y) - \nabla_{\vect{\theta}}\mathcal{L}(f_{\vect{\theta}_2}(\vect{x}), y)\|_2 + 2\epsilon K. \end{equation} \end{theorem} We provide the proof in Appendix \ref{app:b}, where we show the upper bound in Eq.~(\ref{eq:smooth}) is tight. Theorem~\ref{thm:1} indicates that the gradient of the adversarial loss $\mathcal{J}(\vect{x}, y, \vect{\theta})$ of PGD-AT will change more dramatically than that of the clean CE loss $\mathcal{L}(f_{\vect{\theta}}(\vect{x}), y)$. When $\vect{\theta}_1$ and $\vect{\theta}_2$ are close, the difference between the gradients of $\mathcal{L}$ at $\vect{\theta}_1$ and $\vect{\theta}_2$ is close to $0$ due to the semi-smoothness of over-parameterized DNNs \citep{allen2019convergence}, but that of $\mathcal{J}$ is relatively large due to $2\epsilon K$ in Eq.~(\ref{eq:smooth}). To validate this, we visualize the change of gradient when moving the parameters $\vect{\theta}$ along a random direction $\vect{d}$ with magnitude $\lambda$. In particular, we set $\vect{\theta}$ as initialization, $\vect{d}$ is sampled from a Gaussian distribution and normalized filter-wise \citep{li2018visualizing}. For PGD-AT and TRADES, we craft adversarial examples on-the-fly for the model with $\vect{\theta}+\lambda\vect{d}$ and measure the change of gradient by the $\ell_2$ distance to gradient at $\vect{\theta}$ averaged over all data samples. The curves on gradient change of PGD-AT, TRADES, and the clean CE loss are shown in Fig.~\ref{fig:3a}. In a small neighborhood of $\vect{\theta}$ (i.e., small $\lambda$), the gradient of PGD-AT changes abruptly while the gradients of TRADES and the clean CE loss are more continuous. The gradient instability leads to a lower cosine similarity between the gradient directions w.r.t. the same data in each two successive training epochs of PGD-AT, as illustrated in Fig.~\ref{fig:3b}. Therefore, the training of PGD-AT would be rather unstable that the gradient exhibits large variance, making it fail to converge. \begin{wrapfigure}{r}{0.25\linewidth} \vspace{-6ex} \centering \includegraphics[width=0.99\linewidth,height=15ex]{add_fig/plot-adaptive.pdf}\vspace{-2ex} \caption{AT by Eq.~(\ref{eq:6})}.\vspace{-5ex} \label{fig:refine} \end{wrapfigure} \textbf{Clean CE loss helps PGD-AT converge.} To further verify our argument, we add the clean CE loss into the PGD-AT objective to resemble the learning of TRADES with random labels, as \begin{equation}\label{eq:6} \min_{\vect{\theta}}\sum_{i=1}^{n}\left\{ (1-\gamma)\cdot\mathcal{L}(f_{\vect{\theta}}(\vect{x}_i), y_i) + \gamma\cdot \max_{\vect{x}_i'\in\mathcal{S}(\vect{x}_i)}\mathcal{L}(f_{\vect{\theta}}(\vect{x}_i'), y_i)\right\}, \end{equation} where $\gamma$ is gradually increased from $0$ to $1$. By using Eq.~(\ref{eq:6}), the gradient would be stabler at the initial stage and training on random labels can successfully converge, as shown Fig.~\ref{fig:refine}. \textbf{In summary}, our convergence analysis identifies the gradient instability issue of PGD-AT, provides new insights on the differences between PGD-AT and TRADES, and partially explain the failures of AT under other realistic settings beyond the scope of this section as detailed in Appendix \ref{app:a2}. \iffalse \begin{table*}[t] \vspace{-2ex} \caption{The training accuracy, test accuracy, and generalization gap (\%) of TRADES when trained on true or random labels, with and without explicit regularizations, including data augmentation (random crop and flip), weight decay ($0.0002$), and dropout ($0.2$). \centering \small \begin{tabular}{c|c|c|c|cc|cc|cc} \hline \multirow{2}{*}{Labels} & Data & Weight & \multirow{2}{*}{Dropout} & \multicolumn{2}{c|}{Training Accuracy} & \multicolumn{2}{c|}{Test Accuracy} & \multicolumn{2}{c}{Generalization Gap} \\ & Augmentation & Decay & & Natural & Robust & Natural & Robust & Natural & Robust \\ \hline true & \xmark & \xmark & \xmark & 99.73 & 99.65 & 77.53 & 37.47 & 22.20 & 62.18 \\ true & \cmark & \xmark & \xmark & 99.57 & 97.03 & 82.91 & 45.37 & 16.93 & 51.66 \\ true & \xmark & \cmark & \xmark & 99.59 & 99.53 & 77.31 & 38.94 & 22.28 & 60.59 \\ true & \xmark & \xmark & \cmark & 99.65 & 99.40 & 79.96 & 39.86 & 19.69 & 59.54 \\ true & \cmark & \cmark & \xmark & 99.50 & 97.28 & 84.26 & 49.16 & 15.24 & 48.12 \\ true & \xmark & \cmark & \cmark & 99.41 & 99.20 & 80.28 & 41.64 & 19.13 & 57.56 \\ \hline random & \xmark & \xmark & \xmark & 99.80 & 99.55 & 9.79 & 0.15 & 90.01 & 99.40 \\ random & \cmark & \xmark & \xmark & 99.36 & 86.10 & 9.71 & 0.24 & 89.65 & 85.86 \\ random & \xmark & \cmark & \xmark & 99.84 & 99.53 & 10.13 & 0.23 & 89.71 & 99.30 \\ random & \xmark & \xmark & \cmark & 99.15 & 92.23 & 9.04 & 0.17 & 90.11 & 92.06 \\ random & \cmark & \cmark & \xmark & 99.25 & 69.62 & 9.67 & 0.24 & 89.58 & 69.38 \\ random & \xmark & \cmark & \cmark & 99.38 & 81.57 & 9.54 & 0.19 & 89.84 & 81.38 \\ \hline \end{tabular} \vspace{-1ex} \label{table:reg} \end{table*} \begin{figure}[t] \centering \includegraphics[width=0.95\linewidth]{figures/plot-acc.pdf}\vspace{-2.5ex} \caption{The robust training accuracy, test accuracy, and generalization gap of TRADES when trained on true or random labels, with and without explicit regularizations, including data augmentation (\emph{DA}: random crop and flip), weight decay (\emph{WD}: $0.0002$), and \emph{dropout} ($0.2$). The exact numbers of the results are provided in Table~A.1 in Appendix A.4.} \label{fig:reg}\vspace{-0.6ex} \end{figure} \begin{figure}[t] \centering \includegraphics[width=0.95\linewidth]{figures/trades_full.pdf}\vspace{-2.5ex} \caption{Accuracy curves of TRADES under different noise rates on CIFAR-10.}\vspace{-2ex} \label{fig:full} \end{figure} \fi \vspace{-0.5ex} \subsection{Generalization analysis of AT with random labels \vspace{-0.5ex} As our study demonstrates DNNs' ability to memorize adversarial examples with random labels, we raise the question of whether DNNs rely on a similar memorization tactic on true labels and how to explain/ensure robust generalization. Although many efforts have been devoted to studying robust generalization of AT theoretically or empirically \citep{yin2018rademacher,schmidt2018adversarially,bubeck2019adversarial,tu2019theoretical,wu2020adversarial}, they do not take the models trained on random labels into consideration. As it is easy to show that the explicit regularizations are not the adequate explanation of generalization in ST \citep{zhang2017understanding,arpit2017closer} and AT (see Appendix \ref{app:a3}), people resort to complexity measures of a model to explain generalization (i.e., a lower complexity should imply a smaller generalization gap). Here we show how the recently proposed complexity measures fail to explain robust generalization when comparing models trained on true and random labels. \begin{figure}[t] \vspace{-3ex} \centering \includegraphics[width=0.99\columnwidth]{figures/plot-measure.pdf}\vspace{-1.5ex} \caption{The results on four complexity measures of the adversarially trained models w.r.t. robust generalization gap. The training settings of these models are provided in Appendix \ref{app:a3}.}\vspace{-3ex} \label{fig:measure} \end{figure} We consider several norm-based and sharpness/flatness-based measures. We denote the parameters of a network by $\vect{\theta} := \{W_i\}_{i=1}^m$. The norm-based measures include spectral norm $\frac{1}{\gamma_{\text{margin}}}\prod_{i=1}^m\|W_i\|_2$ and $\ell_1$ norm $\frac{1}{\gamma_{\text{margin}}}\sum_{i=1}^m\|W_i\|_1$ of model parameters, where $\gamma_{\text{margin}}$ is a margin on model output to make them scale-insensitive \citep{neyshabur2017exploring}. The spectral norm appears in the theoretical robust generalization bounds \citep{yin2018rademacher,tu2019theoretical} and is related to the Lipschitz constant of neural networks \citep{cisse2017parseval}. The $\ell_1$ norm is adopted to reduce the robust generalization gap \citep{yin2018rademacher}. The sharpness/flatness-based measures include the curvature of input loss landscape \citep{moosavi2019robustness} as the dominant eigenvalue of the Hessian matrix, as well as the flatness of weight loss landscape \citep{wu2020adversarial} related to the change of adversarial loss when moving the weights along a random direction. Fig.~\ref{fig:measure} plots the four complexity measures w.r.t. robust generalization gap of several models trained with various combinations of regularizations on true or random labels. The results show that the first three measures can hardly ensure robust generalization, that lower complexity does not necessarily imply smaller robust generalization gap, e.g., the models trained on random labels can even lead to lower complexity than those trained on true labels. Among them, the flatness of weight loss landscape \citep{wu2020adversarial} is more reliable. \textbf{In summary}, the generalization analysis indicates that the previous approaches, especially various complexity measures, cannot adequately explain and ensure the robust generalization performance in AT. Our finding of robust generalization in AT is complementary to that of standard generalization in ST \citep{zhang2017understanding,neyshabur2017exploring,jiang2019fantastic}. Accordingly, robust generalization of adversarially trained models remains an open problem for future research. \vspace{-1.5ex} \section{Robust overfitting analysis}\label{sec:4} \vspace{-0.6ex} \citet{rice2020overfitting} have identified robust overfitting as a dominant phenomenon in AT, i.e., shortly after the first learning rate decay, further training will continue to decrease the robust test accuracy. They further show that several remedies for overfitting, including explicit $\ell_1$ and $\ell_2$ regularizations, data augmentation, etc., cannot gain improvements upon early stopping. Although robust overfitting has been thoroughly investigated, there still lacks an explanation of why it occurs. In this section, we draw a connection between memorization and robust overfitting in AT by showing that robust overfitting is caused by excessive memorization of one-hot labels in the typical AT methods. Motivated by the analysis, we then propose an effective strategy to eliminate robust overfitting. \vspace{-1ex} \subsection{Explaining robust overfitting} \vspace{-0.5ex} The typical AT approaches (e.g., PGD-AT, TRADES) commonly adopt one-hot labels as the targets for training, as introduced in Sec.~\ref{sec:2-1}. The one-hot labels could be inappropriate for some adversarial examples because it is difficult for a network to assign high-confident one-hot labels for all perturbed samples within the perturbation budget $\epsilon$ \citep{stutz2020confidence,cheng2020cat}. Intuitively, some examples may naturally lie close to the decision boundary and should be assigned lower predictive confidence for the worst-case adversarial examples. It indicates that one-hot labels of some training data may be \emph{noisy} in AT\footnote{Note that we argue the one-hot labels are noisy when used in AT, but do not argue the ground-truth labels of the dataset are noisy, which is different from a previous work \citep{sanyal2021how}.}. After a certain training epoch, the model memorizes these ``hard'' training examples with possibly noisy labels, leading to the reduction of test robustness, as shown in Fig.~\ref{fig:6a}. Thus, we hypothesize the cause of robust overfitting lies in the \emph{memorization of one-hot labels}. Our hypothesis is well supported by two pieces of evidence. First, we find that when the perturbation budget $\epsilon$ is small, robust overfitting does not occur, as shown in Fig.~\ref{fig:6b}. This observation implies that the one-hot labels are more appropriate as the targets for adversarial examples within a smaller neighborhood while become noisier under a larger perturbation budget and lead to overfitting. Second, we validate that the ``hard'' training examples with higher adversarial loss values are consistent across different models. We first train two independent networks (using the same architecture and different random seeds) by PGD-AT and calculate the adversarial loss for each training sample. We show the adversarial losses on 500 samples sorted by the loss of the first model in Fig.~\ref{fig:6c}. It can be seen that the samples with lower adversarial losses of the first model also have relatively lower losses of the second one and vice versa. We further quantitatively measure the consistency of the adversarial losses of all training samples between the two models using the Kendall’s rank coefficient \citep{kendall1938new}, which is $0.85$ in this case. A similar result can be observed for two different model architectures (see Appendix \ref{app:c1}). The results verify that the ``hard'' training examples with possibly noisy labels are intrinsic of a dataset, supporting our hypothesis on why robust overfitting occurs. \begin{figure}[t] \vspace{-2.5ex} \centering \begin{subfigure}[b]{0.30\linewidth} \centering \includegraphics[width=\textwidth]{figures/pgd_test_noise0.0.pdf} \vspace{-3ex}\caption{} \label{fig:6a} \end{subfigure}\hspace{1.5ex} \begin{subfigure}[b]{0.30\linewidth} \centering \includegraphics[width=\textwidth]{figures/plot-epsilon} \vspace{-3ex}\caption{} \label{fig:6b} \end{subfigure}\hspace{1.5ex} \begin{subfigure}[b]{0.30\linewidth} \centering \includegraphics[width=\textwidth]{figures/plot-loss.pdf} \vspace{-3ex}\caption{} \label{fig:6c} \end{subfigure}\vspace{-1.3ex} \caption{(a): The accuracy curves of PGD-AT with true labels to reproduce robust overfitting. (b): The robust test accuracy of PGD-AT under various perturbation budgets $\epsilon$. (c): The adversarial loss of two independently trained networks by PGD-AT on 500 samples sorted by the loss of the first model.}\vspace{-2.5ex} \end{figure} \vspace{-0.5ex} \subsection{Mitigating robust overfitting} \vspace{-0.5ex} Based on the above analysis, we resort to the methods that are less prone to overfit noisy labels for mitigating robust overfitting in AT. Although learning with noisy labels has been broadly studied in ST \citep{natarajan2013learning,patrini2017making,jiang2017mentornet,han2018co,zhang2018generalized}, we find that most of these approaches are not suitable for AT. For example, a typical line of methods filter out noisy samples and train the models on the identified clean samples \citep{jiang2017mentornet,han2018co,ren2018learning}. However, they will neglect a portion of training data with noisy labels, which can lead to inferior results for AT due to the reduction of training data \citep{schmidt2018adversarially}. Table~\ref{table:res2} shows the results to validate this. To address this problem, we propose to regularize the predictions of adversarial examples from being over-confident by integrating the \textbf{temporal ensembling (TE)} approach \citep{laine2016temporal} into the AT frameworks. TE maintains an ensemble prediction of each data and penalizes the difference between the current prediction and the ensemble prediction, which is effective for semi-supervised learning and learning with noisy labels \citep{laine2016temporal}. We think that TE is suitable for AT since it enables to leverage all training samples and hinders the network from excessive memorization of one-hot labels with a regularization term. Specifically, we denote the ensemble prediction of a training sample $\vect{x}_i$ as $\vect{p}_i$, which is updated in each training epoch as $\vect{p}_i\leftarrow \eta\cdot \vect{p}_i + (1-\eta)\cdot f_{\vect{\theta}}(\vect{x}_i)$, where $\eta$ is the momentum term. The training objective of PGD-AT with TE can be expressed as \begin{equation} \label{eq:at-te} \min_{\vect{\theta}}\sum_{i=1}^{n} \max_{\vect{x}_i'\in\mathcal{S}(\vect{x}_i)}\left\{\mathcal{L}(f_{\vect{\theta}}(\vect{x}_i'), y_i) + w\cdot \|f_{\vect{\theta}}(\vect{x}_i') - \hat{\vect{p}}_i\|_2^2\right\}, \end{equation} where $\hat{\vect{p}}_i$ is the normalization of $\vect{p}_i$ as a probability vector and $w$ is a balancing weight. TE can be similarly integrated with TRADES with the same regularization term. The network would learn to fit relatively easy samples with one-hot labels in the initial training stage, as shown in Fig.~\ref{fig:6a}. After the learning rate decays, the network can keep assigning low confidence for hard samples with the regularization term in Eq.~(\ref{eq:at-te}) and avoid fitting one-hot labels. Therefore, the proposed algorithm enables to learn under label noise in AT and alleviates the robust overfitting problem. \vspace{-1ex} \section{Empirical evaluation on mitigating robust overfitting} \label{sec:5}\vspace{-0.5ex} In this section, we provide the experimental results on CIFAR-10, CIFAR-100 \citep{krizhevsky2009learning}, and SVHN \citep{netzer2011reading} datasets to validate the effectiveness of our proposed method. Code is available at \url{https://github.com/dongyp13/memorization-AT}. \begin{table}[t] \vspace{-2.5ex} \caption{Test accuracy (\%) of several methods on CIFAR-10, CIFAR-100, and SVHN under the $\ell_\infty$ norm with $\epsilon=8/255$ based on the ResNet-18 architecture. We choose the best checkpoint according to the highest robust accuracy on the test set under PGD-10.}\vspace{-1.5ex} \begin{subtable}{\linewidth} \centering \small \setlength{\tabcolsep}{1.8pt} \begin{tabular}{l|ccc|ccc|ccc|ccc|ccc} \toprule \multirow{2}{*}{Method} & \multicolumn{3}{c|}{Natural Accuracy} & \multicolumn{3}{c|}{PGD-10} & \multicolumn{3}{c|}{PGD-1000} & \multicolumn{3}{c|}{C\&W-1000} & \multicolumn{3}{c}{AutoAttack} \\ & Best & Final & Diff & Best & Final & Diff & Best & Final & Diff & Best & Final & Diff & Best & Final & Diff \\ \midrule PGD-AT & \bf83.75 & \bf84.82 & -1.07 & 52.64 & 44.92 & 7.72 & 51.22 & 42.74 & 8.48 & 50.11 & 43.63 & 7.48 & 47.74 & 41.84 & 5.90 \\ PGD-AT\textbf{+TE} & 82.35 & 82.79 & \bf-0.44 & \bf55.79 & \bf54.83 & \bf0.96 & \bf54.65 & \bf53.30 & \bf1.35 & \bf52.30 & \bf51.73 & \bf0.57 & \bf50.59 & \bf49.62 & \bf0.97 \\ \midrule TRADES & 81.19 & 82.48 & -1.29 & 53.32 & 50.25 & 3.07 & 52.44 & 48.67 & 3.77 & 49.88 & 48.14 & 1.74 & 49.03 & 46.80 & 2.23 \\ TRADES\textbf{+TE} & \bf83.86 & \bf83.97 & \bf-0.11 & \bf55.15 & \bf54.42 & \bf0.73 & \bf53.74 & \bf53.03 & \bf0.71 & \bf50.77 & \bf50.63 & \bf0.14 & \bf49.77 & \bf49.20 & \bf0.57 \\ \bottomrule \end{tabular \caption{The evaluation results on \textbf{CIFAR-10}.}\vspace{-0.5ex} \end{subtable} \begin{subtable}{\linewidth} \centering \small \setlength{\tabcolsep}{1.8pt} \begin{tabular}{l|ccc|ccc|ccc|ccc|ccc} \toprule \multirow{2}{*}{Method} & \multicolumn{3}{c|}{Natural Accuracy} & \multicolumn{3}{c|}{PGD-10} & \multicolumn{3}{c|}{PGD-1000} & \multicolumn{3}{c|}{C\&W-1000} & \multicolumn{3}{c}{AutoAttack} \\ & Best & Final & Diff & Best & Final & Diff & Best & Final & Diff & Best & Final & Diff & Best & Final & Diff \\ \midrule PGD-AT & \bf57.54 & \bf57.51 & \bf0.03 & 29.40 & 21.75 & 7.65 & 28.54 & 20.63 & 7.91 & 27.06 & 21.17 & 5.89 & 24.72 & 19.34 & 5.38 \\ PGD-AT\textbf{+TE} & 56.45 & 57.12 & -0.67 & \bf31.74 & \bf30.24 & \bf1.50 & \bf31.27 & \bf29.80 & \bf1.47 & \bf28.27 & \bf27.36 & \bf0.91 & \bf26.30 & \bf25.34 & \bf0.96 \\ \midrule TRADES & 57.98 & 56.32 & 1.66 & 29.93 & 27.70 & 2.23 & 29.51 & 26.93 & 2.58 & 25.46 & 24.42 & 1.04 & 24.61 & 23.40 & 1.21 \\ TRADES\textbf{+TE} & \bf59.35 & \bf58.72 & \bf0.63 & \bf31.09 & \bf30.12 & \bf0.97 & \bf30.54 & \bf29.45 & \bf1.09 & \bf26.61 & \bf25.94 & \bf0.67 & \bf25.27 & \bf24.55 & \bf0.72 \\ \bottomrule \end{tabular \caption{The evaluation results on \textbf{CIFAR-100}.}\vspace{-0.5ex} \end{subtable} \begin{subtable}{\linewidth} \centering \small \setlength{\tabcolsep}{1.8pt} \begin{tabular}{l|ccc|ccc|ccc|ccc|ccc} \toprule \multirow{2}{*}{Method} & \multicolumn{3}{c|}{Natural Accuracy} & \multicolumn{3}{c|}{PGD-10} & \multicolumn{3}{c|}{PGD-1000} & \multicolumn{3}{c|}{C\&W-1000} & \multicolumn{3}{c}{AutoAttack} \\ & Best & Final & Diff & Best & Final & Diff & Best & Final & Diff & Best & Final & Diff & Best & Final & Diff \\ \midrule PGD-AT & 89.00 & 90.55 & -1.55 & 54.51 & 46.97 & 7.54 & 52.22 & 42.85 & 9.37 & 48.66 & 44.13 & 4.53 & 46.61 & 38.24 & 8.37 \\ PGD-AT\textbf{+TE} & \bf90.09 & \bf90.91 & \bf-0.82 & \bf59.74 & \bf59.05 & \bf0.69 & \bf57.71 & \bf56.46 & \bf1.25 & \bf54.55 & \bf53.94 & \bf0.61 & \bf51.44 & \bf50.61 & \bf0.83 \\ \midrule TRADES & \bf90.88 & \bf91.30 & \bf-0.42 & 59.50 & 57.04 & 2.46 & 52.78 & 50.17 & 2.61 & 52.76 & 50.53 & 2.23 & 40.36 & 38.88 & 1.48 \\ TRADES\textbf{+TE} & 89.01 & 88.52 & 0.49 & \bf59.81 & \bf58.49 & \bf1.32 & \bf58.24 & \bf56.66 & \bf1.58 & \bf54.00 & \bf53.24 & \bf0.76 & \bf51.45 & \bf50.16 & \bf1.29 \\ \bottomrule \end{tabular \caption{The evaluation results on \textbf{SVHN}.}\vspace{-5ex} \end{subtable} \label{table:res} \end{table} \textbf{Training details.} We adopt the common setting that the perturbation budget is $\epsilon=8/255$ under the $\ell_\infty$ norm in most experiments. We consider PGD-AT and TRADES as two typical AT baselines and integrate the proposed TE approach into them, respectively. We use the ResNet-18 \citep{he2016deep} model as the classifier in most experiments. In training, we use the 10-step PGD adversary with $\alpha=2/255$. The models are trained via the SGD optimizer with momentum $0.9$, weight decay $0.0005$, and batch size $128$. For CIFAR-10/100, we set the learning rate as $0.1$ initially which is decayed by $0.1$ at $100$ and $150$ epochs with totally $200$ training epochs. For SVHN, the learning rate starts from $0.01$ with a cosine annealing schedule for a total number of $80$ training epochs. In our method, We set $\eta=0.9$ and $w=30$ along a Gaussian ramp-up curve \citep{laine2016temporal}. \textbf{Evaluation results.} We adopt PGD-10, PGD-1000, C\&W-1000 \citep{carlini2017towards}, and AutoAttack \citep{croce2020reliable} for evaluating adversarial robustness rigorously. AutoAttack is a strong attack to evaluate model robustness, which is composed of an ensemble of diverse attacks, including APGD-CE \citep{croce2020reliable}, APGD-DLR \citep{croce2020reliable}, FAB \citep{croce2020minimally}, and Square attack \citep{andriushchenko2020square}. To show the performance of robust overfitting, we report the test accuracy on the best checkpoint that achieves the highest robust test accuracy under PGD-10 and the final checkpoint, as well as the difference between these two checkpoints. The results of PGD-AT, TRADES, and the combinations of them with our proposed approach (denoted as PGD-AT\textbf{+TE} and TRADES\textbf{+TE}) on the CIFAR-10, CIFAR-100, and SVHN datasets are shown in Table~\ref{table:res}. \begin{wrapfigure}{r}{0.6\linewidth} \vspace{-1.5ex} \centering \includegraphics[width=0.99\linewidth]{figures/plot-te.pdf}\vspace{-1ex} \caption{The natural and robust test accuracy curves (under PGD-10) of PGD-AT, TRADES, and their extensions by integrating the proposed TE approach. The models are trained on CIFAR-10 under the $\ell_\infty$ norm with $\epsilon=8/255$ based on the ResNet-18 architecture.}\vspace{-1.5ex} \label{fig:te} \end{wrapfigure} We can observe that the differences between best and final test accuracies of our method are reduced to around $1\%$, while the accuracy gaps of PGD-AT and TRADES are much larger. It indicates that our method largely eliminates robust overfitting. Due to being less affected by robust overfitting, our method achieves higher robust accuracies than the baselines. We also show the learning curves of these methods in Fig.~\ref{fig:te}. We consistently demonstrate the effectiveness of our method on different network architectures (including WRN-34-10 and VGG-16) and threat models (including $\ell_2$ norm), which will be shown in Appendix \ref{app:c2}. \textbf{Discussion and comparison with related works.} Our method is kind of similar to the label smoothing (LS) technique, which is studied in AT \citep{pang2020bag}. Recent works have also introduced the smoothness in training labels and model weights \citep{chen2021robust,huang2020self}, which can alleviate robust overfitting to some extent. The significant difference between our work and them is that we provide a reasonable explanation for robust overfitting---\emph{one-hot labels are noisy for AT}, while previous methods did not give such an explanation and could be viewed as solutions to our identified problem. To empirically compare with these methods, we conduct experiments on CIFAR-10 with the ResNet-18 network. Under the PGD-AT framework, we compare with the baseline PGD-AT, PGD-AT\textbf{+LS}, self-adaptive training (SAT) \citep{huang2020self}, and knowledge distillation with stochastic weight averaging (KD-SWA) \citep{chen2021robust}. We also adopt the \emph{Co-teaching} approach \citep{han2018co} adapted to PGD-AT, which jointly trains two models using the filtered samples given by each other. The results under the adopted attacks are presented in Table~\ref{table:res2}. Although various techniques can alleviate robust overfitting, our method achieves better robustness than the others, validating its effectiveness. For Co-teaching, though robust overfitting is alleviated, the performance is worse than our proposed method due to the reduction of training data. \begin{table}[h] \vspace{-1ex} \caption{Test accuracy (\%) of the proposed method and other methods on CIFAR-10 under the $\ell_\infty$ norm with $\epsilon=8/255$ based on the ResNet-18 architecture.}\vspace{-1.5ex} \centering \small \setlength{\tabcolsep}{1.8pt} \begin{tabular}{l|ccc|ccc|ccc|ccc|ccc} \toprule \multirow{2}{*}{Method} & \multicolumn{3}{c|}{Natural Accuracy} & \multicolumn{3}{c|}{PGD-10} & \multicolumn{3}{c|}{PGD-1000} & \multicolumn{3}{c|}{C\&W-1000} & \multicolumn{3}{c}{AutoAttack} \\ & Best & Final & Diff & Best & Final & Diff & Best & Final & Diff & Best & Final & Diff & Best & Final & Diff \\ \midrule PGD-AT & 83.75 & 84.82 & -1.07 & 52.64 & 44.92 & 7.72 & 51.22 & 42.74 & 8.48 & 50.11 & 43.63 & 7.48 & 47.74 & 41.84 & 5.90 \\ PGD-AT\textbf{+LS} & 82.68 & 85.16 & -2.48 & 53.70 & 48.90 & 4.80 & 52.56 & 46.31 & 6.25 & 50.41 & 46.06 & 4.35 & 49.02 & 44.39 & 4.63 \\ SAT & 82.81 & 81.86 & 0.95 & 53.81 & 53.31 & \bf0.50 & 52.41 & 52.00 & \bf0.41 & 51.99 & 51.71 & \bf0.28 & 50.21 & 49.73 & \bf0.48 \\ KD-SWA & \bf84.84 & \bf85.26 & -0.42 & 54.89 & 53.80 & 1.09 & 53.31 & 52.45 & 0.86 & 51.48 & 50.91 & 0.57 & 50.42 & \bf49.83 & 0.59 \\ Co-teaching & 81.94 & 82.22 & \bf-0.28 & 51.27 & 50.52 & 0.75 & 50.15 & 49.12 & 1.03 & 50.85 & 49.86 & 0.99 & 49.60 & 48.49 & 1.11 \\ PGD-AT\textbf{+TE} & 82.35 & 82.79 & -0.44 & \bf55.79 & \bf54.83 & 0.96 & \bf54.65 & \bf53.30 & 1.35 & \bf52.30 & \bf51.73 & 0.57 & \bf50.59 & 49.62 & 0.97 \\ \bottomrule \end{tabular} \vspace{-2ex} \label{table:res2} \end{table} \vspace{-1ex} \section{Conclusion} \vspace{-1ex} In this paper, we demonstrate the capacity of DNNs to fit adversarial examples with random labels by exploring memorization in adversarial training, which also poses open questions on the convergence and generalization of adversarially trained models. We validate that some AT methods suffer from a gradient instability issue and robust generalization can hardly be explained by complexity measures. We further identify a significant drawback of memorization in AT related to the robust overfitting phenomenon---robust overfitting is caused by memorizing one-hot labels in adversarial training. We propose a new mitigation algorithm to address this issue, with the effectiveness validated extensively. \section*{Acknowledgements} This work was supported by the National Key Research and Development Program of China (2020AAA0106000, 2020AAA0104304, 2020AAA0106302), NSFC Projects (Nos. 61620106010, 62061136001, 61621136008, 62076147, U19B2034, U1811461, U19A2081), Beijing NSF Project (No. JQ19016), Beijing Academy of Artificial Intelligence (BAAI), Tsinghua-Alibaba Joint Research Program, Tsinghua Institute for Guo Qiang, Tsinghua-OPPO Joint Research Center for Future Terminal Technology. \section*{Ethics Statement} The existence of adversarial examples can pose severe security threats to machine learning and deep learning models when they are deployed to real-world applications. The vulnerability to adversarial examples could also lower the confidence of the public on machine learning techniques. Therefore, it is important to develop more robust models. As the most effective method for promoting model robustness, adversarial training (AT) has not been fully investigated. This paper aims to investigate the memorization effect of AT to facilitate a better understanding of its working mechanism. Some findings in this paper can be analyzed more deeply, including theoretical analysis of AT convergence, generalization, etc., which we leave to future work. \section*{Reproducibility Statement} Most of the experiments are easily reproducible. We provide the code for reproducing the results at \url{https://github.com/dongyp13/memorization-AT}. \section{Introduction} \vspace{-0.5ex} Deep neural networks (DNNs) usually exhibit excellent generalization ability in pattern recognition tasks, despite their sufficient capacity to overfit or \emph{memorize} the entire training set with completely random labels \citep{zhang2017understanding}. The memorization behavior in deep learning has aroused tremendous attention to identifying the differences between learning on true and random labels \citep{arpit2017closer,neyshabur2017exploring}, and examining what and why DNNs memorize \citep{feldman2020does,feldman2020neural,maennel2020neural}. This phenomenon has also motivated a growing body of works on model capacity \citep{arpit2017closer,belkin2019reconciling}, convergence \citep{allen2019convergence,du2019gradient,zou2020gradient}, and generalization \citep{neyshabur2017exploring,bartlett2017spectrally}, which consequently provide a better understanding of the DNN working mechanism. In this paper, we explore the memorization behavior for a different learning algorithm---\textbf{adversarial training (AT)}. Owing to the security threat of adversarial examples, i.e., maliciously generated inputs by adding imperceptible perturbations to cause misclassification \citep{szegedy2013intriguing,goodfellow2014explaining}, various defense methods have been proposed to improve the adversarial robustness of DNNs \citep{kurakin2016adversarial,madry2017towards,liao2018defense,wong2018provable,cohen2019certified,zhang2019theoretically,pang2019improving,pang2019rethinking,dong2020adversarial}. AT is arguably the most effective defense technique \citep{Athalye2018Obfuscated,dong2020benchmarking}, in which the network is trained on the adversarially augmented samples instead of the natural ones \citep{madry2017towards}. \begin{figure}[t] \vspace{-3.5ex} \centering \includegraphics[width=0.9\columnwidth]{figures/demo.pdf}\vspace{-1ex} \caption{A conceptual illustration of decision boundaries learned via standard training and adversarial training with true and random labels, respectively. The model needs a significantly more complicated decision boundary to memorize adversarial examples of training data with random labels.}\vspace{-2.5ex} \label{fig:demo} \end{figure} Despite the popularity, the memorization behavior in AT is less explored. \citet{schmidt2018adversarially} show that a model is able to fully (over)fit the training set against an adversary, i.e., reaching almost $100\%$ robust training accuracy, while the performance on test data is much inferior, witnessing a significant generalization gap. The overfitting phenomenon in AT is further investigated in \cite{rice2020overfitting}. However, it is not clear \emph{whether DNNs could memorize adversarial examples of training data with completely random labels}. Answering this question could help to examine the effects of memorization in AT under the ``extreme'' circumstance and facilitate a deeper understanding of capacity, convergence, generalization, and robust overfitting of the adversarially trained models. In general, it is difficult for a classifier to memorize adversarial examples with random labels since the model entails a much more complicated decision boundary, as illustrated in Fig.~\ref{fig:demo}. Even though the networks have sufficient capacity, AT may not necessarily converge. Therefore, we aim to comprehensively study this problem and explore how the analysis can motivate better algorithms. \textbf{Our contributions.} We first empirically investigate the memorization behavior in AT by performing \textbf{PGD-AT} \citep{madry2017towards} and \textbf{TRADES} \citep{zhang2019theoretically} with random labels sampled uniformly over all classes. Different from standard training (ST) that can easily memorize random labels \citep{zhang2017understanding}, AT may \emph{fail to converge}, with PGD-AT being a typical example. Nevertheless, TRADES can converge under this circumstance. It demonstrates that DNNs have \emph{sufficient capacity} to memorize adversarial examples of training data with completely random labels. This phenomenon is commonly observed on multiple datasets, network architectures, and threat models. The memorization analysis has further implications for understanding the \emph{convergence} and \emph{generalization} of AT. We conduct a convergence analysis on gradient magnitude and stability to explain the counter-intuitive different convergence properties of PGD-AT and TRADES with random labels since they behave similarly when trained on true labels \citep{rice2020overfitting}. We corroborate that PGD-AT suffers from a gradient instability issue while the gradients of TRADES are relatively stable thanks to its adversarial loss. Moreover, by considering models trained on random labels, our generalization analysis indicates that several recently suggested complexity measures are inadequate to explain robust generalization, which is complementary to the findings in ST \citep{neyshabur2017exploring}. Accordingly, an appropriate explanation of robust generalization remains largely under-addressed Lastly, but most importantly, we identify a significant drawback of memorization in AT that it could result in \emph{robust overfitting} \citep{rice2020overfitting}. We argue that the cause of robust overfitting lies in the memorization of one-hot labels in the typical AT methods. The one-hot labels can be inappropriate or even \emph{noisy} for some adversarial examples because some data naturally lies close to the decision boundary, and the corresponding adversarial examples should be assigned low predictive confidence \citep{stutz2020confidence,cheng2020cat}. To solve this problem, we propose a new mitigation algorithm that impedes over-confident predictions by regularization for avoiding the excessive memorization of adversarial examples with possibly noisy labels. Experiments validate that our method can eliminate robust overfitting to a large extent across multiple datasets, network architectures, threat models, and AT methods, achieving better robustness under a variety of adversarial attacks than the baselines. \vspace{-1ex} \section{Background} \vspace{-1ex} \subsection{Adversarial training}\label{sec:2-1} \vspace{-0.7ex} Let $\mathcal{D}=\{(\vect{x}_i,y_i)\}_{i=1}^n$ denote a training dataset with $n$ samples, where $\vect{x}_i \in \mathbb{R}^d$ is a natural example and $y_i\in\{1,...,C\}$ is its true label often encoded as an one-hot vector $\mathbf{1}_{y_i}$ with totally $C$ classes. Adversarial training (AT) can be formulated as a robust optimization problem \citep{madry2017towards}: \begin{equation} \label{eq:at} \min_{\vect{\theta}}\sum_{i=1}^{n} \max_{\vect{x}_i'\in\mathcal{S}(\vect{x}_i)}\mathcal{L}(f_{\vect{\theta}}(\vect{x}_i'), y_i), \end{equation} where $f_{\vect{\theta}}$ is a DNN classifier with parameters $\vect{\theta}$ that predicts probabilities over all classes, $\mathcal{L}$ is the classification loss (i.e., the cross-entropy loss as $\mathcal{L}(f_{\vect{\theta}}(\vect{x}), y)=-\mathbf{1}_{y}^{\top}\log f_{\vect{\theta}}(\vect{x})$), and $\mathcal{S}(\vect{x}) = \{{\vect{x}'}: \|\vect{x}'-\vect{x}\|_p\leq\epsilon\}$ is an adversarial region centered at $\vect{x}$ with radius $\epsilon>0$ under the $\ell_p$-norm threat models (e.g., $\ell_2$ and $\ell_\infty$ norms that we consider). The robust optimization problem~(\ref{eq:at}) is solved by using adversarial attacks to approximate the inner maximization and updating the model parameters $\vect{\theta}$ via gradient descent. A typical method uses projected gradient descent (PGD) \citep{madry2017towards} for the inner problem, which starts at a randomly initialized point in $\mathcal{S}(\vect{x}_i)$ and iteratively updates the adversarial example under the $\ell_\infty$-norm threat model by \begin{equation} \vect{x}_i'=\Pi_{\mathcal{S}(\vect{x}_i)}\big(\vect{x}_i' + \alpha\cdot\mathrm{sign}(\nabla_{\vect{x}}\mathcal{L}(f_{\vect{\theta}}(\vect{x}_i'),y_i))\big),\label{eq:pgd} \end{equation} where $\Pi(\cdot)$ is the projection operator and $\alpha$ is the step size. Besides PGD-AT, another typical AT method is TRADES \citep{zhang2019theoretically}, which balances the trade-off between robustness and natural accuracy by minimizing a different adversarial loss \begin{equation \min_{\vect{\theta}}\sum_{i=1}^{n}\left\{ \mathcal{L}(f_{\vect{\theta}}(\vect{x}_i), y_i)+ \beta\cdot\max_{\vect{x}_i'\in\mathcal{S}(\vect{x}_i)}\mathcal{D}(f_{\vect{\theta}}(\vect{x}_i)\Vert f_{\vect{\theta}}(\vect{x}_i'))\right\}, \label{eq:trades} \end{equation} where $\mathcal{L}$ is the clean cross-entropy loss on the natural example, $\mathcal{D}$ is the Kullback–Leibler divergence, and $\beta$ is a balancing parameter. The inner maximization of TRADES is also solved by PGD. Recent progress of AT includes designing new adversarial losses \citep{mao2019metric,qin2019adversarial,pang2019rethinking,wang2020improving,dong2020adversarial} and network architecture \citep{xie2019feature}, training acceleration \citep{shafahi2019adversarial,zhang2019you,wong2020fast}, and exploiting more training data \citep{hendrycks2019using,alayrac2019labels,carmon2019unlabeled,zhai2019adversarially}. Recent works highlight the training tricks in AT \citep{gowal2020uncovering,pang2020bag}. \vspace{-0.5ex} \subsection{Related work on DNN memorization} \vspace{-0.5ex} It has been observed that DNNs can easily memorize training data with random labels \citep{zhang2017understanding}, which requires ``rethinking'' of conventional techniques (e.g., VC dimension) to explain generalization. \citet{arpit2017closer} identify qualitative differences between learning on true and random labels. Further works attempt to examine what and why DNNs memorize \citep{feldman2020does,feldman2020neural,maennel2020neural}. Motivated by the memorization phenomenon in deep learning, convergence of training has been analyzed in the over-parameterized setting \citep{allen2019convergence, du2019gradient,zou2020gradient}, while generalization has been studied with numerous theoretical and empirical complexity measures \citep{neyshabur2015norm,neyshabur2017exploring,bartlett2017spectrally,novak2018sensitivity,arora2018stronger,cao2019generalization,jiang2019fantastic,chen2020much}. In contrast, the memorization behavior in AT has been less explored. The previous works demonstrate that DNNs can fit training data against an adversary \citep{madry2017towards,schmidt2018adversarially,rice2020overfitting}, e.g., achieving nearly $100\%$ robust training accuracy against a PGD adversary, but this behavior is not explored when trained on random labels. This paper is dedicated to investigating the memorization in AT under the extreme condition with random labels, while drawing connections to capacity, convergence, generalization, and robust overfitting, with the overarching goal of better understanding the AT working mechanism. \vspace{-1ex} \section{Memorization in AT and implications}\label{sec:3} \vspace{-0.5ex} In this section, we first explore the memorization behavior in AT through an empirical study. Our analysis raises new questions about the convergence and generalization of AT, many of which cannot be answered by existing works. Thereafter, we provide further analytical studies on the convergence and generalization of AT by considering models trained on random labels particularly. \vspace{-0.5ex} \subsection{AT with random labels}\label{sec:3.1} \vspace{-0.5ex} We explore the memorization behavior of PGD-AT \citep{madry2017towards} and TRADES \citep{zhang2019theoretically} as two studying cases. The experiments are conducted on CIFAR-10 \citep{krizhevsky2009learning} with a Wide ResNet model \citep{zagoruyko2016wide} of depth 28 and widen factor 10 (WRN-28-10). Similar to \cite{zhang2017understanding}, we train a network on the original dataset with true labels and on a copy of the dataset in which the true labels are corrupted by random ones. For training and robustness evaluation, a 10-step $\ell_\infty$ PGD adversary with $\epsilon=8/255$ and $\alpha=2/255$ is adopted. For TRADES, the PGD adversary maximizes the KL divergence during training, while maximizes the cross-entropy loss for robustness evaluation, as common practice \citep{zhang2019theoretically}. We set $\beta=6.0$. In the sequel, we denote accuracy of a classifier against the 10-step PGD adversary as ``\textbf{robust accuracy}'', and accuracy on natural examples as ``\textbf{natural accuracy}''. \begin{figure}[t] \vspace{-2.5ex} \centering \begin{subfigure}[b]{0.30\linewidth} \centering \includegraphics[width=\textwidth]{figures/plot-pgd.pdf} \vspace{-3ex}\caption{PGD-AT} \label{fig:1a} \end{subfigure}\hspace{1.5ex} \begin{subfigure}[b]{0.30\linewidth} \centering \includegraphics[width=\textwidth]{figures/plot-trades.pdf} \vspace{-3ex}\caption{TRADES} \label{fig:1b} \end{subfigure}\hspace{1.5ex} \begin{subfigure}[b]{0.30\linewidth} \centering \includegraphics[width=\textwidth]{figures/plot-gap.pdf} \vspace{-3ex}\caption{Generalization gap growth} \label{fig:1c} \end{subfigure}\vspace{-1.2ex} \caption{(a) and (b) show the natural and robust training accuracies of PGD-AT and TRADES, respectively, when trained on true or random labels. (c) shows the generalization gap under varying levels of label noise.}\vspace{-2.5ex} \label{fig:fitting} \end{figure} Fig.~\ref{fig:1a} and Fig.~\ref{fig:1b} show the learning curves of PGD-AT and TRADES without explicit regularizations. Both methods achieve almost $100\%$ natural and robust training accuracies when trained on true labels. When the labels are random, we observe the totally different behaviors between PGD-AT and TRADES---PGD-AT fails to converge while TRADES still reaches nearly $100\%$ training accuracies. This phenomenon is somewhat striking because PGD-AT and TRADES perform similarly on true labels \citep{rice2020overfitting}. We find that the different memorization behaviors between PGD-AT and TRADES when trained on random labels can commonly be observed across a variety of datasets, model architectures, and threat models (shown in Appendix \ref{app:a1}), indicating that it is a general phenomenon of memorization in the two AT methods. Therefore, our finding is: \emph{DNNs have sufficient capacity to memorize adversarial examples of training data with completely random labels, but the convergence depends on the AT algorithms.} \textbf{Partially corrupted labels.} We then inspect the behavior of AT under varying levels of label noise from $0\%$ (true labels) to $100\%$ (completely random labels). The generalization gap (i.e., difference between training and test accuracies) presented in Fig.~\ref{fig:1c} grows steadily as we increase the noise rate before the network fails to converge. The learning curves are provided in Appendix \ref{app:a1}. \textbf{Explicit regularizations.} We study the role of common regularizers in AT memorization, including data augmentation, weight decay, and dropout \citep{srivastava2014dropout}. We train TRADES on true and random labels with several combinations of regularizers. We observe the explicit regularizers do not significantly affect the model’s ability to memorize adversarial examples, similar to the finding in ST \citep{zhang2017understanding,arpit2017closer}. The detailed results are provided in Appendix \ref{app:a1}. \vspace{-0.5ex} \subsection{Convergence analysis of AT with random labels}\label{sec:3-2} \vspace{-0.5ex} Since we have observed a counter-intuitive fact that PGD-AT and TRADES exhibit different convergence properties with random labels, it is necessary to perform a convergence analysis to understand this phenomenon. Note that our finding can hardly be explained by previous works \citep{gao2019convergence,wang2019convergence,zhang2020over}. We first study the effects of different training settings on PGD-AT with random labels. We conduct experiments to analyze each training factor individually, including network architecture, attack steps, optimizer, and perturbation budget. We find that tuning the training settings cannot make PGD-AT converge with random labels (Appendix \ref{app:a2} details the results). Based on the analysis, we think that the convergence issue of PGD-AT could be a result of the adversarial loss function in Eq.~(\ref{eq:at}) rather than other training configurations. Specifically, TRADES in Eq.~(\ref{eq:trades}) minimizes a clean cross-entropy (CE) loss on natural examples, making DNNs memorize natural examples with random labels before fitting adversarial examples. As seen in Fig.~\ref{fig:1b}, at the very early stage of TRADES training (the first 25 epochs), the natural accuracy starts to increase while the robust accuracy does not. However, PGD-AT in Eq.~(\ref{eq:at}) directly minimizes the CE loss on adversarial samples with random labels, which can introduce unstable gradients with large variance, making it fail to converge. To corroborate the above argument, we analyze the gradient magnitude and stability below. \textbf{Gradient magnitude.} First, we calculate the average gradient norm of the adversarial loss in Eq.~(\ref{eq:at}) w.r.t. model parameters over each training sample for PGD-AT, and similarly calculate the average gradient norm of the clean CE loss (the first term) and the KL loss (the second term) in Eq.~(\ref{eq:trades}) w.r.t. parameters for TRADES to analyze their effects, respectively. We present the gradient norm along with training in Fig.~\ref{fig:2b}. We can see that at the initial training epochs, the gradient norm of the KL loss in TRADES is much smaller than that of the CE loss, which indicates that the CE loss dominates TRADES training initially. With the training progressing, the KL loss has a larger gradient norm, making the network memorize adversarial examples. However, it is still unclear why PGD-AT does not rely on a similar learning tactic for convergence. To make a direct comparison with TRADES, we rewrite the adversarial loss of PGD-AT in Eq.~(\ref{eq:at}) as \begin{equation*} \max_{\vect{x}_i'\in\mathcal{S}(\vect{x}_i)}\mathcal{L}(f_{\vect{\theta}}(\vect{x}_i'), y_i) = \mathcal{L}(f_{\vect{\theta}}(\vect{x}_i), y_i) + \mathcal{R}(\vect{x}_i, y_i, \vect{\theta}), \end{equation*} where $\mathcal{R}(\vect{x}_i, y_i, \vect{\theta})$ denotes the difference between the CE loss on adversarial example $\vect{x}_i'$ and that on natural example $\vect{x}_i$. Hence we can separately calculate the gradient norm of $\mathcal{L}(f_{\vect{\theta}}(\vect{x}_i), y_i)$ and $\mathcal{R}(\vect{x}_i, y_i, \vect{\theta})$ w.r.t. parameters $\vect{\theta}$ to find out the effect of $\mathcal{R}(\vect{x}_i, y_i, \vect{\theta})$ on training. Specifically, we measure the relative gradient magnitude, i.e., in PGD-AT we calculate the ratio of the gradient norm $\frac{\|\nabla_{\vect{\theta}}\mathcal{R}(\vect{x}_i, y_i, \vect{\theta})\|_2}{\|\nabla_{\vect{\theta}}\mathcal{L}(f_{\vect{\theta}}(\vect{x}_i), y_i)\|_2}$; while in TRADES, we similarly calculate the ratio of the gradient norm of the KL loss to that of the CE loss. Fig.~\ref{fig:2a} illustrates the ratio of PGD-AT and TRADES during the first 1000 training iterations. The ratio of PGD-AT is consistently higher than that of TRADES, meaning that $\mathcal{R}(\vect{x}_i, y_i, \vect{\theta})$ has a non-negligible impact on training. \begin{figure}[t] \vspace{-2.5ex} \centering \begin{minipage}{.494\textwidth} \begin{subfigure}[b]{0.49\columnwidth} \centering \includegraphics[width=\textwidth]{figures/pgd_g1.pdf} \vspace{-3ex}\caption{} \label{fig:2b} \end{subfigure}\hspace{0.2ex} \begin{subfigure}[b]{0.48\columnwidth} \centering \includegraphics[width=\textwidth]{figures/plot-norm.pdf} \vspace{-3ex}\caption{} \label{fig:2a} \end{subfigure} \vspace{-1ex} \caption{(a): Gradient norm of PGD-AT and TRADES along the training process. (b): The ratio of the gradient norm of PGD-AT and TRADES during the first 1000 training iterations.} \label{fig:norm} \end{minipage}\hspace{0.5ex} \begin{minipage}{.494\textwidth} \begin{subfigure}[b]{0.49\columnwidth} \centering \includegraphics[width=\textwidth]{figures/plot-stability.pdf} \vspace{-3ex}\caption{} \label{fig:3a} \end{subfigure}\hspace{0.2ex} \begin{subfigure}[b]{0.49\columnwidth} \centering \includegraphics[width=\textwidth]{figures/pgd_g2.pdf} \vspace{-3.4ex}\caption{} \label{fig:3b} \end{subfigure} \vspace{-3.7ex} \caption{(a): The $\ell_2$ distance between the gradients at $\vect{\theta}$ and $\vect{\theta}+\lambda\vect{d}$ of different losses, where $\vect{\theta}$ are initialized, $\lambda\in[-0.05,0.05]$. (b): The cosine similarity between the gradients in each two successive epochs.} \end{minipage} \vspace{-2.5ex} \end{figure} \textbf{Gradient stability.} Then, we analyze the gradient stability to explain why PGD-AT cannot converge. We denote the adversarial loss of PGD-AT as $\mathcal{J}(\vect{x}, y, \vect{\theta}) = \max_{\vect{x}'\in\mathcal{S}(\vect{x})}\mathcal{L}(f_{\vect{\theta}}(\vect{x}'), y)$ with the subscript $i$ omitted for notation simplicity. We have a theorem on gradient stability. \begin{theorem}\label{thm:1} Suppose the gradient of the clean cross-entropy loss is locally Lipschitz continuous as \begin{equation}\label{eq:ass} \|\nabla_{\vect{\theta}}\mathcal{L}(f_{\vect{\theta}}(\vect{x}'), y) - \nabla_{\vect{\theta}}\mathcal{L}(f_{\vect{\theta}}(\vect{x}), y)\|_2 \leq K\|\vect{x}'-\vect{x}\|_p, \end{equation} for any $\vect{x}\in\mathbb{R}^d$, $\vect{x}'\in \mathcal{S}(\vect{x})$, and any $\vect{\theta}$, where $K$ is the Lipschitz constant. Then we have \begin{equation}\label{eq:smooth} \|\nabla_{\vect{\theta}}\mathcal{J}(\vect{x}, y, \vect{\theta}_1) - \nabla_{\vect{\theta}}\mathcal{J}(\vect{x}, y, \vect{\theta}_2) \|_2 \leq \|\nabla_{\vect{\theta}}\mathcal{L}(f_{\vect{\theta}_1}(\vect{x}), y) - \nabla_{\vect{\theta}}\mathcal{L}(f_{\vect{\theta}_2}(\vect{x}), y)\|_2 + 2\epsilon K. \end{equation} \end{theorem} We provide the proof in Appendix \ref{app:b}, where we show the upper bound in Eq.~(\ref{eq:smooth}) is tight. Theorem~\ref{thm:1} indicates that the gradient of the adversarial loss $\mathcal{J}(\vect{x}, y, \vect{\theta})$ of PGD-AT will change more dramatically than that of the clean CE loss $\mathcal{L}(f_{\vect{\theta}}(\vect{x}), y)$. When $\vect{\theta}_1$ and $\vect{\theta}_2$ are close, the difference between the gradients of $\mathcal{L}$ at $\vect{\theta}_1$ and $\vect{\theta}_2$ is close to $0$ due to the semi-smoothness of over-parameterized DNNs \citep{allen2019convergence}, but that of $\mathcal{J}$ is relatively large due to $2\epsilon K$ in Eq.~(\ref{eq:smooth}). To validate this, we visualize the change of gradient when moving the parameters $\vect{\theta}$ along a random direction $\vect{d}$ with magnitude $\lambda$. In particular, we set $\vect{\theta}$ as initialization, $\vect{d}$ is sampled from a Gaussian distribution and normalized filter-wise \citep{li2018visualizing}. For PGD-AT and TRADES, we craft adversarial examples on-the-fly for the model with $\vect{\theta}+\lambda\vect{d}$ and measure the change of gradient by the $\ell_2$ distance to gradient at $\vect{\theta}$ averaged over all data samples. The curves on gradient change of PGD-AT, TRADES, and the clean CE loss are shown in Fig.~\ref{fig:3a}. In a small neighborhood of $\vect{\theta}$ (i.e., small $\lambda$), the gradient of PGD-AT changes abruptly while the gradients of TRADES and the clean CE loss are more continuous. The gradient instability leads to a lower cosine similarity between the gradient directions w.r.t. the same data in each two successive training epochs of PGD-AT, as illustrated in Fig.~\ref{fig:3b}. Therefore, the training of PGD-AT would be rather unstable that the gradient exhibits large variance, making it fail to converge. \begin{wrapfigure}{r}{0.25\linewidth} \vspace{-6ex} \centering \includegraphics[width=0.99\linewidth,height=15ex]{add_fig/plot-adaptive.pdf}\vspace{-2ex} \caption{AT by Eq.~(\ref{eq:6})}.\vspace{-5ex} \label{fig:refine} \end{wrapfigure} \textbf{Clean CE loss helps PGD-AT converge.} To further verify our argument, we add the clean CE loss into the PGD-AT objective to resemble the learning of TRADES with random labels, as \begin{equation}\label{eq:6} \min_{\vect{\theta}}\sum_{i=1}^{n}\left\{ (1-\gamma)\cdot\mathcal{L}(f_{\vect{\theta}}(\vect{x}_i), y_i) + \gamma\cdot \max_{\vect{x}_i'\in\mathcal{S}(\vect{x}_i)}\mathcal{L}(f_{\vect{\theta}}(\vect{x}_i'), y_i)\right\}, \end{equation} where $\gamma$ is gradually increased from $0$ to $1$. By using Eq.~(\ref{eq:6}), the gradient would be stabler at the initial stage and training on random labels can successfully converge, as shown Fig.~\ref{fig:refine}. \textbf{In summary}, our convergence analysis identifies the gradient instability issue of PGD-AT, provides new insights on the differences between PGD-AT and TRADES, and partially explain the failures of AT under other realistic settings beyond the scope of this section as detailed in Appendix \ref{app:a2}. \iffalse \begin{table*}[t] \vspace{-2ex} \caption{The training accuracy, test accuracy, and generalization gap (\%) of TRADES when trained on true or random labels, with and without explicit regularizations, including data augmentation (random crop and flip), weight decay ($0.0002$), and dropout ($0.2$). \centering \small \begin{tabular}{c|c|c|c|cc|cc|cc} \hline \multirow{2}{*}{Labels} & Data & Weight & \multirow{2}{*}{Dropout} & \multicolumn{2}{c|}{Training Accuracy} & \multicolumn{2}{c|}{Test Accuracy} & \multicolumn{2}{c}{Generalization Gap} \\ & Augmentation & Decay & & Natural & Robust & Natural & Robust & Natural & Robust \\ \hline true & \xmark & \xmark & \xmark & 99.73 & 99.65 & 77.53 & 37.47 & 22.20 & 62.18 \\ true & \cmark & \xmark & \xmark & 99.57 & 97.03 & 82.91 & 45.37 & 16.93 & 51.66 \\ true & \xmark & \cmark & \xmark & 99.59 & 99.53 & 77.31 & 38.94 & 22.28 & 60.59 \\ true & \xmark & \xmark & \cmark & 99.65 & 99.40 & 79.96 & 39.86 & 19.69 & 59.54 \\ true & \cmark & \cmark & \xmark & 99.50 & 97.28 & 84.26 & 49.16 & 15.24 & 48.12 \\ true & \xmark & \cmark & \cmark & 99.41 & 99.20 & 80.28 & 41.64 & 19.13 & 57.56 \\ \hline random & \xmark & \xmark & \xmark & 99.80 & 99.55 & 9.79 & 0.15 & 90.01 & 99.40 \\ random & \cmark & \xmark & \xmark & 99.36 & 86.10 & 9.71 & 0.24 & 89.65 & 85.86 \\ random & \xmark & \cmark & \xmark & 99.84 & 99.53 & 10.13 & 0.23 & 89.71 & 99.30 \\ random & \xmark & \xmark & \cmark & 99.15 & 92.23 & 9.04 & 0.17 & 90.11 & 92.06 \\ random & \cmark & \cmark & \xmark & 99.25 & 69.62 & 9.67 & 0.24 & 89.58 & 69.38 \\ random & \xmark & \cmark & \cmark & 99.38 & 81.57 & 9.54 & 0.19 & 89.84 & 81.38 \\ \hline \end{tabular} \vspace{-1ex} \label{table:reg} \end{table*} \begin{figure}[t] \centering \includegraphics[width=0.95\linewidth]{figures/plot-acc.pdf}\vspace{-2.5ex} \caption{The robust training accuracy, test accuracy, and generalization gap of TRADES when trained on true or random labels, with and without explicit regularizations, including data augmentation (\emph{DA}: random crop and flip), weight decay (\emph{WD}: $0.0002$), and \emph{dropout} ($0.2$). The exact numbers of the results are provided in Table~A.1 in Appendix A.4.} \label{fig:reg}\vspace{-0.6ex} \end{figure} \begin{figure}[t] \centering \includegraphics[width=0.95\linewidth]{figures/trades_full.pdf}\vspace{-2.5ex} \caption{Accuracy curves of TRADES under different noise rates on CIFAR-10.}\vspace{-2ex} \label{fig:full} \end{figure} \fi \vspace{-0.5ex} \subsection{Generalization analysis of AT with random labels \vspace{-0.5ex} As our study demonstrates DNNs' ability to memorize adversarial examples with random labels, we raise the question of whether DNNs rely on a similar memorization tactic on true labels and how to explain/ensure robust generalization. Although many efforts have been devoted to studying robust generalization of AT theoretically or empirically \citep{yin2018rademacher,schmidt2018adversarially,bubeck2019adversarial,tu2019theoretical,wu2020adversarial}, they do not take the models trained on random labels into consideration. As it is easy to show that the explicit regularizations are not the adequate explanation of generalization in ST \citep{zhang2017understanding,arpit2017closer} and AT (see Appendix \ref{app:a3}), people resort to complexity measures of a model to explain generalization (i.e., a lower complexity should imply a smaller generalization gap). Here we show how the recently proposed complexity measures fail to explain robust generalization when comparing models trained on true and random labels. \begin{figure}[t] \vspace{-3ex} \centering \includegraphics[width=0.99\columnwidth]{figures/plot-measure.pdf}\vspace{-1.5ex} \caption{The results on four complexity measures of the adversarially trained models w.r.t. robust generalization gap. The training settings of these models are provided in Appendix \ref{app:a3}.}\vspace{-3ex} \label{fig:measure} \end{figure} We consider several norm-based and sharpness/flatness-based measures. We denote the parameters of a network by $\vect{\theta} := \{W_i\}_{i=1}^m$. The norm-based measures include spectral norm $\frac{1}{\gamma_{\text{margin}}}\prod_{i=1}^m\|W_i\|_2$ and $\ell_1$ norm $\frac{1}{\gamma_{\text{margin}}}\sum_{i=1}^m\|W_i\|_1$ of model parameters, where $\gamma_{\text{margin}}$ is a margin on model output to make them scale-insensitive \citep{neyshabur2017exploring}. The spectral norm appears in the theoretical robust generalization bounds \citep{yin2018rademacher,tu2019theoretical} and is related to the Lipschitz constant of neural networks \citep{cisse2017parseval}. The $\ell_1$ norm is adopted to reduce the robust generalization gap \citep{yin2018rademacher}. The sharpness/flatness-based measures include the curvature of input loss landscape \citep{moosavi2019robustness} as the dominant eigenvalue of the Hessian matrix, as well as the flatness of weight loss landscape \citep{wu2020adversarial} related to the change of adversarial loss when moving the weights along a random direction. Fig.~\ref{fig:measure} plots the four complexity measures w.r.t. robust generalization gap of several models trained with various combinations of regularizations on true or random labels. The results show that the first three measures can hardly ensure robust generalization, that lower complexity does not necessarily imply smaller robust generalization gap, e.g., the models trained on random labels can even lead to lower complexity than those trained on true labels. Among them, the flatness of weight loss landscape \citep{wu2020adversarial} is more reliable. \textbf{In summary}, the generalization analysis indicates that the previous approaches, especially various complexity measures, cannot adequately explain and ensure the robust generalization performance in AT. Our finding of robust generalization in AT is complementary to that of standard generalization in ST \citep{zhang2017understanding,neyshabur2017exploring,jiang2019fantastic}. Accordingly, robust generalization of adversarially trained models remains an open problem for future research. \vspace{-1.5ex} \section{Robust overfitting analysis}\label{sec:4} \vspace{-0.6ex} \citet{rice2020overfitting} have identified robust overfitting as a dominant phenomenon in AT, i.e., shortly after the first learning rate decay, further training will continue to decrease the robust test accuracy. They further show that several remedies for overfitting, including explicit $\ell_1$ and $\ell_2$ regularizations, data augmentation, etc., cannot gain improvements upon early stopping. Although robust overfitting has been thoroughly investigated, there still lacks an explanation of why it occurs. In this section, we draw a connection between memorization and robust overfitting in AT by showing that robust overfitting is caused by excessive memorization of one-hot labels in the typical AT methods. Motivated by the analysis, we then propose an effective strategy to eliminate robust overfitting. \vspace{-1ex} \subsection{Explaining robust overfitting} \vspace{-0.5ex} The typical AT approaches (e.g., PGD-AT, TRADES) commonly adopt one-hot labels as the targets for training, as introduced in Sec.~\ref{sec:2-1}. The one-hot labels could be inappropriate for some adversarial examples because it is difficult for a network to assign high-confident one-hot labels for all perturbed samples within the perturbation budget $\epsilon$ \citep{stutz2020confidence,cheng2020cat}. Intuitively, some examples may naturally lie close to the decision boundary and should be assigned lower predictive confidence for the worst-case adversarial examples. It indicates that one-hot labels of some training data may be \emph{noisy} in AT\footnote{Note that we argue the one-hot labels are noisy when used in AT, but do not argue the ground-truth labels of the dataset are noisy, which is different from a previous work \citep{sanyal2021how}.}. After a certain training epoch, the model memorizes these ``hard'' training examples with possibly noisy labels, leading to the reduction of test robustness, as shown in Fig.~\ref{fig:6a}. Thus, we hypothesize the cause of robust overfitting lies in the \emph{memorization of one-hot labels}. Our hypothesis is well supported by two pieces of evidence. First, we find that when the perturbation budget $\epsilon$ is small, robust overfitting does not occur, as shown in Fig.~\ref{fig:6b}. This observation implies that the one-hot labels are more appropriate as the targets for adversarial examples within a smaller neighborhood while become noisier under a larger perturbation budget and lead to overfitting. Second, we validate that the ``hard'' training examples with higher adversarial loss values are consistent across different models. We first train two independent networks (using the same architecture and different random seeds) by PGD-AT and calculate the adversarial loss for each training sample. We show the adversarial losses on 500 samples sorted by the loss of the first model in Fig.~\ref{fig:6c}. It can be seen that the samples with lower adversarial losses of the first model also have relatively lower losses of the second one and vice versa. We further quantitatively measure the consistency of the adversarial losses of all training samples between the two models using the Kendall’s rank coefficient \citep{kendall1938new}, which is $0.85$ in this case. A similar result can be observed for two different model architectures (see Appendix \ref{app:c1}). The results verify that the ``hard'' training examples with possibly noisy labels are intrinsic of a dataset, supporting our hypothesis on why robust overfitting occurs. \begin{figure}[t] \vspace{-2.5ex} \centering \begin{subfigure}[b]{0.30\linewidth} \centering \includegraphics[width=\textwidth]{figures/pgd_test_noise0.0.pdf} \vspace{-3ex}\caption{} \label{fig:6a} \end{subfigure}\hspace{1.5ex} \begin{subfigure}[b]{0.30\linewidth} \centering \includegraphics[width=\textwidth]{figures/plot-epsilon} \vspace{-3ex}\caption{} \label{fig:6b} \end{subfigure}\hspace{1.5ex} \begin{subfigure}[b]{0.30\linewidth} \centering \includegraphics[width=\textwidth]{figures/plot-loss.pdf} \vspace{-3ex}\caption{} \label{fig:6c} \end{subfigure}\vspace{-1.3ex} \caption{(a): The accuracy curves of PGD-AT with true labels to reproduce robust overfitting. (b): The robust test accuracy of PGD-AT under various perturbation budgets $\epsilon$. (c): The adversarial loss of two independently trained networks by PGD-AT on 500 samples sorted by the loss of the first model.}\vspace{-2.5ex} \end{figure} \vspace{-0.5ex} \subsection{Mitigating robust overfitting} \vspace{-0.5ex} Based on the above analysis, we resort to the methods that are less prone to overfit noisy labels for mitigating robust overfitting in AT. Although learning with noisy labels has been broadly studied in ST \citep{natarajan2013learning,patrini2017making,jiang2017mentornet,han2018co,zhang2018generalized}, we find that most of these approaches are not suitable for AT. For example, a typical line of methods filter out noisy samples and train the models on the identified clean samples \citep{jiang2017mentornet,han2018co,ren2018learning}. However, they will neglect a portion of training data with noisy labels, which can lead to inferior results for AT due to the reduction of training data \citep{schmidt2018adversarially}. Table~\ref{table:res2} shows the results to validate this. To address this problem, we propose to regularize the predictions of adversarial examples from being over-confident by integrating the \textbf{temporal ensembling (TE)} approach \citep{laine2016temporal} into the AT frameworks. TE maintains an ensemble prediction of each data and penalizes the difference between the current prediction and the ensemble prediction, which is effective for semi-supervised learning and learning with noisy labels \citep{laine2016temporal}. We think that TE is suitable for AT since it enables to leverage all training samples and hinders the network from excessive memorization of one-hot labels with a regularization term. Specifically, we denote the ensemble prediction of a training sample $\vect{x}_i$ as $\vect{p}_i$, which is updated in each training epoch as $\vect{p}_i\leftarrow \eta\cdot \vect{p}_i + (1-\eta)\cdot f_{\vect{\theta}}(\vect{x}_i)$, where $\eta$ is the momentum term. The training objective of PGD-AT with TE can be expressed as \begin{equation} \label{eq:at-te} \min_{\vect{\theta}}\sum_{i=1}^{n} \max_{\vect{x}_i'\in\mathcal{S}(\vect{x}_i)}\left\{\mathcal{L}(f_{\vect{\theta}}(\vect{x}_i'), y_i) + w\cdot \|f_{\vect{\theta}}(\vect{x}_i') - \hat{\vect{p}}_i\|_2^2\right\}, \end{equation} where $\hat{\vect{p}}_i$ is the normalization of $\vect{p}_i$ as a probability vector and $w$ is a balancing weight. TE can be similarly integrated with TRADES with the same regularization term. The network would learn to fit relatively easy samples with one-hot labels in the initial training stage, as shown in Fig.~\ref{fig:6a}. After the learning rate decays, the network can keep assigning low confidence for hard samples with the regularization term in Eq.~(\ref{eq:at-te}) and avoid fitting one-hot labels. Therefore, the proposed algorithm enables to learn under label noise in AT and alleviates the robust overfitting problem. \vspace{-1ex} \section{Empirical evaluation on mitigating robust overfitting} \label{sec:5}\vspace{-0.5ex} In this section, we provide the experimental results on CIFAR-10, CIFAR-100 \citep{krizhevsky2009learning}, and SVHN \citep{netzer2011reading} datasets to validate the effectiveness of our proposed method. Code is available at \url{https://github.com/dongyp13/memorization-AT}. \begin{table}[t] \vspace{-2.5ex} \caption{Test accuracy (\%) of several methods on CIFAR-10, CIFAR-100, and SVHN under the $\ell_\infty$ norm with $\epsilon=8/255$ based on the ResNet-18 architecture. We choose the best checkpoint according to the highest robust accuracy on the test set under PGD-10.}\vspace{-1.5ex} \begin{subtable}{\linewidth} \centering \small \setlength{\tabcolsep}{1.8pt} \begin{tabular}{l|ccc|ccc|ccc|ccc|ccc} \toprule \multirow{2}{*}{Method} & \multicolumn{3}{c|}{Natural Accuracy} & \multicolumn{3}{c|}{PGD-10} & \multicolumn{3}{c|}{PGD-1000} & \multicolumn{3}{c|}{C\&W-1000} & \multicolumn{3}{c}{AutoAttack} \\ & Best & Final & Diff & Best & Final & Diff & Best & Final & Diff & Best & Final & Diff & Best & Final & Diff \\ \midrule PGD-AT & \bf83.75 & \bf84.82 & -1.07 & 52.64 & 44.92 & 7.72 & 51.22 & 42.74 & 8.48 & 50.11 & 43.63 & 7.48 & 47.74 & 41.84 & 5.90 \\ PGD-AT\textbf{+TE} & 82.35 & 82.79 & \bf-0.44 & \bf55.79 & \bf54.83 & \bf0.96 & \bf54.65 & \bf53.30 & \bf1.35 & \bf52.30 & \bf51.73 & \bf0.57 & \bf50.59 & \bf49.62 & \bf0.97 \\ \midrule TRADES & 81.19 & 82.48 & -1.29 & 53.32 & 50.25 & 3.07 & 52.44 & 48.67 & 3.77 & 49.88 & 48.14 & 1.74 & 49.03 & 46.80 & 2.23 \\ TRADES\textbf{+TE} & \bf83.86 & \bf83.97 & \bf-0.11 & \bf55.15 & \bf54.42 & \bf0.73 & \bf53.74 & \bf53.03 & \bf0.71 & \bf50.77 & \bf50.63 & \bf0.14 & \bf49.77 & \bf49.20 & \bf0.57 \\ \bottomrule \end{tabular \caption{The evaluation results on \textbf{CIFAR-10}.}\vspace{-0.5ex} \end{subtable} \begin{subtable}{\linewidth} \centering \small \setlength{\tabcolsep}{1.8pt} \begin{tabular}{l|ccc|ccc|ccc|ccc|ccc} \toprule \multirow{2}{*}{Method} & \multicolumn{3}{c|}{Natural Accuracy} & \multicolumn{3}{c|}{PGD-10} & \multicolumn{3}{c|}{PGD-1000} & \multicolumn{3}{c|}{C\&W-1000} & \multicolumn{3}{c}{AutoAttack} \\ & Best & Final & Diff & Best & Final & Diff & Best & Final & Diff & Best & Final & Diff & Best & Final & Diff \\ \midrule PGD-AT & \bf57.54 & \bf57.51 & \bf0.03 & 29.40 & 21.75 & 7.65 & 28.54 & 20.63 & 7.91 & 27.06 & 21.17 & 5.89 & 24.72 & 19.34 & 5.38 \\ PGD-AT\textbf{+TE} & 56.45 & 57.12 & -0.67 & \bf31.74 & \bf30.24 & \bf1.50 & \bf31.27 & \bf29.80 & \bf1.47 & \bf28.27 & \bf27.36 & \bf0.91 & \bf26.30 & \bf25.34 & \bf0.96 \\ \midrule TRADES & 57.98 & 56.32 & 1.66 & 29.93 & 27.70 & 2.23 & 29.51 & 26.93 & 2.58 & 25.46 & 24.42 & 1.04 & 24.61 & 23.40 & 1.21 \\ TRADES\textbf{+TE} & \bf59.35 & \bf58.72 & \bf0.63 & \bf31.09 & \bf30.12 & \bf0.97 & \bf30.54 & \bf29.45 & \bf1.09 & \bf26.61 & \bf25.94 & \bf0.67 & \bf25.27 & \bf24.55 & \bf0.72 \\ \bottomrule \end{tabular \caption{The evaluation results on \textbf{CIFAR-100}.}\vspace{-0.5ex} \end{subtable} \begin{subtable}{\linewidth} \centering \small \setlength{\tabcolsep}{1.8pt} \begin{tabular}{l|ccc|ccc|ccc|ccc|ccc} \toprule \multirow{2}{*}{Method} & \multicolumn{3}{c|}{Natural Accuracy} & \multicolumn{3}{c|}{PGD-10} & \multicolumn{3}{c|}{PGD-1000} & \multicolumn{3}{c|}{C\&W-1000} & \multicolumn{3}{c}{AutoAttack} \\ & Best & Final & Diff & Best & Final & Diff & Best & Final & Diff & Best & Final & Diff & Best & Final & Diff \\ \midrule PGD-AT & 89.00 & 90.55 & -1.55 & 54.51 & 46.97 & 7.54 & 52.22 & 42.85 & 9.37 & 48.66 & 44.13 & 4.53 & 46.61 & 38.24 & 8.37 \\ PGD-AT\textbf{+TE} & \bf90.09 & \bf90.91 & \bf-0.82 & \bf59.74 & \bf59.05 & \bf0.69 & \bf57.71 & \bf56.46 & \bf1.25 & \bf54.55 & \bf53.94 & \bf0.61 & \bf51.44 & \bf50.61 & \bf0.83 \\ \midrule TRADES & \bf90.88 & \bf91.30 & \bf-0.42 & 59.50 & 57.04 & 2.46 & 52.78 & 50.17 & 2.61 & 52.76 & 50.53 & 2.23 & 40.36 & 38.88 & 1.48 \\ TRADES\textbf{+TE} & 89.01 & 88.52 & 0.49 & \bf59.81 & \bf58.49 & \bf1.32 & \bf58.24 & \bf56.66 & \bf1.58 & \bf54.00 & \bf53.24 & \bf0.76 & \bf51.45 & \bf50.16 & \bf1.29 \\ \bottomrule \end{tabular \caption{The evaluation results on \textbf{SVHN}.}\vspace{-5ex} \end{subtable} \label{table:res} \end{table} \textbf{Training details.} We adopt the common setting that the perturbation budget is $\epsilon=8/255$ under the $\ell_\infty$ norm in most experiments. We consider PGD-AT and TRADES as two typical AT baselines and integrate the proposed TE approach into them, respectively. We use the ResNet-18 \citep{he2016deep} model as the classifier in most experiments. In training, we use the 10-step PGD adversary with $\alpha=2/255$. The models are trained via the SGD optimizer with momentum $0.9$, weight decay $0.0005$, and batch size $128$. For CIFAR-10/100, we set the learning rate as $0.1$ initially which is decayed by $0.1$ at $100$ and $150$ epochs with totally $200$ training epochs. For SVHN, the learning rate starts from $0.01$ with a cosine annealing schedule for a total number of $80$ training epochs. In our method, We set $\eta=0.9$ and $w=30$ along a Gaussian ramp-up curve \citep{laine2016temporal}. \textbf{Evaluation results.} We adopt PGD-10, PGD-1000, C\&W-1000 \citep{carlini2017towards}, and AutoAttack \citep{croce2020reliable} for evaluating adversarial robustness rigorously. AutoAttack is a strong attack to evaluate model robustness, which is composed of an ensemble of diverse attacks, including APGD-CE \citep{croce2020reliable}, APGD-DLR \citep{croce2020reliable}, FAB \citep{croce2020minimally}, and Square attack \citep{andriushchenko2020square}. To show the performance of robust overfitting, we report the test accuracy on the best checkpoint that achieves the highest robust test accuracy under PGD-10 and the final checkpoint, as well as the difference between these two checkpoints. The results of PGD-AT, TRADES, and the combinations of them with our proposed approach (denoted as PGD-AT\textbf{+TE} and TRADES\textbf{+TE}) on the CIFAR-10, CIFAR-100, and SVHN datasets are shown in Table~\ref{table:res}. \begin{wrapfigure}{r}{0.6\linewidth} \vspace{-1.5ex} \centering \includegraphics[width=0.99\linewidth]{figures/plot-te.pdf}\vspace{-1ex} \caption{The natural and robust test accuracy curves (under PGD-10) of PGD-AT, TRADES, and their extensions by integrating the proposed TE approach. The models are trained on CIFAR-10 under the $\ell_\infty$ norm with $\epsilon=8/255$ based on the ResNet-18 architecture.}\vspace{-1.5ex} \label{fig:te} \end{wrapfigure} We can observe that the differences between best and final test accuracies of our method are reduced to around $1\%$, while the accuracy gaps of PGD-AT and TRADES are much larger. It indicates that our method largely eliminates robust overfitting. Due to being less affected by robust overfitting, our method achieves higher robust accuracies than the baselines. We also show the learning curves of these methods in Fig.~\ref{fig:te}. We consistently demonstrate the effectiveness of our method on different network architectures (including WRN-34-10 and VGG-16) and threat models (including $\ell_2$ norm), which will be shown in Appendix \ref{app:c2}. \textbf{Discussion and comparison with related works.} Our method is kind of similar to the label smoothing (LS) technique, which is studied in AT \citep{pang2020bag}. Recent works have also introduced the smoothness in training labels and model weights \citep{chen2021robust,huang2020self}, which can alleviate robust overfitting to some extent. The significant difference between our work and them is that we provide a reasonable explanation for robust overfitting---\emph{one-hot labels are noisy for AT}, while previous methods did not give such an explanation and could be viewed as solutions to our identified problem. To empirically compare with these methods, we conduct experiments on CIFAR-10 with the ResNet-18 network. Under the PGD-AT framework, we compare with the baseline PGD-AT, PGD-AT\textbf{+LS}, self-adaptive training (SAT) \citep{huang2020self}, and knowledge distillation with stochastic weight averaging (KD-SWA) \citep{chen2021robust}. We also adopt the \emph{Co-teaching} approach \citep{han2018co} adapted to PGD-AT, which jointly trains two models using the filtered samples given by each other. The results under the adopted attacks are presented in Table~\ref{table:res2}. Although various techniques can alleviate robust overfitting, our method achieves better robustness than the others, validating its effectiveness. For Co-teaching, though robust overfitting is alleviated, the performance is worse than our proposed method due to the reduction of training data. \begin{table}[h] \vspace{-1ex} \caption{Test accuracy (\%) of the proposed method and other methods on CIFAR-10 under the $\ell_\infty$ norm with $\epsilon=8/255$ based on the ResNet-18 architecture.}\vspace{-1.5ex} \centering \small \setlength{\tabcolsep}{1.8pt} \begin{tabular}{l|ccc|ccc|ccc|ccc|ccc} \toprule \multirow{2}{*}{Method} & \multicolumn{3}{c|}{Natural Accuracy} & \multicolumn{3}{c|}{PGD-10} & \multicolumn{3}{c|}{PGD-1000} & \multicolumn{3}{c|}{C\&W-1000} & \multicolumn{3}{c}{AutoAttack} \\ & Best & Final & Diff & Best & Final & Diff & Best & Final & Diff & Best & Final & Diff & Best & Final & Diff \\ \midrule PGD-AT & 83.75 & 84.82 & -1.07 & 52.64 & 44.92 & 7.72 & 51.22 & 42.74 & 8.48 & 50.11 & 43.63 & 7.48 & 47.74 & 41.84 & 5.90 \\ PGD-AT\textbf{+LS} & 82.68 & 85.16 & -2.48 & 53.70 & 48.90 & 4.80 & 52.56 & 46.31 & 6.25 & 50.41 & 46.06 & 4.35 & 49.02 & 44.39 & 4.63 \\ SAT & 82.81 & 81.86 & 0.95 & 53.81 & 53.31 & \bf0.50 & 52.41 & 52.00 & \bf0.41 & 51.99 & 51.71 & \bf0.28 & 50.21 & 49.73 & \bf0.48 \\ KD-SWA & \bf84.84 & \bf85.26 & -0.42 & 54.89 & 53.80 & 1.09 & 53.31 & 52.45 & 0.86 & 51.48 & 50.91 & 0.57 & 50.42 & \bf49.83 & 0.59 \\ Co-teaching & 81.94 & 82.22 & \bf-0.28 & 51.27 & 50.52 & 0.75 & 50.15 & 49.12 & 1.03 & 50.85 & 49.86 & 0.99 & 49.60 & 48.49 & 1.11 \\ PGD-AT\textbf{+TE} & 82.35 & 82.79 & -0.44 & \bf55.79 & \bf54.83 & 0.96 & \bf54.65 & \bf53.30 & 1.35 & \bf52.30 & \bf51.73 & 0.57 & \bf50.59 & 49.62 & 0.97 \\ \bottomrule \end{tabular} \vspace{-2ex} \label{table:res2} \end{table} \vspace{-1ex} \section{Conclusion} \vspace{-1ex} In this paper, we demonstrate the capacity of DNNs to fit adversarial examples with random labels by exploring memorization in adversarial training, which also poses open questions on the convergence and generalization of adversarially trained models. We validate that some AT methods suffer from a gradient instability issue and robust generalization can hardly be explained by complexity measures. We further identify a significant drawback of memorization in AT related to the robust overfitting phenomenon---robust overfitting is caused by memorizing one-hot labels in adversarial training. We propose a new mitigation algorithm to address this issue, with the effectiveness validated extensively. \section*{Acknowledgements} This work was supported by the National Key Research and Development Program of China (2020AAA0106000, 2020AAA0104304, 2020AAA0106302), NSFC Projects (Nos. 61620106010, 62061136001, 61621136008, 62076147, U19B2034, U1811461, U19A2081), Beijing NSF Project (No. JQ19016), Beijing Academy of Artificial Intelligence (BAAI), Tsinghua-Alibaba Joint Research Program, Tsinghua Institute for Guo Qiang, Tsinghua-OPPO Joint Research Center for Future Terminal Technology. \section*{Ethics Statement} The existence of adversarial examples can pose severe security threats to machine learning and deep learning models when they are deployed to real-world applications. The vulnerability to adversarial examples could also lower the confidence of the public on machine learning techniques. Therefore, it is important to develop more robust models. As the most effective method for promoting model robustness, adversarial training (AT) has not been fully investigated. This paper aims to investigate the memorization effect of AT to facilitate a better understanding of its working mechanism. Some findings in this paper can be analyzed more deeply, including theoretical analysis of AT convergence, generalization, etc., which we leave to future work. \section*{Reproducibility Statement} Most of the experiments are easily reproducible. We provide the code for reproducing the results at \url{https://github.com/dongyp13/memorization-AT}.
{'timestamp': '2022-03-15T01:20:12', 'yymm': '2106', 'arxiv_id': '2106.01606', 'language': 'en', 'url': 'https://arxiv.org/abs/2106.01606'}
arxiv
\section{Figures} \begin{figure}[!h] \centerline{ \includegraphics[scale=0.4]{CPH_mrp2.pdf} \hfill \includegraphics[scale=0.38]{PD4mrp2.pdf} } \caption{The Cartesian position heap of string $S = \mathtt{264275843647576}$ together with the maximal reach pointers (doubly-lined arcs). For each $w_i = \mathsf{PD}(S[n-i+1..])$, the singly-underlined prefix is the string that is represented by the node $u_i$ in $\mathsf{CPH}(S)$, and the doubly-underlined substring is the string skipped by the maximal reach pointer.} \label{fig:CPH_mrp} \end{figure} \begin{figure}[!h] \centerline{ \includegraphics[scale=0.4]{lowerbound_branches_CPH.pdf} \hfill \includegraphics[scale=0.38]{lowerbound_branches_string.pdf} } \caption{The string $S$ of Lemma~\ref{lem:many_branches} with $k = 4$, i.e., $S = \mathtt{1121221222122221}$ and its Cartesian-tree position heap $\mathsf{CPH}(S)$. For each $w_i = \mathsf{PD}(S[n-i+1..])$, the underlined prefix is represented by the node of $\mathsf{CPH}(S)$ that corresponds to $w_i$. Node $011$ has $k = 4$ out-going edges. This example also shows that the upper bound of Lemma~\ref{lem:number_of_branches} is tight, since node $011$ has $|011|+1 = 4$ out-going edges.} \label{fig:lower_bound_branches} \end{figure} \begin{figure}[!h] \centerline{ \includegraphics[scale=0.35]{DAG.pdf} } \caption{DAG $\mathsf{G}(S)$, $\mathsf{PD}(S)$, and $\mathsf{FP}(S)$ for string $S = \mathtt{26427584365741}$.} \label{fig:DAG} \end{figure} \begin{figure}[!h] \begin{minipage}{0.69\textwidth} \raisebox{10mm}{\includegraphics[scale=0.35]{InputTrie.pdf}} \includegraphics[scale=0.35]{FP.pdf} \end{minipage} \begin{minipage}{0.29\textwidth} \includegraphics[scale=0.33]{PD4FP.pdf} \end{minipage} \vspace*{2mm} \caption{Left upper: An example of input trie $\boldsymbol{T}$. Left lower: The FP-trie $\boldsymbol{T}_{\mathsf{FP}}$ that is obtained from the original trie $\boldsymbol{T}$. For instance, the FP encodings of the two path strings $\boldsymbol{T}[3..] = \mathtt{5343}$ and $\boldsymbol{T}[4..] = \mathtt{4253}$ have the same FP encoding $0200$ and thus the node id's $3$ and $4$ are stored in a single node in $\boldsymbol{T}_{\mathsf{FP}}$. The representative (the id) of the node $\{3, 4\}$ in $\boldsymbol{T}_{\mathsf{FP}}$ is $\min\{3, 4\} = 3$.} \label{fig:input_trie} \end{figure} \begin{figure}[!h] \centerline{ \includegraphics[scale=0.4]{CPH4trie.pdf} } \caption{$\mathsf{CPH}(\boldsymbol{T})$ for the trie $\boldsymbol{T}$ of Fig.~\ref{fig:input_trie}, where every node $v$ store the representatives $1, 2, 3, 5, 6, 8, 9, 11, 12, 13, 15, 16$ of the corresponding equivalence class $\mathcal{C}_v$.} \label{fig:CPM_trie} \end{figure} \begin{figure}[!h] \centerline{ \includegraphics[scale=0.4]{matching_caseA.pdf} \hfill \includegraphics[scale=0.4]{matching_caseB.pdf} } \caption{Left: Illustration for Condition (a) of Lemma~\ref{lemma:decendant_condition}. Right: Illustration for Condition (b) of Lemma~\ref{lemma:decendant_condition}, where the doubly-lined arc represents the maximal reach pointer.} \label{fig:matching} \end{figure} \section*{Acknowledgments} This work was supported by JSPS KAKENHI Grant Numbers JP18K18002 (YN) and JP21K17705 (YN), and by JST PRESTO Grant Number JPMJPR1922 (SI). \clearpage \bibliographystyle{abbrv} \section{Cartesian-tree Position Heaps for Strings} \label{sec:cph_string} \begin{wrapfigure}[21]{r}{0.7\textwidth} \centering \raisebox{5mm}{\includegraphics[scale=0.4]{CPH_rsl_decrease2.pdf}} \hfill \includegraphics[scale=0.5]{string_example.pdf} \caption{$\mathsf{CPH}(S)$ for string $S = \mathtt{26427584365741}$. For each $w_i = \mathsf{PD}(S[n-i+1..])$, the underlined prefix is the string that is represented by the node $u_i$ in $\mathsf{CPH}(S)$. The dotted arcs are reversed suffix links (not all reversed suffix links are shown).} \label{fig:CPH_string_example} \end{wrapfigure} In this section, we introduce our new indexing structure for Problem~\ref{prob:string}. For a given text string $S$ of length $n$, let $\mathcal{W}_S$ denote the sequence of the parent distance encodings of the non-empty suffixes of $S$ which are sorted in increasing order of their lengths. Namely, $\mathcal{W}_S = \langle w_1$, \ldots, $w_n \rangle = \langle \mathsf{PD}(S[n..])$, \ldots, $\mathsf{PD}(S[1..]) \rangle$, where $w_{n-i+1} = \mathsf{PD}(S[i..])$. The \emph{Cartesian-tree Position Heap} (\emph{CPH}) of string $S$, denoted $\mathsf{CPH}(S)$, is the sequence hash tree of $\mathcal{W}_S$, that is, $\mathsf{CPH}(S) = \mathsf{SHT}(\mathcal{W}_S)$. Note that for each $1 \leq i \leq n+1$, $\mathsf{CPH}(S[i..]) = \mathsf{SHT}(\mathcal{W}_S)^{n-i+1}$ holds. Our algorithm builds $\mathsf{CPH}(S[i..])$ for decreasing $i = n, \ldots, 1$, which means that we process the given text string $S$ in a right-to-left online manner, by prepending the new character $S[i]$ to the current suffix $S[i+1..]$. For a sequence $v$ of integers, let $\mathcal{Z}_v$ denote the sorted list of positions $z$ in $v$ such that $v[z] = 0$ iff $z \in \mathcal{Z}_v$. Clearly $|\mathcal{Z}_v|$ is equal to the number of $0$'s in $v$. \begin{lemma} \label{lem:number_of_zeros} For any string $S$, $|\mathcal{Z}_{\mathsf{PD}(S)}| \leq \sigma_S$. \end{lemma} \begin{proof} Let $\mathcal{Z}_{\mathsf{PD}(S)} = z_1, \ldots, z_{\ell}$. We have that $S[z_{1}] > \cdots > S[z_{\ell}]$ since otherwise $\mathsf{PD}(S)[z_{x}] \neq 0$ for some $z_x$, a contradiction. Thus $|\mathcal{Z}_{\mathsf{PD}(S)}| \leq \sigma_S$ holds. \end{proof} \begin{lemma} \label{lem:online_PD} For each $i = n, \ldots, 1$, $\mathsf{PD}(S[i..])$ can be computed from $\mathsf{PD}(S[i+1..])$ in an online manner, using a total of $O(n)$ time with $O(\sigma_S)$ working space. \end{lemma} \begin{proof} Given a new character $S[i]$, we check each position $z$ in the list $\mathcal{Z}_{\mathsf{PD}(S[i+1..])}$ in increasing order. Let $\hat{z} = z+i$, i.e., $\hat{z}$ is the global position in $S$ corresponding to $z$ in $S[i+1..]$. If $S[i] \leq S[\hat{z}]$, then we set $\mathsf{PD}(S[i..])[z-i+1] = z-i~(> 0)$ and remove $z$ from the list. Remark that these removed positions correspond to the front pointers in the next suffix $S[i..]$. We stop when we encounter the first $z$ in the list such that $S[i] > S[\hat{z}]$. Finally we add the position $i$ to the head of the remaining positions in the list. This gives us $\mathcal{Z}_{\mathsf{PD}(S[i..])}$ for the next suffix $S[i..]$. It is clear that once a position in the PD encoding is assigned a non-zero value, then the value never changes whatever characters we prepend to the string. Therefore, we can compute $\mathsf{PD}(S[i..])$ from $\mathsf{PD}(S[i+1..])$ in a total of $O(n)$ time for every $1 \leq i \leq n$. The working space is $O(\sigma_S)$ due to Lemma~\ref{lem:number_of_zeros}. \end{proof} A position $i$ in a sequence $u$ of non-negative integers is said to be a \emph{front pointer} in $u$ if $i - u[i] = 1$ \sinote*{added}{and $i \geq 2$.} Let $\mathcal{F}_u$ denote the sorted list of front pointers in $u$. \annote*{added}{% For example, if $u = 01214501$, then $\mathcal{F}_u = \{2,3,5,6\}$. }% The positions of the suffix $S[i+1..]$ which are removed from $\mathcal{Z}_{\mathsf{PD}(S[i+1..])}$ correspond to the front pointers in $\mathcal{F}_{\mathsf{PD}(S[i..])}$ for the next suffix $S[i..]$. Our construction algorithm updates $\mathsf{CPH}(S[i+1..])$ to $\mathsf{CPH}(S[i..])$ by inserting a new node for the next suffix $S[i..]$, processing the given string $S$ in a right-to-left online manner. Here the task is to efficiently locate the parent of the new node in the current CPH at each iteration. As in the previous work on right-to-left online construction of indexing structures for other types of pattern matching~\cite{Weiner,ehrenfeucht_position_heaps_2011,FujisatoNIBT18,FujisatoNIBT19b}, we use the \emph{reversed suffix links} in our construction algorithm for $\mathsf{CPH}(S)$. For ease of explanation, we first introduce the notion of the \emph{suffix links}. Let $u$ be any non-root node of $\mathsf{CPH}(S)$. We identify $u$ with the path label from the root of $\mathsf{CPH}(S)$ to $u$, so that $u$ is a PD encoding of some substring of $S$. We define the suffix link of $u$, denoted $\mathsf{sl}(u)$, such that $\mathsf{sl}(u) = v$ iff $v$ is obtained by (1) removing the first $0$~($= u[1]$), and (2) substituting $0$ for the character $u[f]$ at every front pointer $f \in \mathcal{F}_u \subseteq [2..|u|]$ of $u$. The reversed suffix link of $v$ with non-negative integer label $a$, denoted $\mathsf{rsl}(v, a)$, is defined such that $\mathsf{rsl}(v, a) = u$ iff $\mathsf{sl}(u) = v$ and $a = |\mathcal{F}_u|$. See also Figure~\ref{fig:CPH_string_example}. \begin{lemma} \label{lem:upper_bound_a} Let $u, v$ be any nodes of $\mathsf{CPH}(S)$ such that $\mathsf{rsl}(v, a) = u$ with label $a$. Then $a \leq \sigma_S$. \end{lemma} \begin{proof} Since $|\mathcal{F}_u| \leq |\mathcal{Z}_v|$, using Lemma~\ref{lem:number_of_zeros}, we obtain $a = |\mathcal{F}_u| \leq |\mathcal{Z}_v| \leq \sigma_{S'} \leq \sigma_S$, where $S'$ is a substring of $S$ such that $\mathsf{PD}(S') = v$. \qed \end{proof} The next lemma shows that the number of out-going reversed suffix links of each node $v$ is bounded by the alphabet size. \begin{figure}[tbh] \centering \includegraphics[scale=0.4]{construction_algorithm.pdf} \caption{We climb up the path from $u(i+1)$ and find the parent $p(i)$ of the new node $u(i)$ (in black). The label $a$ of the reversed suffix link we traverse from $v(i)$ is equal to the number of front pointers in $p(i)$.} \label{fig:CPH_construction_string} \end{figure} Our CPH construction algorithm makes use of the following monotonicity of the labels of reversed suffix links: \begin{lemma} \label{lem:monotonicity} Suppose that there exist two reversed suffix links $\mathsf{rsl}(v, a) = u$ and $\mathsf{rsl}(v', a') = u'$ such that $v' = \mathsf{parent}(v)$ and $u' = \mathsf{parent}(u)$. Then, $0 \leq a - a' \leq 1$. \end{lemma} \begin{proof} Immediately follows from $a = |\mathcal{F}_{u}|$, $a' = |\mathcal{F}_{u'}|$, and $u' = u[1..|u|-1]$. \end{proof} We are ready to design our right-to-left online construction algorithm for the CPH of a given string $S$. Since $\mathsf{PD}(S[i..])$ is the $(n-i+1)$-th string $w_{n-i+1}$ of the input sequence $\mathcal{W}_S$, for ease of explanation, we will use the convention that $u(i) = u_{n-i+1}$ and $p(i) = p_{n-i-1}$, where the new node $u(i)$ for $w_{n-i+1} = \mathsf{PD}(S[i..])$ is inserted as a child of $p(i)$. See Figure~\ref{fig:CPH_construction_string}. \vspace*{2mm} \begin{breakbox} \noindent Algorithm 1: Right-to-Left Online Construction of $\mathsf{CPH}(S)$ \begin{description} \item[$i = n$ (base case):] We begin with $\mathsf{CPH}(S[n..])$ which consists of the root $r = u(n+1)$ and the node $u(n)$ for the first (i.e. shortest) suffix $S[n..]$ of $S$. Since $w_1 = \mathsf{PD}(S[n..]) = \mathsf{PD}(S[n]) = 0$, the edge from $r$ to $u(n)$ is labeled $0$. Also, we set the reversed suffix link $\mathsf{rsl}(r, 0) = u(n)$. \item[$i = n-1, \ldots, 1$ (iteration):] Given $\mathsf{CPH}(S[i+1..])$ which consists of the nodes $u(i+1), \ldots, u(n)$, which respectively represent some prefixes of the already processed strings $w_{n-i}, \ldots, w_1 = \mathsf{PD}(S[i+1..]), \ldots, \mathsf{PD}(S[n..])$, together with their reversed suffix links. We find the parent $p(i)$ of the new node $u(i)$ for $\mathsf{PD}(S[i..])$, as follows: We start from the last-created node $u(i+1)$ for the previous $\mathsf{PD}(S[i+1..])$, and climb up the path towards the root $r$. Let $d_i \in [1..|u(i+1)|]$ be the smallest integer such that the $d_i$-th ancestor $v(i) = \mathsf{anc}(u(i+1), d_i)$ of $u(i+1)$ has the reversed suffix link $\mathsf{rsl}(v(i), a)$ with the label $a = |\mathcal{F}_{\mathsf{PD}(S[i..i+|v(i)|])}|$. We traverse the reversed suffix link from $v(i)$ and let $p(i) = \mathsf{rsl}(v(i), a)$. We then insert the new node $u(i)$ as the new child of $p(i)$, with the edge labeled $\mathsf{PD}(S[i..])[i+|u(i)|-1]$. Finally, we create a new reversed suffix link $\mathsf{rsl}(\hat{v}(i), b) = u(i)$, where $\hat{v}(i) = \mathsf{anc}(u(i+1), d_i-1)$ and $\mathsf{parent}(\hat{v}) = v$. We set $b \leftarrow a+1$ if the position $i+|p(i)|$ is a front pointer of $\mathsf{PD}(S[i..])$, and $b \leftarrow a$ otherwise. \end{description} \end{breakbox} For computing the label $a = |\mathcal{F}_{\mathsf{PD}(S[i..i+|v(i)|])}|$ efficiently, we introduce a new encoding $\mathsf{FP}$ that is defined as follows: For any string $S$ of length $n$, let \sinote*{fixed}{% $\mathsf{FP}(S)[i] = |\mathcal{F}_{\mathsf{PD}(S[i..n])}|$. }% The $\mathsf{FP}$ encoding preserves the ct-matching equivalence: \begin{lemma} \label{lem:FP_PD} For any two strings $S_1$ and $S_2$, $S_1 \approx S_2$ iff $\mathsf{FP}(S_1) = \mathsf{FP}(S_2)$. \end{lemma} \begin{proof} For a string $S$, consider the DAG $\mathsf{G}(S) = (V, E)$ such that $V = \{1, \ldots, |S|\}$, $E = \{(j, i) \mid j = i - \mathsf{PD}(S)[i] \}$ (see also Figure~\ref{fig:DAG} in Appendix). By Lemma~\ref{lem:CT-PD}, for any strings $S_1$ and $S_2$, $\mathsf{G}(S_1) = \mathsf{G}(S_2)$ iff $S_1 \approx S_2$. Now, we will show there is a one-to-one correspondence between the DAG $\mathsf{G}$ and the $\mathsf{FP}$ encoding. ($\Rightarrow$) We are given $\mathsf{G}(S)$ for some (unknown) string $S$. Since $\mathsf{FP}(S)[i]$ is the in-degree of the node $i$ of $\mathsf{G}(S)$, $\mathsf{FP}(S)$ is unique for the given DAG $\mathsf{G}(S)$. ($\Leftarrow$) Given $\mathsf{FP}(S)$ for some (unknown) string $S$, we show an algorithm that builds DAG $\mathsf{G}(S)$. We first create nodes $V = \{1, \ldots, |S|\}$ without edges, where all nodes in $V$ are initially unmarked. For each $i = n, \ldots, 1$ in decreasing order, if $\mathsf{FP}(S)[i] > 0$, then select the leftmost $\mathsf{FP}(S)[i]$ unmarked nodes in the range $[i-1..n]$, and create an edge $(i, i')$ from each selected node $i'$ to $i$. We mark all these $\mathsf{FP}(S)[i]$ nodes at the end of this step, and proceed to the next node $i-1$. The resulting DAG $\mathsf{G}(S)$ is clearly unique for a given $\mathsf{PD}(S)$. \end{proof} \sinote*{added}{% For computing the label $a = |\mathcal{F}_{\mathsf{PD}(S[i..i+|v(i)|])}| = \mathsf{FP}(S[i..i+|v(i)|])[1]$ of the reversed suffix link in Algorithm 1, it is sufficient to maintain the induced graph $\mathsf{G}_{[i..j]}$ of DAG $\mathsf{G}$ for a variable-length sliding window $S[i..j]$ with the nodes $\{i, \ldots, j\}$. This can easily be maintained in $O(n)$ total time. }% \begin{theorem} \label{lem:construction_cph_string} Algorithm 1 builds $\mathsf{CPH}(S[i..])$ for decreasing $i = n, \ldots, 1$ in a total of $O(n \log \sigma)$ time and $O(n)$ space, where $\sigma$ is the alphabet size. \end{theorem} \begin{proof} \textbf{Correctness:} Consider the $(n-i+1)$-th step in which we process $\mathsf{PD}(S[i..])$. By Lemma~\ref{lem:monotonicity}, the $d_i$-th ancestor $v(i) = \mathsf{anc}(u(i+1), d_i)$ of $u(i+1)$ can be found by simply walking up the path from the start node $u(i+1)$. Note that there always exists such ancestor $v(i)$ of $u(i+1)$ since the root $r$ has the defined reversed suffix link $\mathsf{rsl}(r, 0) = 0$. By the definition of $v(i)$ and its reversed suffix link, $\mathsf{rsl}(v(i), a) = p(i)$ is the longest prefix of $\mathsf{PD}(S[i..])$ that is represented by $\mathsf{CPH}(S[i+1..])$ (see also Figure~\ref{fig:CPH_construction_string}). Thus, $p(i)$ is the parent of the new node $u(i)$ for $\mathsf{PD}(S[i..])$. The correctness of the new reversed suffix link $\mathsf{rsl}(\hat{v}(i),b) = u(i)$ follows from the definition. \noindent \textbf{Complexity:} The time complexity is proportional to the total number $\sum_{i = 1}^{n} d_i$ of nodes that we visit for all $i = n, \ldots, 1$. Clearly $|u(i)| - |u(i+1)| = d_i-2$. Thus, $\sum_{i = 1}^{n} d_i = \sum_{i = 1}^{n}(|u(i)| - |u(i+1)|+2) = |u(1)| - |u(n)| + 2n \leq 3n = O(n)$. Using Lemma~\ref{lem:rsl_bounds} and sliding-window $\mathsf{FP}$, we can find the reversed suffix links in $O(\log \sigma_S)$ time at each of the $\sum_{i = 1}^{n} d_i$ visited nodes. Thus the total time complexity is $O(n \log \sigma_S)$. Since the number of nodes in $\mathsf{CPH}(S)$ is $n+1$ and the number of reversed suffix links is $n$, the total space complexity is $O(n)$. \end{proof} \begin{lemma} \label{lem:many_branches} There exists a string $S$ of length $n$ over a binary alphabet $\Sigma = \{\mathtt{1, 2}\}$ such a node in $\mathsf{CPH}(S)$ has $\Omega(\sqrt{n})$ out-going edges. \end{lemma} \begin{proof} Consider string $S = \mathtt{1}\mathtt{121}\mathtt{1221} \cdots \mathtt{1}\mathtt{2}^k\mathtt{1}$. Then, for any $1 \leq \ell \leq k$, there exist nodes representing $01^{k-2}\ell$ (see also Figure~\ref{fig:lower_bound_branches} in Appendix). Since $k = \Theta(\sqrt{n})$, the parent node $01^{k-2}$ has $\Omega(\sqrt{n})$ out-going edges. \end{proof} Due to Lemma~\ref{lem:many_branches}, if we maintain a sorted list of out-going edges for each node during our online construction of $\mathsf{CPH}(S[i..])$, it would require $O(n \log n)$ time even for a constant-size alphabet. Still, after $\mathsf{CPH}(S)$ has been constructed, we can sort all the edges offline, as follows: \begin{theorem} For any string $S$ over an integer alphabet $\Sigma = [1..\sigma]$ of size $\sigma = n^{O(1)}$, the edge-sorted $\mathsf{CPH}(S)$ together with the maximal reach pointers can be computed in $O(n \log \sigma_S)$ time and $O(n)$ space. \end{theorem} \begin{proof} We sort the edges of $\mathsf{CPH}(S)$ as follows: Let $i$ be the id of each node $u(i)$. Then sort the pairs $(i, x)$ of the ids and the edge labels. Since $i \in [0..n-1]$ and $x \in [1..n^{O(1)}]$, we can sort these pairs in $O(n)$ time by a radix sort. % The maximal reach pointers can be computed in $O(n \log \sigma_S)$ time using the reversed suffix links, in a similar way to the position heaps for exact matching~\cite{ehrenfeucht_position_heaps_2011}. \end{proof} See Figure~\ref{fig:CPH_mrp} in Appendix for an example of $\mathsf{CPH}(S)$ with maximal reach pointers. \section{Cartesian-tree Position Heaps for Tries} Let $\boldsymbol{T}$ be the input text trie with $N$ nodes. A na\"ive extension of our CPH to a trie would be to build the CPH for the sequence $\langle \mathsf{PD}(\boldsymbol{T}[N..]), \ldots, \mathsf{PD}(\boldsymbol{T}[1..]) \rangle$ of the parent encodings of all the path strings of $\boldsymbol{T}$ towards the root $\mathbf{r}$. However, this does not seem to work because the parent encodings are not consistent for suffixes. For instance, consider two strings $\mathtt{1432}$ and $\mathtt{4432}$. Their longest common suffix $\mathtt{432}$ is represented by a single path in a trie $\boldsymbol{T}$. However, the longest common suffix of $\mathsf{PD}(\mathtt{1432}) = 0123$ and $\mathsf{PD}(\mathtt{4432}) = 0100$ is $\varepsilon$. Thus, in the worst case, we would have to consider all the path strings $\boldsymbol{T}[N..]$, \ldots, $\boldsymbol{T}[1..]$ in $\boldsymbol{T}$ separately, but the total length of these path strings in $\boldsymbol{T}$ is $\Omega(N^2)$. To overcome this difficulty, \sinote*{modified}{% we reuse the $\mathsf{FP}$ encoding from Section~\ref{sec:cph_string}. Since $\mathsf{FP}(S)[i]$ is determined merely by the suffix $S[i..]$, the $\mathsf{FP}$ encoding is suffix-consistent. }% For an input trie $\boldsymbol{T}$, let the \emph{FP-trie} $\boldsymbol{T}_{\mathsf{FP}}$ be the reversed trie storing $\mathsf{FP}(\boldsymbol{T}[i..])$ for all the original path strings $\boldsymbol{T}[i..]$ towards the root. Let $N'$ be the number of nodes in $\boldsymbol{T}_{\mathsf{FP}}$. Since $\mathsf{FP}$ is suffix-consistent, $N' \leq N$ always holds. Namely, $\mathsf{FP}$ is a linear-size representation of the equivalence relation of the nodes of $\boldsymbol{T}$ w.r.t. $\approx$. Each node $v$ of $\boldsymbol{T}_{\mathsf{FP}}$ stores the equivalence class $\mathcal{C}_v = \{i \mid \boldsymbol{T}_{\mathsf{FP}}[v..] = \mathsf{FP}(\boldsymbol{T}[i..])\}$ of the nodes $i$ in $\boldsymbol{T}$ that correspond to $v$. We set $\min\{\mathcal{C}_v\}$ to be the representative of $\mathcal{C}_v$, as well as the id of node $v$. See Figure~\ref{fig:input_trie} in Appendix. Let $\Sigma_{\inputtrie}$ be the set of distinct characters (i.e. edge labels) in $\boldsymbol{T}$ and let $\sigma_{\inputtrie} = |\Sigma_{\inputtrie}|$. The FP-trie $\boldsymbol{T}_{\mathsf{FP}}$ can be computed in $O(N\sigma_{\inputtrie})$ time and working space by a standard traversal on $\boldsymbol{T}$, where we store at most $\sigma_{\inputtrie}$ front pointers in each node of the current path in $\boldsymbol{T}$ due to Lemma~\ref{lem:online_PD}. Let $i_{N'}, \ldots, i_{1}$ be the node id's of $\boldsymbol{T}_{\mathsf{FP}}$ which are sorted in decreasing order. The Cartesian-tree position heap for the input trie $\boldsymbol{T}$ is $\mathsf{CPH}(\boldsymbol{T}) = \mathsf{SHT}(\mathcal{W}_{\boldsymbol{T}})$, where $\mathcal{W}_{\boldsymbol{T}} = \langle \mathsf{PD}(\boldsymbol{T}[i_{N'}..], \ldots, \mathsf{PD}(\boldsymbol{T}[i_1..]) \rangle$. As in the case of string inputs in Section~\ref{sec:cph_string}, we insert the shortest prefix of $\mathsf{PD}(\boldsymbol{T}[i_{k}..])$ that does not exist in $\mathsf{CPH}(\boldsymbol{T}[i_{k+1}..])$. To perform this insert operation, we use the following data structure for a random-access query on the PD encoding of any path string in $\boldsymbol{T}$: \begin{lemma} \label{lem:nearest_ancestor} There is a data structure of size $O(N \sigma_{\inputtrie})$ that can answer the following queries in $O(\sigma_{\inputtrie})$ time each.\\ \textbf{Query input:} The id $i$ of a node in $\boldsymbol{T}$ and integer $\ell > 0$.\\ \textbf{Query output:} The $\ell$th (last) symbol $\mathsf{PD}((\boldsymbol{T}[i..])[1..\ell])[\ell]$ in $\mathsf{PD}(\boldsymbol{T}[i..])[1..\ell]$. \end{lemma} \begin{proof} Let $\mathbf{x}$ be the node with id $i$, and $\mathbf{z} = \mathsf{anc}(\mathbf{x}, \ell)$. Namely, $\mathsf{str}(\mathbf{x}, \mathbf{z}) = (\boldsymbol{T}[j..])[1..\ell]$. For each character $a \in \Sigma_{\inputtrie}$, let $\mathsf{na}(\mathbf{x},a)$ denote the nearest ancestor $\mathbf{y}_a$ of $\mathbf{x}$ such that the edge $(\mathsf{parent}(\mathbf{y}_a), \mathbf{y}_a)$ is labeled $a$. If such an ancestor does not exist, then we set $\mathsf{na}(\mathbf{x},a)$ to the root $\mathbf{r}$. Let $\mathbf{z'} = \mathsf{anc}(\mathbf{x}, \ell-1)$, and $b$ be the label of the edge $(\mathbf{z}, \mathbf{z'})$. Let $D$ be an empty set. For each character $a \in \Sigma_{\inputtrie}$, we query $\mathsf{na}(\mathbf{x}, a) = \mathbf{y}_a$. If $d_a = |\mathbf{y}_a| - |\mathbf{z}'| > 0$ and $a \leq b$, then $d_a$ is a candidate for $(\mathsf{PD}(\boldsymbol{T}[j..])[1..\ell])[\ell]$ and add $d_a$ to set $D$. After testing all $a \in \Sigma_{\inputtrie}$, we have that $(\mathsf{PD}(\boldsymbol{T}[j..])[1..\ell])[\ell] = \min D$. See Figure~\ref{fig:nearest_ancestor}. \begin{figure}[tbh] \centering \includegraphics[scale=0.5]{nearest_ancestor.pdf} \caption{Illustration for the data structure of Lemma~\ref{lem:nearest_ancestor}, where $(\boldsymbol{T}[i..])[1..\ell] = \mathsf{str}(\mathbf{x}, \mathbf{z})$.} \label{fig:nearest_ancestor} \end{figure} For all characters $a \in \Sigma_{\inputtrie}$ and all nodes $x$ in $\boldsymbol{T}$, $\mathsf{na}(\mathbf{x}, a)$ can be pre-computed in a total of $O(N \sigma_{\inputtrie})$ preprocessing time and space, by standard traversals on $\boldsymbol{T}$. Clearly each query is answered in $O(\sigma_{\boldsymbol{T}})$ time. \end{proof} \begin{theorem} Let $\boldsymbol{T}$ be a given trie with $N$ nodes whose edge labels are from an integer alphabet of size $n^{O(1)}$. The edge-sorted $\mathsf{CPH}(\boldsymbol{T})$ with the maximal reach pointers, which occupies $O(N \sigma_{\inputtrie})$ space, can be built in $O(N \sigma_{\inputtrie})$ time. \end{theorem} \begin{proof} The rest of the construction algorithm of $\mathsf{CPH}(\boldsymbol{T})$ is almost the same as the case of the CPH for a string, except that the amortization argument in the proof for Theorem~\ref{lem:construction_cph_string} cannot be applied to the case where the input is a trie. Instead, we use the nearest marked ancestor (NMA) data structure~\cite{westbrook_fast_incre_1992,amir_improved_dynamic_1995} that supports queries and marking nodes in amortized $O(1)$ time each, using space linear in the input tree. For each $a \in [0..\sigma_{\inputtrie}]$, we create a copy $\mathsf{CPH}_a(\boldsymbol{T})$ of $\mathsf{CPH}(\boldsymbol{T})$ and maintain the NMA data structure on $\mathsf{CPH}_a(\boldsymbol{T})$ so that every node $v$ that has defined reversed suffix link $\mathsf{rsl}(v, a)$ is marked, and any other nodes are unmarked. The NMA query for a given node $v$ with character $a$ is denoted by $\mathsf{nma}_a(v)$. If $v$ itself is marked with $a$, then let $\mathsf{nma}_a(v) = v$. % \sinote*{added}{% For any node $\mathbf{x}$ of $\boldsymbol{T}$, let $\mathcal{I}_{\mathbf{x}}$ be the array of size at most $\sigma_{\inputtrie}$ s.t. $\mathcal{I}_{\mathbf{x}}[j] = h$ iff $h$ is the $j$th smallest element of $\mathcal{F}_{\mathsf{PD}(\mathsf{str}(\mathbf{x}))}$. }% We are ready to design our construction algorithm: Suppose that we have already built $\mathsf{CPH}(\boldsymbol{T}[i_{k+1}..])$ and we are to update it to $\mathsf{CPH}(\boldsymbol{T}[i_{k}..])$. \sinote*{modified}{% Let $\mathbf{w}$ be the node in $\boldsymbol{T}$ with id $i_{k}$, and let $\mathbf{u} = \mathsf{parent}(\mathbf{w})$ in $\boldsymbol{T}_{\mathsf{FP}}$. Let $u$ be the node of $\mathsf{CPH}(\boldsymbol{T}[i_{k+1}..])$ that corresponds to $\mathbf{u}$. We initially set $v \leftarrow u$ and $a \leftarrow |\mathcal{F}_{\mathsf{PD}(\boldsymbol{T}[i_k..i_k+|u|])}|$. Let $d(a) = \max\{|u|-\mathcal{I}_{\mathbf{w}}[a]+1, 0\}$. We perform the following: \begin{enumerate} \item[(1)] Check whether $v' = \mathsf{anc}(u, d(a))$ is marked in $\mathsf{CPH}_a(\boldsymbol{T})$. If so, go to (2). Otherwise, update $v \leftarrow v'$, $a \leftarrow a - 1$, and repeat (1). \item[(2)] Return $\mathsf{nma}(v, a)$. \end{enumerate} By the definitions of $\mathcal{I}_{\mathbf{w}}[a]$ and $d(a)$, the node $v(i_k)$ from which we should take the reversed suffix link is in the path between $v'$ and $v$, and it is the lowest ancestor of $v$ that has the reversed suffix link with $a$. Thus, the above algorithm correctly computes the desired node. By Lemma~\ref{lem:upper_bound_a}, the number of queries in (1) for each of the $N'$ nodes is $O(\sigma_{\inputtrie})$, and we use the dynamic level ancestor data structure on our CPH that allows for leaf insertions and level ancestor queries in $O(1)$ time each~\cite{AlstrupH00}. This gives us $O(N \sigma_{\inputtrie})$-time and space construction. }% We will reuse the random access data structure of Lemma~\ref{lem:nearest_ancestor} for pattern matching (see Section~\ref{sec:matching_trie}). Thus $\mathsf{CPH}(\boldsymbol{T})$ requires $O(N \sigma_{\boldsymbol{T}})$ space. \end{proof} \section{Introduction} \label{sec:intro} If the Cartesian trees $\mathsf{CT}(X)$ and $\mathsf{CT}(Y)$ of two strings $X$ and $Y$ are equal, then we say that $X$ and $Y$ \emph{Cartesian-tree match} (\emph{ct-match}). The \emph{Cartesian-tree pattern matching problem} (\emph{ct-matching problem}) ~\cite{ParkBALP20} is, given a text string $S$ and a pattern $P$, to find all substrings $S'$ of $S$ that ct-match with $P$. String equivalence with ct-matching belongs to the class of \emph{substring-consistent equivalence relation} (\emph{SCER})~\cite{MatsuokaAIBT16}, namely, the following holds: If two strings $X$ and $Y$ ct-match, then $X[i..j]$ and $Y[i..j]$ also ct-match for any $1 \leq i \leq j \leq |X|$. Among other types of SCERs (\cite{Baker93,baker95parameterized,Baker96,IIT11,KimH16}), ct-matching is the most related to order-peserving matching (op-matching)~\cite{KimEFHIPPT14,ChoNPS15,CrochemoreIKKLP16}. Two strings $X$ and $Y$ are said to op-match if the relative order of the characters in $X$ and the relative order of the characters in $Y$ are the same. It is known that with ct-matching one can detect some interesting occurrences of a pattern that cannot be captured with op-matching. More precisely, if two strings $X$ and $Y$ op-match, then $X$ and $Y$ also ct-match. However, the reverse is not true. With this property in hand, ct-matching is motivated for analysis of time series such as stock charts~\cite{ParkBALP20,FuCLN07}. This paper deals with the indexing version of the ct-matching problem. Park et al.~\cite{ParkBALP20} proposed the \emph{Cartesian suffix tree} (\emph{CST}) for a text string $S$ that can be built in $O(n \log n)$ worst-case time or $O(n)$ expected time, where $n$ is the length of the text string $S$. The $\log n$ factor in the worst-case complexity is due to the fact that the \emph{parent-encoding}, a key concept for ct-matching introduced in~\cite{ParkBALP20}, is a sequence of integers in range $[0..n-1]$. While it is not explicitly stated in Park et al.'s paper~\cite{ParkBALP20}, our simple analysis (c.f. Lemma~\ref{lem:number_of_branches} in Section~\ref{sec:matching}) reveals that the CST supports pattern matching queries in $O(m \log m + \mathit{occ})$ time, where $m$ is the pattern length and $\mathit{occ}$ is the number of pattern occurrences. In this paper, we present a new indexing structure for this problem, called the \emph{Cartesian-tree Position Heap} (\emph{CPH}). We show that the CPH of $S$, which occupies $O(n)$ space, can be built in $O(n \log \sigma)$ time with $O(n)$ working space and supports pattern matching queries in $O(m (\sigma + \log (\min\{h, m\})) + \mathit{occ})$ time, where $h$ is the height of the CPH. Compared to the afore-mentioned CST, our CPH is the \emph{first} index for ct-matching that can be built in worst-case linear time for constant-size alphabets, while pattern matching queries with our CPH can be slower than with the CST when $\sigma$ is large. We then consider the case where the text is a labeled tree (i.e. a trie). Given a trie $\boldsymbol{T}$ with $N$ nodes, we show that the CPH of $\boldsymbol{T}$, which occupies $O(N \sigma)$ space, can be built in $O(N \sigma)$ time and $O(N \sigma)$ working space. We also show how to support pattern matching queries in $O(m (\sigma^2 + \log (\min\{h, m\})) + \mathit{occ})$ time in the trie case. To our knowledge, our CPH is the first indexing structure for ct-matching on tries that uses linear space for constant-size alphabets. Conceptually, our CPH is most related to the \emph{parameterized position heap} (\emph{PPH}) for a string~\cite{FujisatoNIBT18} and for a trie~\cite{FujisatoNIBT19b}, in that our CPHs and the PPHs are both constructed in an incremental manner where the suffixes of an input string and the suffixes of an input trie are processed in increasing order of their lengths. However, some new techniques are required in the construction of our CPH due to different nature of the \emph{parent encoding}~\cite{ParkBALP20} of strings for ct-matching, from the \emph{previous encoding}~\cite{Baker93} of strings for parameterized matching. \section{Cartesian-tree Pattern Matching with Position Heaps} \label{sec:matching} \subsection{Pattern Matching on Text String $S$ with $\mathsf{CPH}(S)$} \label{sec:matching_string} Given a pattern $P$ of length $m$, we first compute the greedy factorization $\mathsf{f}(P) = P_0, P_1, \ldots, P_k$ of $P$ such that $P_0 = \varepsilon$, and for $1 \leq l \leq k$, $P_l = P[\mathsf{lsum}(l-1)+1..\mathsf{lsum}(l)]$ is the longest prefix of $P_l \cdots P_k$ that is represented by $\mathsf{CPH}(S)$, where $\mathsf{lsum}(l) = \sum_{j = 0}^l|P_j|$. We consider such a factorization of $P$ since the height $h$ of $\mathsf{CPH}(S)$ can be smaller than the pattern length $m$. \begin{lemma} \label{lem:number_of_branches} Any node $v$ in $\mathsf{CPH}(S)$ has at most $|v|$ out-going edges. \end{lemma} \begin{proof} Let $(v, c, u)$ be any out-going edge of $v$. When $|u|-1$ is a front pointer of $u$, then $c = u[|u|]$ and this is when $c$ takes the maximum value. Since $u[|u|] \leq |u|-1$, we have $c \leq |u|-1$. Since the edge label of $\mathsf{CPH}(S)$ is non-negative, $v$ can have at most $|u|-1 = |v|$ out-going edges. \end{proof} The next corollary immediately follows from Lemma~\ref{lem:number_of_branches}. \begin{corollary} Given a pattern $P$ of length $m$, its factorization $\mathsf{f}(P)$ can be computed in $O(m \log (\min\{m, h\}))$ time, where $h$ is the height of $\mathsf{CPH}(S)$. \end{corollary} The next lemma is analogous to the position heap for exact matching~\cite{ehrenfeucht_position_heaps_2011}. \begin{lemma} \label{lemma:decendant_condition} Consider two nodes $u$ and $v$ in $\mathsf{CPH}(S)$ such that $u = \mathsf{PD}(P)$ the id of $v$ is $i$. Then, $\mathsf{PD}(S[i..])[1..|u|] = u$ iff one of the following conditions holds: (a) $v$ is a descendant of $u$; (b) $\mathsf{mrp}(v)$ is a descendant of $u$. \end{lemma} See also Figure~\ref{fig:matching} in Appendix. We perform a standard traversal on $\mathsf{CPH}(S)$ so that one we check whether a node is a descendant of another node in $O(1)$ time. When $k = 1$~(i.e. $\mathsf{f}(P) = P$), $\mathsf{PD}(P)$ is represented by some node $u$ of $\mathsf{CPH}(S)$. Now a direct application of Lemma~\ref{lemma:decendant_condition} gives us all the $\mathit{occ}$ pattern occurrences in $O(m \log m + \mathit{occ})$ time, where $\min\{m, h\} = m$ in this case. All we need here is to report the id of every descendant of $u$ (Condition (a)) and the id of each node $v$ that satisfies Condition (b). The number of such nodes $v$ is less than $m$. When $k \geq 2$~(i.e. $\mathsf{f}(P) \neq P$), there is no node that represents $\mathsf{PD}(P)$ for the whole pattern $P$. This happens only when $\mathit{occ} < m$, since otherwise there has to be a node representing $\mathsf{PD}(P)$ by the incremental construction of $\mathsf{CPH}(S)$, a contradiction. This implies that Condition (a) of Lemma~\ref{lemma:decendant_condition} does apply when $k \geq 2$. Thus, the \emph{candidates} for the pattern occurrences only come from Condition (b), which are restricted to the nodes $v$ such that $\mathsf{mrp}(v) = u_1$, where $u_1 = \mathsf{PD}(P_1)$. We apply Condition (b) iteratively for the following $P_2, \ldots, P_k$, while keeping track of the position $i$ that was associated to each node $v$ such that $\mathsf{mrp}(v) = u_1$. This can be done by padding $i$ with the off-set $\mathsf{lsum}(l-1)$ when we process $P_l$. We keep such a position $i$ if Condition (b) is satisfied for all the following pattern blocks $P_2, \ldots, P_k$, namely, if the maximal reach pointer of the node with id $i+\mathsf{lsum}(l-1)$ points to node $u_l = \mathsf{PD}(P_l)$ for increasing $l = 2, \ldots, k$. As soon as Condition (b) is not satisfied with some $l$, we discard position $i$. Suppose that we have processed the all pattern blocks $P_1, \ldots, P_k$ in $\mathsf{f}(P)$. Now we have that $\mathsf{PD}(S[i..])[1..m] = \mathsf{PD}(P)$ (or equivalently $S[i..i+m-1] \approx P$) \emph{only if} the position $i$ has survived. Namely, position $i$ is only a candidate of a pattern occurrence at this point, since the above algorithm only guarantees that $\mathsf{PD}(P_1) \cdots \mathsf{PD}(P_k) = \mathsf{PD}(S[i..])[1..m]$. Note also that, by Condition (b), the number of such survived positions $i$ is bounded by $\min\{|P_1|, \ldots, |P_k|\} \leq m/k$. For each survived position $i$, we verify whether $\mathsf{PD}(P) = \mathsf{PD}(S[i..])[1..m]$. This can be done by checking, for each increasing $l = 1, \ldots, k$, whether or not $\mathsf{PD}(S[i..])[\mathsf{lsum}(l-1)+y]= \mathsf{PD}(P_1 \cdots P_l)[\mathsf{lsum}(l-1)+y]$ for every position $y$~($1 \leq y \leq |P_l|$) such that $\mathsf{PD}(P_l)[y] = 0$. By the definition of $\mathsf{PD}$, the number of such positions $y$ is at most $\sigma_{P_l} \leq \sigma_P$. Thus, for each survived position $i$ we have at most $k \sigma_P$ positions to verify. Since we have at most $m/k$ survived positions, the verification takes a total of $O(\frac{m}{k} \cdot k \sigma_P) = O(m\sigma_P)$ time. \begin{theorem} Let $S$ be the text string of length $n$. Using $\mathsf{CPH}(S)$ of size $O(n)$ augmented with the maximal reach pointers, we can find all $\mathit{occ}$ occurrences for a given pattern $P$ in $S$ in $O(m(\sigma_P +\log(\min\{m,h\})) + \mathit{occ})$ time, where $m = |P|$ and $h$ is the height of $\mathsf{CPH}(S)$. \end{theorem} \subsection{Pattern Matching on Text Trie $\boldsymbol{T}$ with $\mathsf{CPH}(\boldsymbol{T})$} \label{sec:matching_trie} In the text trie case, we can basically use the same matching algorithm as in the text string case of Section~\ref{sec:matching_string}. However, recall that we cannot afford to store the PD encodings of the path strings in $\boldsymbol{T}$ as it requires $\Omega(n^2)$ space. Instead, we reuse the random-access data structure of Lemma~\ref{lem:nearest_ancestor} for the verification step. Since it takes $O(\sigma_{\boldsymbol{T}})$ time for each random-access query, and since the data structure occupies $O(N \sigma_{\boldsymbol{T}})$ space, we have the following complexity: \begin{theorem} Let $\boldsymbol{T}$ be the text trie with $N$ nodes. Using $\mathsf{CPH}(\boldsymbol{T})$ of size $O(N \sigma_{\boldsymbol{T}})$ augmented with the maximal reach pointers, we can find all $\mathit{occ}$ occurrences for a given pattern $P$ in $\boldsymbol{T}$ in $O(m(\sigma_P \sigma_{\boldsymbol{T}}+\log(\min\{m,h\})) + \mathit{occ})$ time, where $m = |P|$ and $h$ is the height of $\mathsf{CPH}(\boldsymbol{T})$. \end{theorem} \section{Preliminaries} \subsection{Strings and (Reversed) Tries} Let $\Sigma$ be an ordered alphabet of size $\sigma$. An element of $\Sigma$ is called a \emph{character}. An element of $\Sigma^*$ is called a \emph{string}. For a string $S \in \Sigma^*$, let $\sigma_S$ denote the number of distinct characters in $S$. The empty string $\varepsilon$ is a string of length 0, namely, $|\varepsilon| = 0$. For a string $S = XYZ$, $X$, $Y$ and $Z$ are called a \emph{prefix}, \emph{substring}, and \emph{suffix} of $S$, respectively. The set of prefixes of a string $S$ is denoted by $\mathsf{Prefix}(S)$. The $i$-th character of a string $S$ is denoted by $S[i]$ for $1 \leq i \leq |S|$, and the substring of a string $S$ that begins at position $i$ and ends at position $j$ is denoted by $S[i..j]$ for $1 \leq i \leq j \leq |S|$. For convenience, let $S[i..j] = \varepsilon$ if $j < i$. Also, let $S[i..] = S[i..|S|]$ for any $1 \leq i \leq |S|+1$. A \emph{trie} is a rooted tree that represents a set of strings, where each edge is labeled with a character from $\Sigma$ and the labels of the out-going edges of each node is mutually distinct. Tries are natural generalizations to strings in that tries can have branches while strings are sequences without branches. Let $\mathbf{x}$ be any node of a given trie $\boldsymbol{T}$, and let $\mathbf{r}$ denote the root of $\boldsymbol{T}$. Let $\mathsf{depth}(\mathbf{x})$ denote the depth of $\mathbf{x}$. When $\mathbf{x} \neq \mathbf{r}$, let $\mathsf{parent}(\mathbf{x})$ denote the parent of $\mathbf{x}$. For any $0 \leq j \leq \mathsf{depth}(\mathbf{x})$, let $\mathsf{anc}(\mathbf{x}, j)$ denote the $j$-th ancestor of $\mathbf{x}$, namely, $\mathsf{anc}(\mathbf{x}, 0) = \mathbf{x}$ and $\mathsf{anc}(\mathbf{x}, j) = \mathsf{parent}(\mathsf{anc}(\mathbf{x}, j-1))$ for $1 \leq j \leq \mathsf{depth}(\mathbf{x})$. It is known that after a linear-time processing on $\boldsymbol{T}$, $\mathsf{anc}(\mathbf{x}, j)$ for any query node $\mathbf{x}$ and integer $j$ can be answered in $O(1)$ time~\cite{BenderF04}. \sinote*{modified}{% For the sake of convenience, in the case where our input is a trie $\boldsymbol{T}$, then we consider its \emph{reversed trie} where the path labels are read in the leaf-to-root direction. On the other hand, the trie-based data structures (namely position heaps) we build for input strings and reversed tries are usual tries where the path labels are read in the root-to-leaf direction. }% For each (reversed) path $(\mathbf{x}, \mathbf{y})$ in $\boldsymbol{T}$ such that $\mathbf{y} = \mathsf{anc}(\mathbf{x}, j)$ with $j = |\mathsf{depth}(\mathbf{x})|-|\mathsf{depth}(\mathbf{y})|$, let $\mathsf{str}(\mathbf{x},\mathbf{y})$ denote the string obtained by concatenating the labels of the edges from $\mathbf{x}$ to $\mathbf{y}$. For any node $\mathbf{x}$ of $\boldsymbol{T}$, let $\mathsf{str}(\mathbf{x}) = \mathsf{str}(\mathbf{x}, \mathbf{r})$. Let $N$ be the number of nodes in $\boldsymbol{T}$. We associate a unique \emph{id} to each node of $\boldsymbol{T}$. Here we use a bottom-up level-order traversal rank as the id of each node in $\boldsymbol{T}$, and we sometimes identify each node with its id. For each node id $i$~($1 \leq i \leq N$) let $\boldsymbol{T}[i..] = \mathsf{str}(i)$, i.e., $\boldsymbol{T}[i..]$ is the path string from node $i$ to the root $\mathbf{r}$. \subsection{Cartesian-tree Pattern Matching} The \emph{Cartesian tree} of a string $S$, denoted $\mathsf{CT}(S)$, is the rooted tree with $|S|$ nodes which is recursively defined as follows: \begin{itemize} \item If $|S| = 0$, then $\mathsf{CT}(S)$ is the empty tree. \item If $|S| \geq 1$, then $\mathsf{CT}(S)$ is the tree whose root $r$ stores the left-most minimum value $S[i]$ in $S$, namely, $r = S[i]$ iff $S[i] \leq S[j]$ for any $i \neq j$ and $S[h] > S[i]$ for any $h < i$. The left-child of $r$ is $\mathsf{CT}(S[1..i-1])$ and the right-child of $r$ is $\mathsf{CT}(S[i+1..|S|])$. \end{itemize} The \emph{parent distance encoding} of a string $S$ of length $n$, denoted $\mathsf{PD}(S)$, is a sequence of $n$ integers over $[0..n-1]$ such that \[ \mathsf{PD}(S)[i] = \begin{cases} i - \max_{1 \leq j < i} \{j \mid S[j] \leq S[i]\} & \mbox{if such $j$ exists}, \\ 0 & \mbox{otherwise.} \end{cases} \] Namely, $\mathsf{PD}(S)[i]$ represents the distance to from position $i$ to its nearest left-neighbor position $j$ that stores a value that is less than or equal to $S[i]$. A tight connection between $\mathsf{CT}$ and $\mathsf{PD}$ is known: \begin{lemma}[\cite{SongGRFLP21}] \label{lem:CT-PD} For any two strings $S_1$ and $S_2$ of equal length, $\mathsf{CT}(S_1) = \mathsf{CT}(S_2)$ iff $\mathsf{PD}(S_1) = \mathsf{PD}(S_2)$. \end{lemma} For two strings $S_1$ and $S_2$, we write $S_1 \approx S_2$ iff $\mathsf{CT}(S_1) = \mathsf{CT}(S_2)$ (or equivalently $\mathsf{PD}(S_1) = \mathsf{PD}(S_2)$). We also say that $S_1$ and $S_2$ \emph{ct-match} when $S_1 \approx S_2$. See Fig.~\ref{fig:CT_PD} for a concrete example. \begin{figure}[tb] \centerline{ \includegraphics[scale=0.4]{cartesian_tree_s1.pdf} \hfil \includegraphics[scale=0.4]{cartesian_tree_s2.pdf} } \caption{Two strings $S_1 = \mathtt{316486759}$ and $S_2 = \mathtt{713286945}$ ct-match since $\mathsf{CT}(S_1) = \mathsf{CT}(S_2)$ and $\mathsf{PD}(S_1) = \mathsf{PD}(S_2)$. } \label{fig:CT_PD} \end{figure} We consider the indexing problems for Cartesian-tree pattern matching on a text string and a text trie, which are respectively defined as follows: \begin{problem}[Cartesian-Tree Pattern Matching on Text String] \label{prob:string} \begin{description} \item[Preprocess:] A text string $S$ of length $n$. \item[Query:] A pattern string $P$ of length $m$. \item[Report:] All text positions $i$ such that $S[i..i+m-1] \approx P$. \end{description} \end{problem} \begin{problem}[Cartesian-Tree Pattern Matching on Text Trie] \label{prob:trie} \begin{description} \item[Preprocess:] A text trie $\boldsymbol{T}$ with $N$ nodes. \item[Query:] A pattern string $P$ of length $m$. \item[Report:] All trie nodes $i$ such that $(\boldsymbol{T}[i..])[1..m] \approx P$. \end{description} \end{problem} \subsection{Sequence Hash Trees} Let $\mathcal{W} = \langle w_1, \ldots, w_k \rangle$ be a sequence of non-empty strings such that for any $1 < i \leq k$, $w_i \notin \mathsf{Prefix}(w_j)$ for any $1 \leq j < i$. The \emph{sequence hash tree}~\cite{coffman} of a sequence $\mathcal{W} = \langle w_1, \ldots, w_k \rangle$ of $k$ strings, denoted $\mathsf{SHT}(\mathcal{W}) = \mathsf{SHT}(\mathcal{W})^{k}$, is a trie structure that is incrementally built as follows: \begin{enumerate} \item $\mathsf{SHT}(\mathcal{W})^0 = \mathsf{SHT}(\langle \ \rangle)$ for the empty sequence $\langle \ \rangle$ is the tree only with the root. \item For $i = 1, \ldots, k$, $\mathsf{SHT}(\mathcal{W})^i$ is obtained by inserting the shortest prefix $u_{i}$ of $w_i$ that does not exist in $\mathsf{SHT}(\mathcal{W})^{i-1}$. This is done by finding the longest prefix $p_i$ of $w_i$ that exists in $\mathsf{SHT}(\mathcal{W})^{i-1}$, and adding the new edge $(p_i, c, u_i)$, where $c = w_i[|p_{i}|+1]$ is the first character of $w_i$ that could not be traversed in $\mathsf{SHT}(\mathcal{W})^{i-1}$. \end{enumerate} Since we have assumed that each $w_i$ in $\mathcal{W}$ is not a prefix of $w_j$ for any $1 \leq j < i$, the new edge $(p_{i}, c, u_{i})$ is always created for each $1 \leq i \leq k$. This means that $\mathsf{SHT}(\mathcal{W})$ contains exactly $k+1$ nodes (including the root). To perform pattern matching queries efficiently, each node of $\mathsf{SHT}(\mathcal{W})$ is augmented with the \emph{maximal reach pointer}. For each $1 \leq i \leq k$, let $u_i$ be the newest node in $\mathsf{SHT}(\mathcal{W})^{i}$, namely, $u_i$ is the shortest prefix of $w_i$ which did not exist in $\mathsf{SHT}(\mathcal{W})^{i-1}$. Then, in the complete sequence hash tree $\mathsf{SHT}(\mathcal{W}) = \mathsf{SHT}(\mathcal{W})^k$, we set $\mathsf{mrp}(u_i) = u_j$ iff $u_j$ is the deepest node in $\mathsf{SHT}(\mathcal{W})$ such that $u_j$ is a prefix of $w_i$. Intuitively, $\mathsf{mrp}(u_i)$ represents the last visited node $u_j$ when we traverse $w_i$ from the root of the complete $\mathsf{SHT}(\mathcal{W})$. Note that $j \geq i$ always holds. When $j = i$ (i.e. when the maximal reach pointer is a self-loop), then we can omit it because it is not used in the pattern matching algorithm.
{'timestamp': '2021-08-17T02:09:10', 'yymm': '2106', 'arxiv_id': '2106.01595', 'language': 'en', 'url': 'https://arxiv.org/abs/2106.01595'}
arxiv
\section*{Acknowledgments} We thank the anonymous reviewers for their helpful comments. \clearpage \section{Appendices} \subsection{Modified Wagner-Fischer algorithm} \label{wagner-fischer} The modified Wagner-Fischer algorithm gets the source word $S$ of length $n$ and the target word $T$ of length $m$ as inputs and performs the following operations in a run-time $O(mn)$. \begin{enumerate} \item Initialize distance matrix $\mathbf{D}$ of size $(m+1) \times (n+1)$ with zeros \item For $i\in [1,m+1]$ do: $\mathbf{D_{i,1}}\gets i-1$ \item Initialize a set-valued start matrix $\mathbf{M}$ of the same size as $\mathbf{D}$ with empty sets. \item For $j\in [1,n+1]$ do: $\mathbf{M_{1,j}}\gets \text{Set}\{j-1\}$ \item For $i\in [1,m+1]$ and $j\in [1,n+1]$ do: \begin{itemize} \item Use previous entries of $D$ to calculate total cost of getting to $(i,j)$ with the edit distance operations: \begin{itemize} \item Insertion: $\mathbf{D_{i-1,j}}+1$ \item Substitution: $\mathbf{D_{i-1,j-1}}+1$ \item Deletion: $\mathbf{D_{i,j-1}}+1$ \item Swap: $\mathbf{D_{i-2,j-2}}+1$ \item If $T_i=S_j$ then no operation cost: $\mathbf{D_{i-1,j-1}}$ \end{itemize} \item Enter the lowest cost from the edit distance operations into $\mathbf{D_{i,j}}$ \item Update $\mathbf{M_{i,j}}$ by merging the set with the set-valued entries of $\mathbf{M}$ that led to $(i,j)$ with lowest cost \end{itemize} \item Initialize empty list $L$ \item Store lowest entry of $\mathbf{D_{m+1}}$ as $c$ and for $j\in [1,n+1]$ do \begin{itemize} \item If $\mathbf{D_{m+1,j}=c}$ do: For $m\in\mathbf{M_{m+1,j}}$ do: Add a 2-tuple $(m,j)$ into L. \end{itemize} \item Return $c$,$L$ \end{enumerate} \subsection{Visual and Phonetic attacks} \label{app:vis_phon} \paragraph{Visual attacks.} In the BERT-Defense{} full-distance pipeline, we exploit visual similarity (see appendix \ref{vis-sim}). The visual attacks implemented in \cite{benz} are also based on visual similarity. To avoid attacking with the same method that we defend with, we decided to use VIPER-DCES \cite{viper} instead. VIPER-DCES exchanges characters based on similarity of the descriptions from the Unicode 11.0.0 final names list (e.g. LATIN SMALL LETTER A for the character `a'). \paragraph{Phonetic attacks.} The phonetic embeddings implemented in \citet{benz} do not consistently produce phonetic attacks of sufficient quality. Thus, we used a many-to-many aligner \cite{m2m,eger2015we} together with the CMU Pronouncing Dictionary (cmudict) \cite{cmudict} and a word frequency list to calculate statistics for the correspondence between letters and phonemes. To attack a word, we convert the word to phonemes using cmudict and then convert it back to letters by sampling from the statistics. The perturbation probability $p$ for this attack controls the sampling temperature which describes how likely it is to sample letters that less frequently correspond to the phoneme in question. Using this method, we generate high-quality phonetically attacked sentences such as the one in Table \ref{tab:adv_attacks}. \subsection{Visual similarity} \label{vis-sim} We calculate the visual similarity of 30000 Unicode characters to 26 letters and 10 numbers. Each glyph is drawn with Python's pillow library \cite{pillow} in 20pt using a fitting font from the google-Noto font collection. The bitmap is then cropped to contain only the glyph. Then the image is resized and padded on the right and bottom to be of size $30px\times 30px$. When comparing the bitmap of a unicode glyph image and a letter/number glyph, multiple versions of the letter/number bitmap are created. For letters, the lowercase as well as the uppercase versions of each letter are taken. The bitmap gets downsized to 5 different sizes between $30px\times 30px$ and $15px\times 15px$, rotated and flipped in all 8 unique ways and then padded to $30px\times 30px$ again, such that the glyph is either placed at the top-left or the bottom left. See Figure \ref{fig:h_versions} for an example. \begin{figure}[!t] \centering \includegraphics[width=1\columnwidth]{graphics/h_versions.png} \caption{Different orientations/scales used for the letter h. The version that matches a Unicode character the best is used to calculate their similarity.} \label{fig:h_versions} \end{figure} The percentage of matching black pixels between bitmaps are calculated and the highest matching percentage of all version becomes the similarity score $S$. The substitution cost between two characters will then be calculated based on the similarity with the equation $\textit{cost}=\max{(0,\min{(1,(0.8-S)*3)})}$. The parameters of this equation have been tuned, so that highly similar characters have a in very low substitution costs while weakly similar characters have next to no reduced in substitution cost. \subsection{Parameters, runtime and computing infrastructure} All experiments where run on a single machine using an Intel(R) Core(TM) i7-4790K processor and a Nvidia GeForce GTX 1070 Ti graphics card. The restoration of a single sentence in the experiments took on average 0.1 seconds using ScRNN Defense, 1.34 seconds for Pyspellchecker and 8 seconds for BERT-defense. In total, $\text{BD}_{agn}$ includes 5 free parameters, most of them controlling the temperature of the used softmax operation to ensure good relative weighting of the probability distributions. The parameter values are shown in Table \ref{tab:parameters}. All additional parameters for $\text{BD}_{spec}$ have been described in \S\ref{sec:lev}. \begin{table}[!h] \begin{tabularx}{\columnwidth}{l X} \toprule \textbf{Parameter} & \textbf{Value} \\ \hline \makecell[l]{Softmax temperature for \\ context-independent hypothesis} & 10 \\ \hline \makecell[l]{Softmax temperature for\\ context-independent word-probabilities} & 1 \\ \hline Softmax temperature for BERT & 0.25 \\ \hline Softmax temperature for GPT & 0.005 \\ \hline Max number of hypothesis & 10\\ \bottomrule \end{tabularx} \caption{Parameters for BERT-Defense.} \label{tab:parameters} \end{table} \begin{table}[!h] \centering \noindent \begin{tabularx}{\linewidth}{@{}>{\bfseries}p{2.8cm}@{\hspace{.5em}}X@{}} \toprule Attacked & theensuing battls abd airstrikes killed at peast 10 militqnts.\\ Ground-truth & the ensuing battle and airstrikes killed at least 10 militants. \\ \midrule $\mathbf{BD_{agn}}$ & the ensuing battle and air strikes killed at least 10 militants. \\ $\mathbf{BD_{spec}}$ & the ensuing battle and air strikes killed at least 10 militants. \\ ScRNN Defense & tunney battls and airstrikes killed at past 10 militqnts. \\ Pyspellchecker & theensuing battle abd airstrips killed at past 10 militants\\\bottomrule Attacked & \includegraphics[width=0.6\columnwidth,valign=b]{graphics/attacked_example.png}\\ Ground-truth & No, you don't need to have taken classes or earned a degree in your area. \\ \midrule $\mathbf{BD_{agn}}$ & no, you do ,' nee ,' not besides of never a degree, you are. \\ $\mathbf{BD_{spec}}$ & no, you do no' need to have taken classes or have a degree in your area. \\ ScRNN Defense & , yu so to nerve to era knaet access of need a degree ïn your areă. \\ Pyspellchecker & \includegraphics[width=0.6\columnwidth,valign=b]{graphics/pyspellchecker_example.png}\\ \bottomrule Attacked & A man ix riding ;n s voat.\\ Ground-truth & A man is riding on a boat. \\ \midrule $\mathbf{BD_{agn}}$ & a man is riding in a boat. \\ $\mathbf{BD_{spec}}$ & a man is riding in a boat. \\ ScRNN Defense & a man imax riding on s voat. \\ Pyspellchecker & a man ix riding in s vote\\ \bottomrule \end{tabularx} \caption{Additional adversarial shielding examples on the rd:0.3,rd:0.3 dataset. } \label{tab:othercases} \end{table} \begin{table*}[!t] \centering \noindent \begin{tabularx}{\textwidth}{ |X||l|l|l|l|l|l|l|l| } \hline \textbf{Dataset} &\multicolumn{2}{c}{$\mathbf{BD_{agn}}$}&\multicolumn{2}{|c}{$\mathbf{BD_{spec}}$}&\multicolumn{2}{|c}{\textbf{Pyspellchecker}}&\multicolumn{2}{|c|}{\textbf{ScRNN Defense}}\\ \Xhline{2\arrayrulewidth} \textbf{Metric}&Mover&Editdist& Mover&Editdist&Mover&Editdist&Mover&Editdist\\\Xhline{2\arrayrulewidth} \textbf{vi:0.3}&0.696&5.04& 0.830&2.267&0.387&8.54&0.257&12.54\\\hline \textbf{tr:0.3}&0.778 &2.91&0.767 &3.14&0.605&3.34&0.386&7.25\\\hline \textbf{dv:0.3}&0.574 &9.27& 0.794&2.995& 0.335&9.53&0.379&9.48\\\hline \textbf{sg:0.3}&0.820 &2.02& 0.808&2.22&0.459&4.52&0.4&6.19\\\hline \textbf{is:0.3}& 0.539 &9.91& 0.842&2.767&0.44&9.26&0.520&7.04\\\hline \textbf{fs:0.3}& 0.399 &14.78& 0.688&3.227&0.310&14.41&0.277&16.12\\\hline \textbf{in:0.3}& 0.845 &1.9& 0.861&1.597&0.588&3.14&0.445&4.92\\\hline \textbf{kt:0.3}& 0.832 &1.96& 0.562&2.36&0.596&2.8&0.416&5.89\\\hline \textbf{nt:0.3}& 0.764 &3.38& 0.512&3.322&0.504&4.91&0.423&7.59\\\hline \textbf{ph:0.1}& 0.776 &3.21& 0.779&3.082&0.632&3.35&0.535&5.50\\\hline \textbf{ph:0.3}& 0.569 &8.77& 0.587&7.55&0.397&8.29&0.302&11.26\\\hline \textbf{ph:0.5}& 0.437 &13.25& 0.469&12.062&0.275&11.78&0.208&15.19\\\hline \textbf{ph:0.7}& 0.350 &16.37& 0.395&14.735&0.218&14.33&0.167&17.34\\\hline \textbf{ph:0.9}& 0.314 &18.45& 0.341&16.967&0.194&15.81&0.152&18.63\\\hline \textbf{sg:0.5,kt:0.3}& 0.701 &4.29& 0.537&4.47&0.23&7.07&0.158&10.25\\\hline \textbf{vi:0.3,in:0.3}& 0.627 &6.48& 0.679&2.467&0.172&13.73&0.14&15.75\\\hline \textbf{rd:0.3}& 0.676 &6.48& 0.650&3.485&0.44&7.25&0.375&8.91\\\hline \textbf{rd:0.3,rd:0.3}& 0.501 &11.49& 0.451&6.657&0.269&12.0425&0.232&13.92\\\hline \textbf{rd:0.6,rd:0.6}& 0.257 &22.30& 0.441&14.0&0.12&20.46&0.104&21.90\\ \hline \end{tabularx} \caption{Exact scores for the results shown in Figure \ref{fig:evaluations_baseline}.} \label{tab:exact_data} \end{table*} \section{Conclusion} We introduced BERT-Defense{}, a model that probabilistically combines context-independent word level information obtained from edit distance with context-dependent information from BERT's masked language modeling to combat low-level orthographic attacks. Our model does not train on possible error types but still substantially outperforms a spell-checker as well as the model of \citet{pruthi-etal-2019-combating}, which has been trained to shield against edit distance like attacks, on a comprehensive benchmark of cognitively inspired attack scenarios. We further show that our model rivals human crowd-workers supervised in a 3-shot manner. The generality of our approach allows it to be applied to a variety of different ``normalization'' problems, such as spelling normalization or OCR post-correction \citep{eger2016comparison} besides the adversarial attack scenario considered in this work, which we will explore in future work. We release our code and data at \url{https://github.com/yannikkellerde/BERT-Defense}. \section{Experimental Setup}\label{sec:experiments} To obtain adversarially attacked sentences against which to defend, we use the \citet{benz} benchmark Zéroe of low-level adversarial attacks. This benchmark contains implementations for a wide range of cognitively inspired adversarial attacks such as letter shuffling, disemvoweling, phonetic and visual attacks. The attacks are parameterized by a perturbation probability $p\in[0,1]$ that controls how strongly the sentence is attacked. We decided to slightly modify two of the attacks in Zéroe, the phonetic and the visual attacks. On close inspection, we found the phonetic attacks to be too weak overall, with too few perturbations per word. The visual attacks in Zeroé are based on pixel similarity which is similar to the visual similarity based defense in our \emph{domain-specific} model. Thus, to avoid attacking with the same method we defend with, we decided to switch to a description based visual attack model (DCES), just like in the original paper \citep{viper}.\footnote{Using description based defense and pixel based attacks would have been possible just as well, but we believe doing it reversely is consistent with the original specification in \citet{viper}.} Our modifications are described in Appendix \ref{app:vis_phon}. \paragraph{Evaluation} Instead of evaluating on a downstream task, we evaluate on the task of restoring the original sentences from the perturbed sentences. This allows us to easier compare to human performances. It also provides a more difficult test case, as a downstream classifier may infer the correct solution even with part of the input destroyed or omitted. Finally, being able to correct the input is also important when the developed tools would be used for humans, e.g., in spelling correction. We evaluate the similarity of the sentences to the ground-truth sentences with the following metrics: \begin{figure*}[!t] \centering \includegraphics[width=0.95\textwidth]{graphics/baseline_compare.pdf} \caption{Comparison between BERT-Defense{}, and the two baseline adversarial defense tools ``pyspellchecker'' and ``ScRNN defense''. The x-labels describe the attack and perturbation level the sentences were attacked with, before applying on of the adversarial defense methods. For conditions with two attack types, the perturbations were applied in order. For edit distance, lower is better. For the other metrics, higher is better. Exact values for the results are included in the appendix in Table \ref{tab:exact_data}.} \label{fig:evaluations_baseline} \end{figure*} \begin{enumerate}[topsep=5pt,itemsep=0pt,leftmargin=*] \item \textbf{Percent perfectly restored} (PPR). The percent of sentences that have been restored perfectly. This is a coarse-grained sentence-level measure. \item \textbf{Editdistance}. The Levenshtein (edit) distance measures the number of insertions, deletions, and substitutions necessary (on character-level) to transform one sequence into another. \item \textbf{MoverScore} \cite{MoverScore}. MoverScore measures the semantic similarity between two sentences using BERT. It has been show to correlate highly with humans as a semantic evaluation metric. \end{enumerate} For all of the metrics, letter case was ignored. \paragraph{Attack scenarios.} We sampled 400 sentences from the GLUE \cite{glue} STS-B development dataset for our experiments. We use various attack scenarios to attack the sentences: \begin{itemize}[topsep=5pt,itemsep=0pt,leftmargin=*] \item[i)] Each of the attack types of the Zéroe benchmark (see Table \ref{tab:adv_attacks}). We set $p=0.3$ throughout. \item[ii)] To evaluate how higher perturbation levels influence restoration difficulty, we create 5 attack scenarios for one attack scenario (we randomly chose phonetic attacks) with perturbation levels $p$ from $0.1$ to $0.9$. \item[iii)] We add combinations of attacks: these are performed by first attacking the sentence with one attack and then with another. \item[iv)] In Random attack scenarios (rd:0.3, [rd:0.3,rd:0.3], [rd:0.6,rd:0.6]), one or two attack types from the benchmark are randomly chosen for each sentence. These constitute stronger attack situations and may be seen as more challenging test cases. \end{itemize} Each of the 19 attack scenarios is applied to all 400 sentences individually to create 19 test cases of attacked sentences. \paragraph{Baselines and upper bounds.} To evaluate how well BERT-Defense{} restores sentences, we compare its sentence restoration ability to two baselines: (a) the \emph{Pyspellchecker} \cite{pyspellchecker}, a simple spellchecking algorithm that uses the Levenshtein distance and word frequency to correct errors in text; (b) ``ScRNN defense'' from the \citet{pruthi-etal-2019-combating} paper. This method uses an RNN that has been trained to recognize and fix character additions, swaps, deletions and keyboard typos. Further, as we use Zeroé, a cognitively inspired attack benchmark supposed to fool machines but not humans, it is especially interesting to see how BERT-Defense{} compares to human performance. Thus, (c) we include human performance, obtained from a crowd-sourcing experiment on Amazon Mechanical Turk (AMT). Note that humans are often considered upper bounds in such settings. \paragraph{Human experiment.} Twenty-seven subjects were recruited using AMT (21 male, mean age 38.37, std age 10.87) using PsiTurk \cite{psiTurk}. Participants were paid \$3 plus up to \$1 score based bonus (mean bonus 0.56, std bonus 0.40) for restoring about 60 adversarially attacked sentences. The task took on average 43.9 minutes with a standard deviation of 20.1. Twenty of the subjects where native English speakers, seven where non-native speakers. The two groups did not significantly differ regarding their edit distances to the true underlying sentences (unequal variance t-test, $p=.85$). We sampled 40 random sentences from nine of our attack scenarios plus 40 random (non-attacked) sentences from the original document. Each sentence was restored by four different humans. The whole set of 1600 sentences (10 scenarios times 40 sentences each times 4 repetitions) was then randomly split into 27 sets of about 60 sentences. No split contained the same sentence multiple times. Each of the 27 participants got one of these sets assigned. After a short instruction text, the participants where shown three examples of how to correctly restore a sentence (``3-shot learning''). Then they were shown the sentences in their set sequentially and entered their attempts at restoring the sentences into a text-field. \section{Introduction} Adversarial attacks to machine learning systems are malicious modifications of their inputs designed to fool machines into misclassification but not humans \citep{Goodfellow2014Explaining}. One of their goals is to expose blind-spots of deep learning models, which can then be shielded against. In the NLP community, typically two different kinds of attack scenarios are considered. ``High-level'' attacks paraphrase (semantically or syntactically) the input sentence \citep{Iyyer2018Adversarial,Alzantot2018Generating,Jin:2020} so that the classification label does not change, but the model changes its decision. \begin{figure}[!t] \centering \includegraphics[width=0.75\columnwidth]{graphics/overview.pdf} \caption{A high-level overview of the processing of an example sentence in our adversarial-defense pipeline. The sentences shown for the hypothesis have been created by choosing the maximum of their associated probability distributions over words. } \label{fig:overview} \end{figure} Often, this is framed as a search problem where the attacker has at least access to model predictions \citep{zang-etal-2020-word}. ``Low-level'' attackers operate on the level of characters and may consist of adversarial typos \citep{Belinkov2017synthetic,Ebrahimi2018OnAdversarial,pruthi-etal-2019-combating,jones-etal-2020-robust} or replacement of characters with similarly looking ones \citep{viper,Li:TextShield}. Such attacks may also be successful when the attacker operates in a blind mode, without having access to model predictions, and they are arguably more realistic, e.g., in social media. However, \citet{pruthi-etal-2019-combating} showed that orthographic attacks can be addressed by placing a spelling correction module in front of a downstream classifier, which may be considered a natural solution to the problem.\footnote{One could argue that such a pipeline solution is not entirely satisfactory from a more theoretical perspective, and that downstream classifiers should be innately robust to attacks in the same way as humans.} In this work, we apply their approach to the recently proposed benchmark \emph{Zéroe} of \citet{benz}, illustrated in Table \ref{tab:adv_attacks}, which provides an array of cognitively motivated orthographic attacks, including missing word segmentation, phonetic and visual attacks. We show that the spelling correction module of \citet{pruthi-etal-2019-combating}, which has been trained on simple typo attacks such as character swaps and character deletions, fails to generalize to this benchmark. This motivates us to propose a novel technique to addressing various forms of orthographic adversaries that does not require to train on the low-level attacks: first, we obtain probability distributions over likely true underlying words from a dictionary using a context-independent extension of the Levenshtein distance; then we use the masked language modeling objective of BERT, which gives likelihoods over word substitutions in context, to refine the obtained probabilities. We iteratively repeat this process to improve the word context from which to predict clean words. Finally, we apply a source text independent language model to produce fluent output text. \textbf{Our contributions:} \textbf{(i)} We empirically show that this approach performs much better than the trained model of \citet{pruthi-etal-2019-combating} on the Zéroe benchmark. Furthermore, \textbf{(ii)} we also evaluate human robustness on Zéroe and \textbf{(iii)} demonstrate that our iterative approach, which we call BERT-Defense{}, sometimes even outperforms human crowd-workers trained via 3-shot learning. \begin{table}[!t] \centering \begin{tabular}{l l} \toprule \textbf{Attacker} & \textbf{Sentence} \\\midrule inner-shuffle & A man is drnviig a car.\\\hline full-shuffle & A amn is ginvdir a acr. \\\hline disemvowel & A mn is drvng a cr.\\\hline intrude & A ma\#n i*s driving a ca\^{}r. \\\hline keyboard-typo & A mwn is dricing a caf. \\\hline natural-typo & A wan his driving as car. \\\hline truncate & A man is drivin a car. \\\hline segmentation & Aman isdriving a car. \\\hline phonetic & Ae man izz dreyvinn a cahar.\\\hline visual & \includegraphics[width=0.45\columnwidth,valign=b]{graphics/visual.pdf} \\\bottomrule \end{tabular} \caption{Examples for the adversarial attacks from the Zéroe benchmark. The phonetic and visual examples show our modified implementations (see appendix \ref{app:vis_phon}).} \label{tab:adv_attacks} \end{table} \section{Methods} Our complete model, which is outlined in Figure \ref{fig:overview} on a high level, has three intuitive components. The first component is context-independent and tries to detect the tokens in a sentence from their given (potentially perturbed) surface forms. This makes sense, since we assume orthographic low-level attacks on our data. The second component uses context, via masked language modeling in BERT, to refine the probability distributions obtained from the first step. The third component uses a language model (in our case, GPT) to make a choice between multiple hypotheses. In the following, we describe each of the three components. \subsection{Context-independent probability} \label{sec:lev} In the first step of our sentence restoration pipeline, we use a modified Levenshtein distance to convert the sentence into a list of probability distributions over word-piece tokens from a dictionary $D$. For the dictionary, we choose BERT's \cite{bert} default word-piece dictionary. We begin by splitting the attacked sentence $S$ at spaces into word tokens $\tilde{w}_i$. However, to be able to use our word-piece dictionary $D$, we need to find the appropriate segmentation of the tokens into word-pieces. \paragraph{Modified Levenshtein distance.} We developed a modified version of the Wagner–Fischer algorithm \cite{wagner_fischer} that calculates a Levenshtein distance to substrings of the input string and keeps track of start as well as end indices of matching substrings. For each $\tilde{w}_{i}$ in $S$, this algorithm (which is described in Appendix \ref{wagner-fischer}) calculates the substring Levenshtein distance \emph{dist} to every word-piece $w_{d}$ in $D$. \paragraph{Segmentation hypothesis.} We store the computed distances $\textit{dist}(\tilde{w}_{i},w_d)$ in a dictionary $C_i$ that maps each start-index $s$ and end-index $e$ to a list of distances, i.e., $C_i$ associates \begin{align*} (s,e)\mapsto \bigl(\textit{dist}(\tilde{w}_{i},w_{d})\bigr)_{w_{d}\in D'} \end{align*} Here, $D'$ selects the subset of all word-pieces in $D$ that match $\tilde{w}_{i}$ at the substring between $s$ and $e$. Using $C_i$, we can then perform a depth-first search to compose $\tilde{w}_{i}$ from start and end-indices in $C_i$. For example, a 10 character word $\tilde{w}_{i}$ could be segmented into two words-pieces that match the substrings from positions 1-5 and 6-10, respectively, or a single word that matches from 1-10. Let $\mathbf{c}_{i}$ be the set of all segmentations of $\tilde{w}_{i}$ from start and end indices. For example, $\mathbf{c}_i$ could be $\bigl\{\bigl((1,5),(6,10)\bigr),\,\bigl((1,10)\bigr)\bigr\}$. For each segmentation $\mathbf{c}_{i,\alpha}\in \mathbf{c}_i$, we then calculate a \emph{total distance} $d(\mathbf{c}_{i,\alpha})$ as a sum of the minimum distances of all parts: \begin{align}\label{eq:tdist} d(\mathbf{c}_{i,\alpha}) = \sum_{k=1}^{\text{len}(\mathbf{c}_{i,\alpha})}\min(C_i[\mathbf{c}_{i,\alpha,k}]) \end{align} Using the total distances to segment each token $\tilde{w}_{i}$, we can now create hypotheses $\mathbf{H}$ about how the whole sentence $S$ consisting of $n$ tokens should be segmented into word-pieces. For this, we calculate the Cartesian product between the sets of possible segmentations for each word $\tilde{w}_{i}$, $i=1,\ldots,n$: \begin{align*} \mathbf{H} = \mathbf{c}_1\times \mathbf{c}_2\times \cdots \times \mathbf{c}_n \end{align*} We set the \emph{loss} of one hypothesis $\mathbf{h}=(\mathbf{c}_{1,\alpha_1},\ldots,\mathbf{c}_{n,\alpha_n}) \in \mathbf{H}$ as the sum of the total distances of its parts that we calculated in Eq.~\eqref{eq:tdist} \begin{align*} \textit{loss}(\mathbf{h}) = \sum_{i=1}^n d(\mathbf{c}_{i,\alpha_i}) \end{align*} By evaluating the softmax on the negative total distances of the hypothesis, we calculate probabilities if a hypothesis $\mathbf{h}_v\in \mathbf{H}$ is equal to the true (unknown) segmentation $\mathbf{h}^{*}$ of the $n$ tokens: \begin{equation} \label{eq:seg_prob} \begin{split} \mathbf{d}_\mathbf{H} &= (\textit{loss}(\mathbf{h}))_{\mathbf{h}\in \mathbf{H}}\\ \mathbf{P}(\mathbf{h}_v{=}\mathbf{h}^{*}\mid S) &= [\text{softmax}(-\mathbf{d_H})]_v \end{split} \end{equation} We will refer back to these probabilities in \S\ref{sec:gpt}. \paragraph{Word probability distributions.} In a hypothesis $\mathbf{h}\in\mathbf{H}$, a token $\tilde{w}_{i}$ has a single segmentation of start and end indices associated with it, $\mathbf{c}_{i,\alpha}$. For all start- and end-indices $(s,e)$, $C_i[s,e]$ stores the distances of the words that match $\tilde{w}_i$ between $s$ and $e$. Let $D'$ again be the dictionary containing all those words. Let $w_{d}$ be a word-piece in $D'$ and let $w^{*}\in D'$ be the true match for the substring between $s$ and $e$ of $\tilde{w}_i$. Then, we can compute a context-independent probability that $w_{d}$ is equal to $w^{*}$, by evaluating the softmax on the negative distances stored in $C_i$: \begin{align*} \mathbf{P_h}(w_{d}=w^{*}\mid \tilde{w}) = [\text{softmax}(-C_i[s,e])]_d \end{align*} When we do this for all words in $\mathbf{h}$ and concatenate the results, we get a vector $\mathbf{V_h}$ of probability distributions over dictionary word-pieces. This is illustrated in Figure \ref{fig:prob_no_context}. We introduce the following notation to select a probability distribution based on its index in $\mathbf{h}$ using the subscript $j$: \begin{align*} \mathbf{P}_{\mathbf{h},j}(w_d=w^{*}\mid \tilde{w}) \coloneqq \mathbf{V}_{\mathbf{h},j} \end{align*} \begin{figure}[!t] \centering \includegraphics[width=1\columnwidth]{graphics/context_independent.pdf} \caption{A context independent probability distribution over words calculated for an example input sentence. There are multiple segmentation-hypothesis associated with the sentence that each consist of a sequence of probability distributions over word-tokens.} \label{fig:prob_no_context} \end{figure} \paragraph{Domain-specific distance.}In the remainder, we will refer to the way of calculating the substring distance as described above as \emph{attack-agnostic{}}. Beyond this, we also aim to leverage domain-specific knowledge. We refer to such an augmented distance as the \emph{domain-specific{}} distance $\textit{dist}_M$. Here, we modify the operation costs in the substring Levenshtein distance in certain situations. \begin{enumerate} \item Edit distance is reduced for visually similar characters. This builds on visual character representations \citep{viper}. See appendix \ref{vis-sim} for details. \item Addressing intruder attacks, we reduce deletion costs depending on the frequency $f$ of the character in the source word. Our assumption is that the same intruder symbol may be repeated in one word. Thus, we decay the cost exponentially for increasing frequency using the formula $0.75^{f-1}$. \item Vowel insertion cost is reduced to 0.3 for words that contain no vowels. \end{enumerate} To address letter-shuffling, we additionally compute an anagram distance of how close the attacked word $\tilde{w_i}$ is to being an anagram to the dictionary word $w_d$. Let $m$ be the number of characters that are in one of the two words, but not in the other. Then, our anagram distance $\textit{dist}_{\text{A}}$ computes to \begin{align*} \textit{dist}_{\text{A}}(\tilde{w_i},w_d) = 2m+1 \end{align*} When two words are permutations of each other, the anagram distance is minimal and otherwise it increases linearly in the number of different characters between the two words. We then take the minimum of the anagram distance and the substring Levenshtein distance with modified operation costs $\textit{dist}_\text{M}$ to obtain the \emph{domain-specific{}} $\textit{dist}_\text{F}$: \begin{align*} \textit{dist}_{\text{F}}(\tilde{w_i},w_d) = \min(\textit{dist}_{\text{A}}(\tilde{w_i},w_d),\textit{dist}_{\text{M}}(\tilde{w_i},w_d)) \end{align*} \subsection{Context-dependent probability using BERT} \label{sec:bert} \begin{figure}[!t] \centering \includegraphics[width=1\columnwidth]{graphics/bert_posterior.pdf} \caption{Iterative, context-based improvements of the word predictions using BERT for masked LM. Each iteration, a different token will be masked. We calculate context-dependent probabilities using Eq. \eqref{eq:softmax} and integrate them with our context-independent probabilities in Eq. \eqref{eq:update}.} \label{fig:bert_posterior} \end{figure} In the following, we describe the context-based improvement for a single hypothesis $\mathbf{h}\in \mathbf{H}$. In Figure \ref{fig:bert_posterior}, the whole process is illustrated for an example sentence. The number of required iterations should scale linearly with the amount of tokens in the hypothesis, so we perform $2\cdot|\mathbf{h}|$ iterations in total. To perform one improvement iteration, we perform the following steps: \noindent 1) Select an index $j$, of a token, that will be masked for this iteration. \noindent 2) For the next part, we slightly modify BERT for masked LM. Instead of using single tokens as inputs as in BERT, we want to use our context-independent probability distributions over word-piece tokens. Thus, for each token $w_{\mathbf{h},j}$ in $\mathbf{h}$, we embed all relevant tokens $w_d$ from the context-independent process described above using BERT's embedding layer and combine them into a weighted average embedding using weights $\mathbf{P}_{\mathbf{h},j}(w_{d}=w^{*}\mid \tilde{w})$. \noindent 3) We now bypass BERT's embedding layer and feed the weighted average embeddings and the embedding for the mask token directly into the next layers of BERT\footnote[1]{Although BERT has only been trained on the single token embeddings, we empirically found that feeding in averaged embeddings produces very sensible results.}. As a result, BERT provides us with a vector of scores $\mathbf{S_{\text{BERT}}}$ for how well the words from the word-piece dictionary $D$ fit into the position of the masked word. \noindent 4) By applying the softmax on these scores, we obtain a new probability distribution over word-pieces which is dependent on the context $c$ of the token at position $j$: \begin{equation}\label{eq:softmax} \mathbf{P}_{\mathbf{h},j}(w_{d}=w^{*}\mid c)=[\text{softmax}(\mathbf{S_{\text{BERT}}})]_d \end{equation} 5) We make the simplifying assumption that each word is attacked independently from the other words. Thus, the context $c$ is independent of the attack on the word $\tilde{w}$. This means that the following equality holds: \begin{equation}\label{eq:update} \begin{split} \mathbf{P}_{\mathbf{h},j}&(w_{d}=w^{*}\mid \tilde{w},c) =\\ &\mathbf{P}_{\mathbf{h},j}(w_{d}=w^{*}\mid \tilde{w})\mathbf{P}_{\mathbf{h},j}(w_{d}=w^{*}\mid c) \end{split} \end{equation} 6) We go back to step 1) and use $\mathbf{P}_{\mathbf{h},j}(w_d=w^{*}\mid \tilde{w},c)$ from Eq.~\eqref{eq:update} instead of $\mathbf{P}_{\mathbf{h},j}(w_d=w^{*}\mid \tilde{w})$ to create the average embedding at position $j$. \subsection{Selecting the best hypothesis with GPT} \label{sec:gpt} After performing the context-based improvements, we are left with multiple hypothesis $\mathbf{h}\in \mathbf{H}$. Each of them has a hypothesis probability $\mathbf{P}(\mathbf{h}{=}\mathbf{h^*}\mid S)$ and a list of word-piece probabilities of length $|\mathbf{h}|$ over dictionary words associated with it. Now, we finally collapse the probability distributions by taking the argmax to form actual sentences $S_\mathbf{h}$: \begin{equation} \begin{split} w_{\mathbf{h},j} &\gets \argmax_{w_d}(\mathbf{P}_{\mathbf{h},j}(w_d=w^{*}\mid \tilde{w},c))\\ S_\mathbf{h} &\gets (w_{\mathbf{h},j})_{j=1}^{|\mathbf{h}|} \end{split} \end{equation} This allows us to use GPT \cite{gpt} to calculate a language modeling (perplexity) score $\text{LM}_{S_\mathbf{h}}$ for each sentence. Using softmax, we again transform these scores into a probability distribution that describes the probability of a segmentation hypothesis $\mathbf{h}_v\in \mathbf{H}$ being the correct segmentation $\mathbf{h^*}$, based on the restored sentences $S_\mathbf{H}$: \begin{align*} S_\mathbf{H} &\gets (S_\mathbf{h})_{\mathbf{h}\in\mathbf{H}}\\ \text{LM}_{S_\mathbf{H}} &\gets (\text{LM}_{S_\mathbf{h}})_{\mathbf{h}\in\mathbf{H}}\\ \mathbf{P}(\mathbf{h}_v{=}\mathbf{h^*}\mid S_\mathbf{H}) &= [\text{softmax}(\text{LM}_{S_\mathbf{H}})]_v \end{align*} The original probability $\mathbf{P}(\mathbf{h}_v{=}\mathbf{h^*}\mid S)$ assigned to each hypothesis is only based on the results of the Levenshtein distance for the attacked sentence $S$. Thus, as $\mathbf{P}(\mathbf{h}_v{=}\mathbf{h^*}\mid S)$ only depends on the character-level properties of the attacked sentence and $\mathbf{P}(\mathbf{h}_v{=}\mathbf{h^*}\mid S_\mathbf{H})$ only depends on the semantic properties of the underlying sentences, it makes sense to assume that these distributions are independent. This allows us to simply multiply them, to get a probability distribution that captures semantic as well as character-level properties: \begin{equation} \label{eq:mult_gtp_probs} \begin{split} \mathbf{P}(\mathbf{h}_v{=}\mathbf{h^*}\mid S_\mathbf{H},S) &=\\ \mathbf{P}(\mathbf{h}_v{=}&\mathbf{h^*}\mid S_\mathbf{H})\mathbf{P}(\mathbf{h}_v{=}\mathbf{h^*}\mid S) \end{split} \end{equation} In Figure \ref{fig:gpt}, we visualize the above described process for a specific example with only 2 hypotheses. \begin{figure}[!t] \centering \includegraphics[width=1\columnwidth]{graphics/GPT.pdf} \caption{An example of how we use OpenAI GPT to decide on which hypothesis to choose as our final sentence prediction. The original probability of the segmentation hypothesis calculated in Eq. \eqref{eq:seg_prob} is multiplied with a probability calculated from the language modeling score using Eq. \eqref{eq:mult_gtp_probs}.} \label{fig:gpt} \end{figure} \section{Related work} \citet{zeng2020openattack} classify adversarial attack scenarios in terms of the \emph{accessibility} of the victim model to the attacker:\footnote{Another recent survey of adversarial attacks in NLP is provided by \citet{roth2021token}.} \emph{white-box} attackers \citep{Ebrahimi2018Hotflip} have full access to the victim model including its gradient to construct adversarial examples. In contrast, \emph{black-box} attackers have only limited knowledge of the victim models: score- \citep{Alzantot2018Generating,Jin:2020} and decision-based attackers \citep{Ribeiro2018Semantically} require access to the victim models' prediction scores (classification probabilities) and final decisions (predicted class), respectively. A score-based black-box attacker of particular interest in our context is BERT-ATTACK \citep{bert-attack}. BERT-ATTACK uses the masked language model (MLM) of BERT to replace words with other words that fit the context. BERT-ATTACK is related to our approach because it uses BERT's MLM in an attack-mode while we use it in defense-mode. Further, in our terminology, BERT-ATTACK is a high-level attacker, while we combine BERT with an edit distance based approach to restore low-level adversarial attacks. \emph{Blind} attackers make fewest assumptions and have no knowledge of the victim models at all. Arguably, they are most realistic, e.g., in the context of online discussion forums and other forms of social media where users may not know which model is employed (e.g.) to censor toxic comments and users may also not have (large-scale) direct access to model predictions. In terms of blind attackers, \citet{viper} design the visual perturber VIPER which replaces characters in the input stream with visual nearest neighbors, an operation to which humans are seemingly very robust.\footnote{Basing text processing on visual properties was also recently explored in \citet{wang2020word} and \citet{salesky:2021}.} \citet{benz} propose a canon of 10 cognitively inspired orthographic character-level blind attackers. We use this benchmark, which is illustrated in Table \ref{tab:adv_attacks}, in our application scenario. While \citet{viper} and \citet{benz} are only moderately successful in defending against their orthographic attacks with \emph{adversarial learning} \citep{Goodfellow2014Explaining} (i.e., including perturbed instances at train time), \citet{pruthi-etal-2019-combating} show that placing a word recognition (correction) module in front of a downstream classifier may be much more effective. They use a correction model trained to recognize words corrupted by random adds, drops, swaps, and keyboard mistakes. \citet{zhou-etal-2019-learning} also train on the adversarial attacks (insertion, deletion, swap as well as word-level) against which they defend. In contrast, we show that an \emph{untrained} attack-agnostic iterative model based on BERT may perform competitively even with humans (crowd-workers) and that this correction module may further be improved by leveraging attack-specific knowledge. \citet{jones-etal-2020-robust} place an encoding module---which should map orthographically similar words to the same (discrete) `encoding'---before the downstream classifier to improve robustness against adversarial typos. However, in contrast to \citet{pruthi-etal-2019-combating} and BERT-Defense{}, their model does not restore the attacked sentence to its original form so that it is less desirable in situations where knowing the underlying surface form may be relevant (e.g., for human introspection or in tasks such as spelling normalization). In contemporaneous work, \citet{hu2021misspelling} use BERT for masked language modeling together with an edit distance to correct a misspelled word in a sentence. They assume a single misspelled word that they correct by selecting from a set of edit distance based hypotheses using BERT. In contrast, in our approach we assume that multiple or even all words in the sentence have been attacked using adversarial attacks and that we do not know which ones. Then, we use an edit distance and integrate its results probabilistically with context information obtained by BERT, rather than using edit distance only for candidate selection. \section{Results and Discussion} \begin{figure*}[!h] \centering \includegraphics[width=0.8\textwidth]{graphics/human_compare.pdf} \caption{Comparison between BERT-Defense{} and humans on Amazon Mechanical Turk.} \label{fig:evaluations_human} \end{figure*} \paragraph{Comparison with baselines.} Figure \ref{fig:evaluations_baseline} visualizes the results (full results are in the appendix). $\text{BD}_{\text{agn}}$ (BERT-Defense{}, attack-agnostic{}) significantly outperforms both baselines regarding \emph{MoverScore} and \emph{PPR} for all random attack scenarios (p $\ll 0.01$, equal variance t-test). However, only $\text{BD}_{\text{spec}}$ (BERT-Defense{}, domain-specific{}) achieves a lower edit distance than the baselines. This discrepancy between the measures is explained by the fact that, by taking context into account, BERT-Defense{} searches for the best restoration in the space of sensible sentences, while \emph{Pyspellchecker} searches the best restoration for each word individually. Although \emph{ScRNN defense} uses an RNN and is able to take context into account, we found that it also mainly seems to restore the words individually and rarely produces grammatically correct sentences for strongly attacked inputs. Table \ref{tab:failure_cases}, which illustrates failure cases of all models, supports this. In the failure case when BERT-Defense{} fails to recognize the correct underlying sentence, BERT-Defense{} outputs a mostly different sentence that usually does make some sense, but has little in common with the ground-truth sentence. This results in much higher edit distances than the failure cases of the baselines which produce grammatically wrong sentences, while restoring individual words the best they can (this sometimes means not trying at all). Interestingly, humans tend to produce similar failure cases as BERT-Defense{}. When comparing the performance on specific attacks, we see a consistent margin of about 0.2 MoverScore and 15-35 percentage points PPR between $\text{BD}_{\text{agn}}$ and the baselines across all attacks. Exceptions include inner-shuffle, for which ScRNN-Defense is on par with $\text{BD}_{\text{agn}}$ and segmentation attacks, which hurt the performance of the baselines far more than the performance of BERT-Defense{}, which includes segmentation hypothesis as an essential part of its restoration pipeline. For $\text{BD}_{\text{spec}}$, we see gains for attacks where we leverage domain-specific knowledge. The biggest gains of around 0.25 MoverScore are achieved against full-shuffle, inner-shuffle and disemvoweling attacks. \begin{table*}[!htb] \centering {\small \begin{tabular}{l|lll} \toprule \textbf{Attacked Sentence} & \textbf{ScRNN} & \textbf{$\text{BD}_{\text{agn}}$}\\ \midrule To lorge doog's wronsing in sum grass. & to lorge doog's wronsing in sum grass. & two large dogs rolling in the grass. \\ Two large dogs runningin some grass. &two large dogs runningin some grass.&two large dogs running in some grass. \\ Tw large dogs rnnng in some grss.&throw large dogs running in some grss.&two large dogs running in some grass.\\ Two larg dog runnin in some grass.&two larg dog runnin in some grass.&a large dog running in some grass.\\ Twolarge dogs running income graas.&twolarge dogs running income graas.&two large dogs running into grass.\\ To lrg doog's rntng in sm gras ..&to long dogs ring in sm gras.&to the dogs running in the grass.\\ \bottomrule \end{tabular} } \caption{Various illustrative attacks on the sentence ``Two large dogs running in some grass.'' and restorations by ScRNN and BD$_{\text{agn}}$. The attacked sentences are attacked with the following attacks (top to bottom): Phonetic-0.7, Segmentation-0.3, Disemvowel-0.3, Truncate-0.3, Segmentation-0.5 \& Keyboard-Typo-0.3, Random-0.3 \& Random-0.3 (the last two are double attacks).} \label{tab:morecases} \end{table*} In the \emph{No attack} condition, we checked if the adversarial defense methods introduce mistakes when presented with clean sentences. Indeed, all models introduce some errors: all three evaluation metrics show that BERT-Defense{} introduces a few more errors than \emph{Pyspellchecker} but less than \emph{ScRNN defense}. \begin{table}[!t] \centering \noindent \begin{tabularx}{\linewidth}{@{}>{\bfseries}p{2.8cm}@{\hspace{.5em}}X@{}} \toprule Ground-truth & china gives us regulators access to audit records \\ Attacked (rd:0.6,rd:0.6) & hainc gcive us regulafors essacf to tufai rsxrdeo \\ \midrule Bert-Defense (attack-agnostic{}) & haine gave us regulators space to turn us over \\ Human & hain gives us regulators escape to dubai suborder \\ ScRNN Defense & hainc give us regulafors essacf to tufai rsxrdeo \\ Pyspellchecker & hain give us regulators essay to tufa rsxrdeo\\ \bottomrule \end{tabularx} \caption{Failure cases for BERT-Defense{}, humans and the baseline methods. Note that in the failure case, BERT-Defense{} and Humans restore sentences that are grammatically correct, but are mostly different from the ground-truth. On the other hand, Pyspellchecker and ScRNN Defense \citep{pruthi-etal-2019-combating} either refuse to try at all for strongly attacked words or create grammatically nonsensical sentences. } \label{tab:failure_cases} \end{table} \paragraph{Comparison with humans.} As stated before, we evaluate human performance on 40 random sentences for each of nine attacks and the no attack condition (see appendix). For each of the sentences, we obtain restorations from 4 crowd-workers. For each attack scenario, we evaluate our metrics on all restorations of these 40 sentences and averaged the results. The results on the 40 attacked sentences are shown in Figure \ref{fig:evaluations_human}. While $\text{BD}_{\text{agn}}$ performs slightly worse than humans, $\text{BD}_{\text{spec}}$ matches human performance with respect to all three evaluation metrics. Regarding performance on specific attacks, humans are still better than BERT-Defense{} when it comes to defending phonetic attacks, while they have a hard time defending full-shuffle attacks. The evaluations for the \emph{No attack} setting reveal that the crowd-workers in our experiment do make quite a few copying mistakes. In fact, they introduce slightly more mistakes than BERT-Defense{}. \paragraph{Ablation Study.} \begin{figure}[!h] \centering \includegraphics[width=0.45\textwidth]{graphics/ablation.pdf} \caption{Ablation study for BERT-Defense. The MoverScore metric is shown for BERT-Defense with exactly one single component left out, respectively, on the rd:0.3,rd:0.3 attack. For comparison, we also show the MoverScore without shielding and after shielding with $\text{BD}_{agn}$ or $\text{BD}_{spec}$ using all components.} \label{fig:ablation} \end{figure} We perform an ablation study to asses the contribution of each individual component of BERT-Defense. For the \emph{No Levenshtein distance} condition, we created the context-independent probability distribution by setting the probability of known words (words in the dictionary) in the attacked dataset to one and using a uniform random distribution for all unknown words. When using BERT-Defense without BERT, we directly select the best hypothesis from the context-independent probability distribution using GPT. To run BERT-Defense without GPT, we select the hypothesis with the highest probability according to the results from the modified Levenshtein distance and improve it using context-dependent probabilities obtained with BERT. We evaluate on the rd:0.3,rd:0.3 attack scenario, because we think that it is the most challenging attack. The results are shown in Figure \ref{fig:ablation}. They indicate that the most important component of BERT-Defense is the Levenshtein distance, as BERT often does not have enough context to meaningfully restore the sentences, given the difficult attacks from Zeroé that typically modify many words in each sentence. Removing BERT also considerably decreases the performance of the defense model. Finally, BERT-Defense without GPT performs on par with $\text{BD}_{agn}$ in these experiments, suggesting that BERT-Defense can also be used without GPT for hypothesis selection. \paragraph{More illustrating examples.} To give an impression of the dataset and how the models cope with the adversarial attacks, we show more illustrating examples in Tables \ref{tab:morecases} and \ref{tab:othercases} (appendix). These indicate the superiority of our approach in that it typically generates semantically adequate sentences.
{'timestamp': '2021-06-04T02:03:39', 'yymm': '2106', 'arxiv_id': '2106.01452', 'language': 'en', 'url': 'https://arxiv.org/abs/2106.01452'}
arxiv
\subsection{Graphs and Learning Tasks} We study on two types of graphs and related tasks about learning, classifying, or predicting links between nodes. \begin{definition}[Weighted graph] A weighted graph, denoted as $\mathcal{G}=(\mathcal{U},\mathcal{E}\subset\mathcal{U}\times\mathcal{U})$, contains a set of nodes $\mathcal{U}$ and a set of links $\mathcal{E}$, with a weight mapping function $w:\mathcal{E}\rightarrow\mathbb{R}$. \end{definition} For example, collaboration networks are weighted graphs. The weight is the frequency of collaborations between two person nodes. So, it is a positive integer when the link exists. The task of \emph{link prediction} is to predict whether the value of $w(u_i, u_j)$ is positive or what the value is, given a pair of nodes $u_i, u_j \in \mathcal{U}$. \begin{definition}[Relational graph] A relational graph, denoted as $\mathcal{G}_{rel}=(\mathcal{U},\mathcal{E}\subset\mathcal{U}\times\mathcal{U}\times\mathcal{R}, \mathcal{R})$, contains a set of nodes $\mathcal{U}$, a set of relational links $\mathcal{E}$, and a relation schema $\mathcal{R}$. A relation link $e=(u_i,u_j,r)\in\mathcal{E}$ indicates that $u_i$ and $u_j$ have relation $r$. \end{definition} Knowledge graphs are typical relational graphs, where the relational links need to be learned and completed. The task of \emph{relation classification} is to predict the type of relation between two nodes (i.e., entities) $u_i, u_j$ from the relation schema $\mathcal{R}$ so that a link $e=(u_i,u_j,r)$ is likely to exist in the graph. The fundamental problem of both tasks is \emph{node representation learning} that learns low-dimensional vectors of nodes to preserve the graph's information. Take \emph{link prediction} as an example -- formally, it is to learn a mapping function: $\vec{u} = f(u, \mathcal{G}, \Theta) \in \mathbb{R}^d$, where $\Theta$ is the node representation learning model's parameters and $d$ is the number of dimensions of node representations. Then the value of $w(u_i, u_j)$ is assigned as $\sigma(\vec{u_i}^{\top} \vec{u_j})$, where $\sigma$ is sigmoid. Simple predictive functions can be specified for the other two tasks. \subsection{Graph Convolutional Network} Graph convolutional network (GCN) is one of the most popular models for node representation learning \cite{kipf2017semi}. Let us continue using \emph{link prediction} as the example. We denote the number of nodes in graph $\mathcal{G}$ by $n = |\mathcal{U}|$. Suppose $A \in \mathbb{R}^{n \times n}$ is the adjacency matrix of $\mathcal{G}$ and $X \in \mathbb{R}^{n \times m}$ has the nodes' raw attribute values, where $m$ is the number of the raw attributes. A two-layer GCN generates the matrix of node representations as follows: \begin{equation} U = \mathrm{softmax} \left( \hat{A}~\mathrm{ReLU}(\hat{A}~X~W_{(1)})~W_{(2)} \right) \in \mathbb{R}^{n \times d}, \label{eq:gcn} \end{equation} where $\Theta = \{W_{(1)} \in \mathbb{R}^{m \times d}, W_{(2)} \in \mathbb{R}^{d \times d}\}$ has layer-specific weight matrices. We choose two layers as most of existing studies suggest. The pre-processing step includes (1) $\tilde{A} = A+I_n$, (2) $\tilde{D}_{ii} = \sum_{j} \tilde{A}_{ij}$, and (3) $\hat{A} = \tilde{D}^{\frac{1}{2}}~\tilde{A}~\tilde{D}^{\frac{1}{2}}$. Graph reconstruction is used to inform the GCN to learn $\Theta$ to generate effective $U$: \begin{equation} g(X, A, W_{(1)}, W_{(2)}) = \sigma(U U^{\top}) \in {[0,1]}^{n \times n}. \end{equation} The loss function can be written as follows: \begin{eqnarray} f(W_{(1)}, W_{(2)}) & = & \mathcal{L} \left( g(X, A, W_{(1)}, W_{(2)}),~A \right) \nonumber \\ & = & - \sum_{i,j \in \{1 \dots n\}} A_{ij}~\mathrm{log} \left( \sigma(\vec{u_i}^{\top} \vec{u_j}) \right) \label{eq:lossgcn} \end{eqnarray} where $\vec{u_i}$ and $\vec{u_j}$ are the $i$-th and $j$-th rows in matrix $U$. It is worth noting that one can easily extend our study from two-layer GCN to $l$-layer GCN ($l > 2$). \subsection{Cross-Network Learning} One GCN can be built for one graph. What if we have multiple graphs which overlap each other to perform the same type of tasks? The overlapping parts, referred as \emph{network alignment} serve as bridge for transferring knowledge across multiple GCNs so that they can mutually enhance each other. Without loss of generality, we focus on the cases that have two graphs $\mathcal{G}^{[A]}$ and $\mathcal{G}^{[B]}$. We denote by $A^{[A,B]} \in {\{0,1\}}^{n_A \times n_B}$ the adjacency matrix of network alignment between the two graphs: $A^{[A,B]}_{ij} = 1$, if node $u^{[A]}_i$ and node $u^{[B]}_j$ are aligned; where $n_A = |\mathcal{U}^{[A]}|$ and $n_B = |\mathcal{U}^{[B]}|$. Usually the graphs are \emph{partially aligned}, leading to missing alignment links and the sparsity of the alignment matrix. \begin{definition}[Separated GCNs] Traditionally, the network alignment was ignored in building GCNs. So, two separated GCNs would be built for the tasks on graphs $\mathcal{G}^{[A]}$ and $\mathcal{G}^{[B]}$: \begin{eqnarray} f(W^{[A]}_{(1)}, W^{[A]}_{(2)}) = \mathcal{L} \left( g(X^{[A]}, A^{[A]}, W^{[A]}_{(1)}, W^{[A]}_{(2)}),~A^{[A]} \right), \nonumber \\ f(W^{[B]}_{(1)}, W^{[B]}_{(2)}) = \mathcal{L} \left( g(X^{[B]}, A^{[B]}, W^{[B]}_{(1)}, W^{[B]}_{(2)}),~A^{[B]} \right), \end{eqnarray} where no model parameters (between ${\Theta}^{[A]}$ and ${\Theta}^{[B]}$) is shared and no alignment information is used. \end{definition} \begin{definition}[Cross-network learning] Given two graphs $\mathcal{G}^{[A]}$ and $\mathcal{G}^{[B]}$ as well as the network alignment information $A^{[A,B]}$, build cross-network learning models that have the properties below: \begin{itemize} \item generate node representations $U^{[A]} \in \mathbb{R}^{n_A \times d_A}$ and $U^{[B]} \in \mathbb{R}^{n_B \times d_B}$ through graph convolutions, where $d_A$ and $d_B$ are the numbers of dimensions, respectively -- $d_A \ll m_A$, $d_B \ll m_B$, and they do not have to be equivalent; \item perform better than separated GCNs by sharing model parameters and/or incorporating the network alignment information. \end{itemize} \end{definition} \subsection{Sharing Model Parameters across GCNs} \label{sec:sharingmodel} Recall that a two-layer GCN on graph $\mathcal{G}^{[A]}$ has parameters $\Theta^{[A]}=\{W^{[A]}_{1} \in \mathbb{R}^{m_A \times d_A}, W^{[A]}_{2} \in \mathbb{R}^{d_A \times d_A}\}$. Same goes for graph $\mathcal{G}^{[B]}$. Suppose $d_A \neq d_B$. None of the parameters can be directly shared. Suppose $d_A = d_B$. The second-layer weight parameters can be shared: $W_{2} = W^{[A]}_{2} = W^{[B]}_{2}$. So, we can perform joint GCN training: \begin{eqnarray} \scale[0.9]{f(W^{[A]}_{(1)}, W^{[B]}_{(1)}; W_{(2)}) = \alpha^{[A]} \cdot \mathcal{L} \left( g(X^{[A]}, A^{[A]}, W^{[A]}_{(1)}, W_{(2)}),~A^{[A]} \right)} \nonumber \\ \scale[0.9]{+~\alpha^{[B]} \cdot \mathcal{L} \left( g(X^{[B]}, A^{[B]}, W^{[B]}_{(1)}, W_{(2)}),~A^{[B]} \right),} \label{eq:sharew2} \end{eqnarray} where $\alpha^{[A]}$ and $\alpha^{[B]}$ are per-graph weight of the training procedure. When we have two graphs, $\alpha^{[A]} + \alpha^{[B]} = 1$. Suppose $m_A = m_B$ and $d_A = d_B$. The weight parameters of both layers can be shared across GCNs. We omit the equation for space -- it simply replaces $W^{[A]}_{(1)}$ and $W^{[B]}_{(1)}$ in Eq.(\ref{eq:sharew2}) by $W_{(1)}$. However, the multiple graphs can hardly have the same raw attribute space. So, when $d = d_A = d_B$ but $m_A \neq m_B$, we assume that linear factorized components of $W^{[A]}_{(1)}$ and $W^{[B]}_{(1)}$ can be shared. We denote the shared component by $W_{(1)} \in \mathbb{R}^{\hat{m} \times d}$, where $\hat{m} = \mathrm{min}\{m_A, m_B\}$ or a smaller value. Then the loss function of joint training is as follows: \begin{eqnarray} \scale[0.8]{f(Q^{[A]}, Q^{[B]}; W_{(1)}, W_{(2)}) = \alpha^{[A]} \cdot \mathcal{L} \left( g(X^{[A]}Q^{[A]}, A^{[A]}, W_{(1)}, W_{(2)}),~A^{[A]} \right)} \nonumber \\ \scale[0.8]{+~\alpha^{[B]} \cdot \mathcal{L} \left( g(X^{[B]}Q^{[B]}, A^{[B]}, W_{(1)}, W_{(2)}),~A^{[B]} \right),} \label{eq:sharew1} \end{eqnarray} where $Q^{[A]} \in \mathbb{R}^{m_A \times \hat{m}}$ and $Q^{[B]} \in \mathbb{R}^{m_B \times \hat{m}}$ are linear transformation matrices on raw feature spaces for aligning the first-layer weight parameter matrices. When the number of graphs is two, we can perform alternatives to save one linear transformation matrix. Alternative 1 is to use $Q^{[A \rightarrow B]} \in \mathcal{R}^{m_A \times m_B}$ to align $\mathcal{G}^{[A]}$'s raw attribute space to $\mathcal{G}^{[B]}$'s: \begin{eqnarray} \scale[0.8]{f(Q^{[A \rightarrow B]}; W^{[B]}_{(1)}, W_{(2)}) = \alpha^{[A]} \cdot \mathcal{L} \left( g(X^{[A]}Q^{[A \rightarrow B]}, A^{[A]}, W^{[B]}_{(1)}, W_{(2)}),~A^{[A]} \right)} \nonumber \\ \scale[0.8]{+~\alpha^{[B]} \cdot \mathcal{L} \left( g(X^{[B]}, A^{[B]}, W^{[B]}_{(1)}, W_{(2)}),~A^{[B]} \right),} \end{eqnarray} And alternative 2 is to use $Q^{[B \rightarrow A]} \in \mathcal{R}^{m_B \times m_A}$ to align $\mathcal{G}^{[B]}$'s raw attribute space to $\mathcal{G}^{[A]}$'s. \subsection{Training Strategies across GCNs} \label{sec:trainingstrategy} The training strategy presented in the above section is \emph{joint training} or referred as multi-task learning. The weights of the tasks, i.e., $\alpha^{[A]}$ and $\alpha^{[B]}$, are determined prior to the training procedure. The other popular training strategy is called \emph{pre-training}, that is to define one task a time as the target task and all the other tasks as source tasks. Take the method of sharing $W_{(2)}$ as an example. The loss function of joint training was given in Eq.(\ref{eq:sharew2}). Now if learning graph $\mathcal{G}^{[B]}$ is the target task, then learning graph $\mathcal{G}^{[A]}$ is the source task. The pre-training procedure has two steps. Their loss functions are: \begin{eqnarray} f_1(W^{[A]}_{(1)}; W_{(2)}) = \mathcal{L} \left( g(X^{[A]}, A^{[A]}, W^{[A]}_{(1)}, W_{(2)}),~A^{[A]} \right), \nonumber \\ f_2(W^{[B]}_{(1)}; W_{(2)}) = \mathcal{L} \left( g(X^{[B]}, A^{[B]}, W^{[B]}_{(1)}, W_{(2)}),~A^{[B]} \right). \end{eqnarray} Each step still minimizes Eq.(\ref{eq:sharew2}): specifically, the first step uses $\alpha^{[A]} = 1$ and $\alpha^{[B]} = 0$; and the second step uses $\alpha^{[A]} = 0$ and $\alpha^{[B]} = 1$. The first step warms up the training of the shared $W_{(2)}$ on $\mathcal{G}^{[A]}$ so that the ``fine-tuning'' step on $\mathcal{G}^{[B]}$ can find more effective model parameters than starting from pure randomization. When the source and target are swapped, the two steps are swapped. \subsection{Aligning Representation Spaces with Regularizations} \label{sec:aligningspaces} Besides sharing model parameters, an idea of bridging the gap between two GCNs is to align their output representation spaces. Given GCNs trained on two graphs $\mathcal{G}^{[A]}$ and $\mathcal{G}^{[B]}$, if two nodes $u^{[A]}_i$ and $u^{[B]}_j$ are aligned, we assume that their representations, $\vec{u}^{[A]}_i \in \mathbb{R}^{d_A}$ and $\vec{u}^{[B]}_j \in \mathbb{R}^{d_B}$ are highly correlated. For example, one named entity (person, location, or organization) in two different knowledge graphs should have very similar representations. The same goes for one researcher in two collaboration networks (as an investigators in projects or an author in papers). We add the network alignment information as two types of regularization terms into the loss function. The first type is \emph{Hard regularization}. It assumes that the aligned nodes have exactly the same representations in the two output spaces. This requires the two spaces to have the same number of dimensions: $d_A = d_B$. The term is written as: \begin{equation} h(W^{[A]}_{(1)}, W^{[A]}_{(2)}, W^{[B]}_{(1)}, W^{[B]}_{(2)}) = {\left\| U^{[A]} - A^{[A,B]}~U^{[B]} \right\|}^2_\mathrm{F}. \end{equation} The entire loss function is as below: \begin{eqnarray} & & f({\Theta}^{[A]}, {\Theta}^{[B]}) = f(W^{[A]}_{(1)}, W^{[A]}_{(2)}, W^{[B]}_{(1)}, W^{[B]}_{(2)}) \nonumber \\ & = & (1-\beta) \cdot \alpha^{[A]} \cdot \mathcal{L} \left( g(X^{[A]}, A^{[A]}, W^{[A]}_{(1)}, W^{[A]}_{(2)}),~A^{[A]} \right) \nonumber \\ & & +~(1-\beta) \cdot \alpha^{[B]} \cdot \mathcal{L} \left( g(X^{[B]}, A^{[B]}, W^{[B]}_{(1)}, W^{[B]}_{(2)}),~A^{[B]} \right) \nonumber \\ & & +~\beta \cdot h(W^{[A]}_{(1)}, W^{[A]}_{(2)}, W^{[B]}_{(1)}, W^{[B]}_{(2)}), \label{eq:alignreg} \end{eqnarray} where $\beta$ is the weight of the regularization task. The second type is \emph{Soft regularization} which is designed for more common cases that $d_A \neq d_B$. It assumes that the aligned nodes' representations from one GCN can be linearly transformed into the ones in the other GCN's output space: \begin{equation} h({\Theta}^{[A]}, {\Theta}^{[B]}, R^{[A \rightarrow B]}) = {\left\| U^{[A]} R^{[A \rightarrow B]} - A^{[A,B]}~U^{[B]} \right\|}^2_\mathrm{F}, \label{eq:softreg} \end{equation} where $R^{[A \rightarrow B]} \in \mathbb{R}^{d_A \times d_B}$ is the transformation matrix. Note that $R^{[A \rightarrow B]}$ is treated as model parameters in the loss function. \subsection{Alignment Reconstruction} \label{sec:alignmentreconstruction} When the two graphs are partially aligned, the network alignment information is usually sparse and incomplete. To address this issue, we treat the alignment information as a bipartite graph $\mathcal{G}^{[A,B]}$ and learn to reconstruct and complete the graph. Given the node representations $U^{[A]} \in \mathbb{R}^{n_A \times d_A}$ and $U^{[B]} \in \mathbb{R}^{n_B \times d_B}$, can we reconstruct the adjacency matrix of observed alignment data $\mathcal{G}^{[A,B]}$, i.e., $I^{[A,B]} \odot A^{[A,B]} \in \mathcal{R}^{n_A \times n_B}$, where $I^{[A,B]}$ is the indicator matrix of the observations? We introduce $R^{[A,B]} \in \mathbb{R}^{d_A \times d_B}$ and minimize the following optimization term: \begin{equation} h = {\left\| \sigma \left( U^{[A]}~R^{[A,B]}~U^{[B]\top} \right) - I^{[A,B]} \odot A^{[A,B]} \right\|}^2_\mathrm{F}. \label{eq:alignreconstruction} \end{equation} The entire loss function optimizes on three graph reconstruction tasks ($\mathcal{G}^{[A]}$, $\mathcal{G}^{[B]}$, and $\mathcal{G}^{[A,B]}$), by replacing $h$ in Eq.(\ref{eq:alignreg}) with the above equation. The learning procedure transfers knowledge across the three tasks to find effective representations $U^{[A]}$ and $U^{[B]}$. \subsection{Beyond Two: Extend to Multiple GCNs} \label{sec:multigcn} Suppose we have $K > 2$ GCNs. All the above methods (i.e., loss functions) can be easily extended from $2$ to $K$ GCNs. For example, the loss of joint multi-GCN training with \emph{shared $W_{2}$} can be written as below (extended from Eq.(\ref{eq:sharew2})): \begin{equation} \scale[0.9]{f({\{W^{[i]}_{(1)}\}}|^{K}_{i=1}; W_{(2)}) = \sum^{K}_{i=1} \alpha^{[i]} \mathcal{L} \left( g(X^{[i]}, A^{[i]}, W^{[i]}_{(1)}, W_{(2)}),~A^{[i]} \right).} \end{equation} And the loss of joint multi-GCN training with \emph{shared $W_{1}$ and $W_{2}$} can be written as below (extended from Eq.(\ref{eq:sharew1})): \begin{equation} \scale[0.88]{f({\{Q^{[i]}\}}|^{K}_{i=1}; W_{(1)}, W_{(2)}) = \sum^{K}_{i=1} \alpha^{[i]} \mathcal{L} \left( g(X^{[i]}Q^{[i]}, A^{[i]}, W_{(1)}, W_{(2)}),~A^{[i]} \right).} \end{equation} When using the network alignment information, the \emph{soft regularization} term is written as below (extended from Eq.(\ref{eq:softreg})): \begin{eqnarray} & & h \left( {\{{\Theta}^{[i]}\}}|^{K}_{i=1},~{\{R^{[i \rightarrow j]}\}}|_{i < j;~i, j \in \{1 \dots n\}} \right) \nonumber \\ & = & \sum_{i < j;~i, j \in \{1 \dots n\}} \gamma^{[i \rightarrow j]} {\left\| U^{[i]} R^{[i \rightarrow j]} - A^{[i,j]}~U^{[j]} \right\|}^2_\mathrm{F}, \end{eqnarray} where $\gamma^{[i \rightarrow j]}$ is the regularization weight of aligning representation spaces between graphs $\mathcal{G}^{[i]}$ and $\mathcal{G}^{[j]}$. The optimization term for alignment reconstruction and completion can be written as below (extended from Eq.(\ref{eq:alignreconstruction})): \begin{equation} h = \sum_{i < j} \gamma^{[i \rightarrow j]} {\left\| \sigma \left( U^{[i]}~R^{[i,j]}~U^{[j]\top} \right) - I^{[i,j]} \odot A^{[i,j]} \right\|}^2_\mathrm{F}. \label{eq:alignreconstruction} \end{equation} \subsection{Implementation on Relational Graphs: Relation Classification across GCNs} \label{sec:relational} Schlichtkrull \emph{et al.} proposed neural relational modeling that uses GCNs for relation classification on relational graphs \cite{schlichtkrull2018modeling}. The output node representations from two-layer GCN are given as below: \begin{equation} U = \mathrm{softmax} \left( \sum_{r \in \mathcal{R}} \frac{1}{c_r} A_{:,:,r}~\mathrm{ReLU} \left( \sum_{r \in \mathcal{R}} \frac{1}{c_r} A_{:,:,r}~X~W_{r,(1)} \right)~W_{r,(2)} \right). \end{equation} Clearly, it can be derived from Eq.(\ref{eq:gcn}) by making these changes: \begin{itemize} \item The relational graph $\mathcal{G}_{rel} = \{\mathcal{U}, \mathcal{E}, \mathcal{R}\}$ is denoted as a three-way tensor $A \in {\{0,1\}}^{n \times n \times n_R}$, where $n = |\mathcal{U}|$ is the number of entity nodes and $n_R = |\mathcal{R}|$ is the number of relation types; \item The model parameters are two three-way tensors: \\ $\Theta = \{{W_{r,(1)}}|_{r \in \mathcal{R}} \in \mathbb{R}^{m \times d}, {W_{r,(2)}}|_{r \in \mathcal{R}} \in \mathbb{R}^{d \times d}\}$; \item $c_r$ controls the weight of relation type $r$. \end{itemize} Relation classification can be considered as relational link prediction if we apply the prediction on all the possible entity-relation triples. The full prediction matrix is: \begin{equation} g(X, A, W_{(1)}, W_{(2)}, D) = \sigma(U \otimes D \otimes U^{\top}) \in {[0,1]}^{n \times n \times n_R}, \end{equation} where $D \in \mathbb{R}^{d \times d \times n_R}$ is a three-way core tensor. For each relation type $r$, $D_{:,:,r}$ is a $d \times d$-diagonal matrix. The loss function is below: \begin{eqnarray} & & f(W_{(1)}, W_{(2)}, D) = \mathcal{L} \left( g(X, A, W_{(1)}, W_{(2)}, D),~A \right) \nonumber \\ & = & - \sum_{i,j \in \{1 \dots n\};~r \in \mathcal{R}} A_{i,j ,r}~\mathrm{log} \left( \sigma(\vec{u_i}^{\top}~D_{:,:,r}~\vec{u_j}) \right) \end{eqnarray} All the proposed methods for partially aligned GCNs in the previous sections can be applied here. The key differences are (1) a three-way tensor data for reconstruction and (2) additional parameters $D$. \subsection{Choices of the Number of Dimensions $d$} The task of graph reconstruction is to use the node representations $U \in \mathbb{R}^{n \times d}$ to recover the adjacency matrix $A \in \mathbb{R}^{n \times n}$. With singular value decomposition, we have $A \simeq \hat{U}~\Sigma~\hat{U}^{\top}$, where $\hat{U} \in \mathbb{R}^{n \times \mathrm{rank}(A)}$ and $\Sigma$ is square diagonal of size $\mathrm{rank}(A) \times \mathrm{rank}(A)$. So, the loss function in Eq.(\ref{eq:lossgcn}) can be approximated as the squared loss: \begin{equation} f = {\left\|~U~B - \hat{U}~\sqrt{\Sigma}~\right\|}^2_\mathrm{F}, \end{equation} where $B \in \mathcal{R}^{d \times \mathrm{rank}(A)}$. It transforms the $n \times n$ classification tasks (for link prediction) into $\mathrm{rank}(A)$ regression tasks. \begin{proposition} Suppose we have $K$ GCNs. In a linear setting for every model in the partially aligned GCNs, the loss function becomes: \begin{equation} \scale[0.95]{f \left( {\{\Theta_{i} = W^{[i]}_{(1)} W^{[i]}_{(2)} B^{[i]}\}}|^{K}_{i=1} \right) = \sum^{K}_{i=1} { {\left\|~\hat{A}^{[i]~2} X^{[i]} \Theta_{i} - \hat{U}^{[i]}~\sqrt{{\Sigma}^{[i]}}~\right\|}^2_\mathrm{F} }.} \label{eq:losslinear} \end{equation} The optimal solution for the $i$-th GCN is \begin{equation} {\Theta}_{i} = {\left( X^{[i]\top} \hat{A}^{[i]~4} X^{[i]} \right)}^{\dagger} X^{[i]\top} \hat{A}^{[i]~2} \hat{U}^{[i]} \sqrt{{\Sigma}^{[i]}} \in \mathcal{R}^{m_i \times \mathrm{rank}(A)}, \end{equation} where $X^{\dagger}$ denotes $X$'s pseudoinverse. Hence a capacity of $\mathrm{rank}(A^{[i]})$ suffices for the $i$-th GCN. If $d \geq \sum^{K}_{i=1} \mathrm{rank}(A^{[i]})$, then $B^{[i]}$ can be an identity matrix and there is \emph{no transfer} between any two GCNs. In that case, no matter ${\{W^{[i]}_{(1)}\}}|^{K}_{i=1}$ or ${\{W^{[i]}_{(2)}\}}|^{K}_{i=1}$ are shared or not, these exists an optimum $W^{[i]*}_{(1)} W^{[i]*}_{(2)} = {\Theta}_{i}$, for all $i=1 \dots K$. \end{proposition} \noindent The illustration of this idea and extension to nonlinear settings are discussed in Appendix. \subsection{Positive Transfer across GCN Models} We apply the theory of \emph{positive transfer} in multi-task learning (MTL) \cite{wu2019understanding} into cross-GCNs learning. If the cross-GCNs training improves over just training the target GCN on one particular graph, we say the source GCNs on other graphs \emph{transfer positively} to the target GCN. \cite{wu2019understanding} proposed a theorem to quantify how many data points are needed to guarantee positive transfer between two ReLU model tasks. By the above section, it is necessary to limit the capacity of the shared model parameters to enforce knowledge transfer. Here we consider $d = 1$ and $m = m_A = m_B$ to align with the theorem in \cite{wu2019understanding}. We have a theorem for positive transfer between two \emph{one-layer} GCNs that share the first-layer model parameters $W_{(1)}$: \begin{theorem} Let $(\hat{A}^{[i]}X^{[i]} \in \mathbb{R}^{n_i \times m}, \vec{\hat{u}}^{[i]} \sqrt{\lambda^{[i]}_1}) \in \mathbb{R}^{n_i}$ denote the data of graph $\mathcal{G}^{[i]}$ ($i=\{A,B\}$). Suppose the output is generated by $ReLU(\hat{A}^{[i]}X^{[i]}~{\theta}^{[i]})$. And suppose $c \geq \mathrm{sin}({\theta}^{[A]}, {\theta}^{[B]}) / \kappa(\hat{A}^{[B]}X^{[B]})$. Denote by $W^{\star}_{(1)}$ the optimal solution of the one-layer setting of Eq.(\ref{eq:sharew1}): $f(W_{(1)}) = \sum_{i \in \{A, B\}} \mathcal{L} \left( g(X^{[i]}, A^{[i]}, W_{(1)}),~A^{[i]} \right)$. With probability $1-\delta$ over the randomness of $(\hat{A}^{[A]}X^{[A]}, \vec{\hat{u}}^{[A]} \sqrt{\lambda^{[A]}_1})$, when \begin{equation} n_i \geq \mathrm{max}\left( \frac{m \log m}{c^2} (\frac{1}{c^2} + \log m), \frac{{\| \vec{\hat{u}}^{[B]} \sqrt{\lambda^{[B]}_1} \|}^2}{c^2} \right), \end{equation} we have that the estimation error is at most: \begin{equation} \mathrm{sin}(W^{\star}_{(1)}, {\theta}^{[A]}) \leq \mathrm{sin}({\theta}^{[A]}, {\theta}^{[B]}) + O(c/\kappa(\hat{A}^{[B]}X^{[B]})). \end{equation} \end{theorem} \noindent \emph{Notations for the above theorem.} $\kappa(A) = \lambda_{\mathrm{max}}(A) / \lambda_{\mathrm{min}}(A)$ denotes the condition number of $A \in \mathbb{R}^{n \times m}$, where $\lambda_{\mathrm{max}}(A)$ denotes its largest singular value and $\lambda_{\mathrm{min}}(A)$ denotes its min$\{n,m\}$-th largest singular value. As MTL is effective over ``similar'' tasks \cite{xue2007multi}, the cross-GCNs learning can be effective across similar GCN models. A natural definition of GCN similarity is $\mathrm{cos}(\theta^{[A]}, \theta^{[B]})$: higher means more similar. So $\mathrm{sin}(W^{\star},\theta)=\sqrt{1-\mathrm{cos}^2(W^{\star},\theta)}$ can denote the estimation error. Proof of the theorem can be referred in \cite{wu2019understanding}. \subsection{Positive Transfer with Network Alignment} \textbf{Soft regularization}: We transfer knowledge across two GCNs' representation spaces by optimizing Eq.(\ref{eq:alignreg}) where $h$ is specified as Eq.(\ref{eq:softreg}). The optimal solution is \begin{eqnarray} & & U^{[A]\star} = {\left( (1-\beta) \cdot \alpha^{[A]}~I + \beta R^{[A \rightarrow B]} R^{[A \rightarrow B] \top} \right)}^{-1} \cdot \nonumber \\ & & \cdot {\left( (1-\beta) \cdot \alpha^{[A]}~\hat{U}^{[A]} \sqrt{\Sigma^{[A]}} + \beta~A^{[A,B]} U^{[B]\star} R^{[A \rightarrow B] \top} \right)}. \end{eqnarray} So, if $\beta = 0$, $U^{[A]\star} = \hat{U}^{[A]} \sqrt{\Sigma^{[A]}}$ may overfit the graph data $\mathcal{G}^{[A]}$; if $\beta \in (0,1]$, the information transferred from $\mathcal{G}^{[B]}$ via the alignment $A^{[A,B]}$, i.e., $A^{[A,B]} U^{[B]\star} R^{[A \rightarrow B]}$, can have positive impact on link prediction on $\mathcal{G}^{[A]}$. \vspace{0.05in} \noindent \textbf{Alignment reconstruction}: Suppose we optimize Eq.(\ref{eq:alignreg} where $h$ is in Eq.(\ref{eq:alignreconstruction}). The optimal solution is \begin{eqnarray} & & U^{[A]\star} = {\left( (1-\beta) \cdot \alpha^{[A]}~\hat{U}^{[A]} \sqrt{\Sigma^{[A]}} + \beta A^{[A,B]} U^{[B]\star} R^{[A,B] \top} \right)} \nonumber \\ & & \cdot {\left( (1-\beta) \cdot \alpha^{[A]}~I + \beta R^{[A,B]} U^{[B]\star\top} U^{[B]\star} R^{[A,B] \top} \right)}^{-1}. \end{eqnarray} So, if $\beta = 0$, $U^{[A]\star} = \hat{U}^{[A]} \sqrt{\Sigma^{[A]}}$ may overfit the graph data $\mathcal{G}^{[A]}$; if $\beta \in (0,1]$, the information transferred from $\mathcal{G}^{[B]}$ via the alignment $A^{[A,B]}$, i.e., $A^{[A,B]} U^{[B]\star} R^{[A,B] \top}$, can have positive impact on link prediction on $\mathcal{G}^{[A]}$. \begin{table*}[t] \centering \includegraphics[width=\textwidth]{fig/results_link_prediction.pdf} \caption{Performance of VGAE \cite{kipf2016variational}, (Separated) GCNs \cite{kipf2017semi}, and 13 cross-GCN learning models on link prediction in NSFAward and DBLP academic graphs ($\mathcal{G}^{[A]}$ and $\mathcal{G}^{[B]}$). The models take various options on model sharing, regularizations, and alignment reconstruction. Equations can be found in Sections 2 and 3. Higher AUC or AP means better performance. We investigated the standard deviation of all the cells: all the values are smaller than 0.0016 and thus omitted for space. Underlined numbers are targeted values in pre-training strategies. Bolded numbers are the highest on the columns.} \label{tab:results_link_prediction} \vspace{-0.2in} \end{table*} \subsection{Link Prediction} \subsubsection{Datasets} Below are two collaboration networks I use that can be considered as weighted graphs between researcher nodes. \begin{itemize} \item NSFAward: It is publicly available on the National Science Foundation (NSF) Awards database from 1970 to 2019.\footnote{NSF Award Search: \url{https://www.nsf.gov/awardsearch/download.jsp}} Nodes are investigators of the awards. Two investigator nodes have a link if they are participated in the same award(s) and the weight of the link is the number of their shared award(s). \item DBLP: I expand the DBLP-4Area \cite{huang2016meta} from 5,915 authors to 14,387 authors by adding their co-authors in the graph. The weight of the link between two author nodes is the number of their co-authored papers. \end{itemize} \begin{figure*}[t] \centering \includegraphics[width=0.33\textwidth]{fig/sensitivity_link_prediction_beta.pdf} \includegraphics[width=0.33\textwidth]{fig/sensitivity_link_prediction_alpha.pdf} \includegraphics[width=0.33\textwidth]{fig/sensitivity_link_prediction_timecost.pdf} \vspace{-0.3in} \caption{Sensitivity analysis on M13 (sharing $W_{(1)}$ and $W_{(2)}$, plus alignment reconstruction): (a) on the weight of the alignment reconstruction task $\beta$, (b) on the weight of learning on graph $\mathcal{G}^{[A]}$: $\alpha^{[A]}$. And (c) running time analysis in seconds per epoch.} \label{fig:sensitivity_link_prediction} \vspace{-0.05in} \end{figure*} \subsubsection{Experimental settings} For each graph, I randomly split the observed links into training, validation, and test sets by 8:1:1. Then I randomly select unobserved links as negative examples in the validation and test sets. Positives and negatives are balanced. I use Area Under the ROC Curve (AUC) and Average Precision (AP) as evaluation metrics. I perform the evaluation 10 times, calculate mean value and standard deviation. I also report the ``overall'' performance by calculating the harmonic mean of the AUC/AP on the two datasets. All models are developed by PyTorch and one NVIDIA GeForce RTX 2080 Ti graphic card. I set $d_A = d_B = 64$. I use grid search on the hyperparameters in $\{0.1, 0.2, \dots, 0.9\}$ and find that the best combination is $\alpha^{[A]} = \alpha^{[B]} = \beta = 0.5$. \subsubsection{Results} Table~\ref{tab:results_link_prediction} presents the performance of as many as 13 cross-GCN learning models I implemented. Models M3--M8 share $W_{(2)}$ across the NSFAward and DBLP academic graphs. Models M9--M13 share both $W_{(1)}$ and $W_{(2)}$. M6 uses hard regularization; M1, M7, and M12 use soft regularization; and M2, M8, and M13 use alignment reconstruction. I have the following observations: \vspace{0.05in} \noindent O1. \emph{Cross-network models perform better than baselines and the best is M13:} M13 shares $W_{(1)}$ and $W_{(2)}$ between two GCNs, and uses alignment reconstruction to bridge the two representation spaces. In terms of the overall AUC on the two test sets, M13 achieves 0.865, which is significantly higher than VGAE's 0.782 \cite{kipf2016variational} and (Separated) GCNs' 0.803 \cite{kipf2017semi}. The AP is improved from VGAE's 0.773 and GCN's 0.793 to 0.870. Clearly, the knowledge is successfully transferred across the GCN models on two academic graphs. Performance on test sets is worse than but very close to that on validation sets, which indicates no or very little overfitting in the GCN models. Both models need information beyond the corresponding graph data for effective learning and decision-making on the test data. \vspace{0.05in} \noindent O2. \emph{Sharing weight matrices is beneficial, and sharing those of both layers is beneficial:} Suppose we do not use the alignment information at all: the only possible bridge across two GCNs is weight matrices $W_{(1)}$ and $W_{(2)}$. M3--M5 share $W_{(2)}$. Compared with separated GCNs, M5 improves the overall AUC on test sets from 0.803 to 0.836. And M9--M11 share both $W_{(1)}$ and $W_{(2)}$. Compared with M5, M11 improves the AUC from 0.836 to 0.847. When soft regularization is adopted, we can compare M7 and M12 with M1; when alignment reconstruction is adopted, we can compare M8 and M13 with M2. The conclusions are the same. \begin{figure}[t] \centering \includegraphics[width=0.48\textwidth]{fig/sensitivity_link_prediction_choice_d.pdf} \vspace{-0.3in} \caption{Empirical analysis on the choice of $d$.} \label{fig:choice_d} \vspace{-0.2in} \end{figure} \vspace{0.05in} \noindent O3. \emph{If $W_{(2)}$ is shared, joint training is slightly better than pre-training:} M3 pre-trains the model with $\mathcal{G}^{[A]}$ and then fine-tunes on $\mathcal{G}^{[B]}$; M4 switches the use of the graphs. So we focus on M3's performance on $\mathcal{G}^{[B]}$ and M4's on $\mathcal{G}^{[A]}$. Compared with separated GCNs, M3 improves AUC on the test set from 0.840 to 0.854; M4 improves it from 0.769 to 0.806. However, with a joint training strategy, M5 achieves an AUC on $\mathcal{G}^{[B]}$ of 0.860 over M3's 0.854 and achieves an AUC on $\mathcal{G}^{[A]}$ of 0.812 over M4's 0.806. \vspace{0.05in} \noindent O4. \emph{If $W_{(1)}$ is shared, learning linear transformation matrices on both graphs is slightly better than learning a matrix on one of them:} M11 learns $Q^{[A]} \in \mathbb{R}^{m_A \times \hat{m}}$ and $Q^{[B]} \in \mathbb{R}^{m_B \times \hat{m}}$. M9 learns $Q^{[A \rightarrow B]}$ only, and M10 learns $Q^{[B \rightarrow A]}$ only. In terms of the overall AUC on the two test sets, compared with M5 that shares $W_{(2)}$ only, M9 improves AUC from M5's 0.836 to 0.840, M10 achieves an AUC of 0.845, and M11 achieves an AUC of 0.847. \vspace{0.05in} \noindent O5. \emph{Regularizations, hard or soft, are beneficial; and alignment reconstruction is better:} (a) M6 adds hard regularization to M5. M6 improves the overall AUC on the two test sets from M5's 0.836 to 0.842. (b) M1, M7, and M12 add soft regularization to separated GCNs, M5, and M11, respectively. M1 improves the AUC from 0.803 to 0.805, M7 improves from 0.836 to 0.849, and M13 improves from 0.847 to 0.863. With more model parameters (e.g., weight matrices) shared, the improvements by regularizations become bigger. (c) M8 and M13 add alignment reconstruction to M5 and M11, respectively. M8 improves the AUC from 0.836 to 0.856. M13 improves from 0.847 to 0.865. The AUC scores are quite significantly improved by alignment reconstruction, slightly higher than regularizations. \subsubsection{Hyperparameter sensitivity} In Figure~\ref{fig:sensitivity_link_prediction}(a) and~(b) we investigate the effect of hyperparameters $\beta$ and $\alpha^{[A]}$ on the performance of model M13. When $\beta=0$, M13 is equivalent with M11. With $\beta$ increasing, the performance becomes better by learning to reconstruct the network alignment. It is the best when $\beta \in [0.4,0.6]$. Then a too big $\beta$ will overfit the model on the alignment reconstruction, so the AUC/AP decreases quickly when $\beta$ goes from 0.6 to 1. Given $\beta=0.5$, a too big or too small $\alpha^{[A]}$ will overfit one of the graph data, $\mathcal{G}^{[A]}$ or $\mathcal{G}^{[B]}$. When $\alpha^{[A]}$ is around 0.5, the performance is the best. So, all the optimization terms are important. \subsubsection{Time complexity} Figure~\ref{fig:sensitivity_link_prediction}(c) presents the time cost per epoch of separated GCNs, M1, M2, M5, M11--M13. The models that share both $W_{(1)}$ and $W_{(2)}$ (M11), share $W_{(2)}$ only (M5), and share neither of them (Separated) do not show significant difference of time cost. Adopting soft regularizations (M1 vs Separated, M12 vs M11) increases the time cost slightly. And adopting alignment reconstruction (M2 vs M1, M13 vs M12) take slightly more time. The time complexity remains at the same level in the proposed models. \subsubsection{On the choice of $d$} Figure~\ref{fig:choice_d} presents the overall AUC on test sets of Separated GCNs, M5 (sharing $W_{(2)}$), and M11 (sharing $W_{(1)}$ and $W_{(2)}$), when the number of dimensions $d$ is $\{2, 2^2, \dots, 2^8\}$. When $d$ becomes bigger, the improvements by model parameters sharing become smaller. As presented in theoretical analysis, small $d$ would force the knowledge transfer across the GCN models; when $d$ is too big, there might be no transfer. We choose $d=64$ as the default number of dimensions of the latent spaces. \subsection{Relation Classification} \subsubsection{Datasets} Below are four knowledge graphs I use that can be considered as relational graphs between entity nodes. \begin{itemize} \item FB15K: It is a subset of the relational database Freebase \cite{schlichtkrull2018modeling}. \item WN18: It is a subset of WordNet containing lexical relations. \item YAGO: The open source knowledge base developed by MPI. \item DBpedia500: A subset of structured content in the Wikipedia. \end{itemize} I will investigate whether incorporating partially-aligned graphs YAGO and DBPedia500 can improve the performance of relation classification on FB15K and WN18, respectively. Entities are aligned if they have the same surface name. Resolving the inaccuracy of entity alignment is important but out of this work's scope. \begin{table}[t] \centering \includegraphics[width=0.48\textwidth]{fig/results_relation_classification.pdf} \caption{Performance of existing methods (e.g., RGCN \cite{schlichtkrull2018modeling}) and cross-R-GCN learning models on relation classification.} \label{tab:results_relation_classification} \vspace{-0.3in} \end{table} \subsubsection{Experimental settings} Both FB15K and WN18 have standard splits for training, validation, and test. I provide results using two common evaluation metrics: mean reciprocal rank (MRR) and Hits at $k$ (Hits@$k$). I report both raw and filtered MRR (with filtered MRR typically considered more reliable) and filtered Hits@1 and Hits@3, following TransE \cite{bordes2013translating}. Other baseline methods include: \begin{itemize} \item HOlE \cite{nickel2016holographic}: it replaces vector-matrix product with circular correlation to compute knowledge graph embeddings. \item DistMult \cite{yang2014embedding}: a neural embedding approach that learns representations of entities and relations. \item ComplEx \cite{trouillon2016complex}: it models asymmetric relations by generalizing DistMult to the complex domain. \item R-GCN \cite{schlichtkrull2018modeling}: it is the first work of relation graph convolutional network, considered the state of the art. And I use it as the basic GCN model for cross-GCN learning. \item CrossE \cite{zhang2019interaction}: its ``interaction embeddings" are learned from both knowledge graph connections and link explanations. \end{itemize} I use the Adam optimizer with a learning rate of 0.01. Implementation details can be found in Appendix. \subsubsection{Results} Table~\ref{tab:results_relation_classification} presents the results of the baselines and six cross-GCN learning models (M1, M2, M5, M11--M13). Model M5 shares $W_{(2)}$ across two knowledge graphs. M11--M13 share both $W_{(1)}$ and $W_{(2)}$. M1 and M12 use soft regularization; and M2 and M13 use alignment reconstruction. Our main observation is that \emph{cross-network models perform better than baselines and the best model is M13}. With the large-scale YAGO, M13 improves the filtered MRR from 0.696 to 0.742 and the filtered Hits@1 from 0.601 to 0.641 for relation classification on FB15K, compared to a sole R-GCN model. With DBPedia500 which is bigger than YAGO, M13 improves the filtered MRR from 0.819 to 0.843 and the filtered Hits@1 from 0.697 to 0.743 on WN18, compared to R-GCN. Both M12 and M13 that share two-layers parameters and alignment information achieve higher performance than the best baseline CrossE on all the metrics. \subsection{Graph Neural Networks} Graph neural network (GNN) is a type of neural network that operates on graph structure to capture the dependence of graphs via message passing between the nodes of graphs \cite{zhang2020deep,wu2020comprehensive}. Kipf \emph{et al.} proposed graph convolutional networks that use a spectral graph convolution to capture the spatial dependency \cite{kipf2017semi}. Velivckovic \emph{et al.} considered the interaction between nodes in the graph convolution measured as graph attention weight \cite{velivckovic2017graph}. Hamilton \emph{et al.} implemented the graph convolution as an efficient aggregation and sampling algorithm for inductive node representation learning \cite{hamilton2017inductive}. Recently, GNN techniques have been applied for learning representations on relational graphs, specifically knowledge graphs \cite{sadeghian2019drum,zhang2019quaternion,ren2020beta}. Relational GNNs perform significantly better than conventional knowledge graph embeddings \cite{schlichtkrull2018modeling}. Most techniques suffer from the issue of data sparsity and our proposed methods address it with knowledge transfer across networks. In this paper, we discussed weighted graph, relational graph, and bipartite graphs; however, heterogeneous graphs are ubiquitous and have unique essential challenges for modeling and learning \cite{wang2020heterogeneous,luo2020dynamic,liu2020heterogeneous,wang2019attentional,wang2019kgat}. We have been seeing heterogeneous GNNs \cite{dong2017metapath2vec,liu2018heterogeneous,zhang2019heterogeneous,fu2020magnn} and heterogeneous attention networks for graphs \cite{wang2019heterogeneous,yang2020heterogeneous,hu2020heterogeneous,yao2020heterogeneous,hu2020gpt}. Extending our proposed cross-network learning to heterogeneous graphs and enabling inductive learning in the framework are very important. These two points are out of the scope of our work but worth being considered as future directions. \subsection{Network Alignment and Modeling} The alignment of nodes between two or more than two graphs has been created and/or utilized in at least three categories of methods \cite{jiang2012social,jiang2015social,vijayan2017multiple,chen2017community,qin2020g,gu2020data}. First, Kong \emph{et al.} inferred anchor links between two social networks by matching the subgraphs surrounding the linked nodes \cite{kong2013inferring}. Emmert \emph{et al.} wrote a comprehensive survey on the algorithms of graph matching \cite{emmert2016fifty}. Second, Zhang \emph{et al.} used graph pattern mining algorithms for node alignment on incomplete networks \cite{zhang2017ineat} and multi-level network \cite{zhang2019multilevel}. Nassar \emph{et al.} leveraged the multimodal information for network alignment \cite{nassar2017multimodal}. The third line of work learned node representations and trained the supervised models with node pairing labels (if available) \cite{du2019joint,ye2019vectorized,nassar2018low}. A matrix factorization-based model has demonstrated that cross-network or cross-platform modeling can alleviate the data sparsity on a single platform \cite{jiang2016little}. \section{Reproducibility} \section{Additional Information for Theoretical Analysis} \subsection{Choices of the Number of Dimensions $d$} The total capacities (i.e., sum of ranks of adjacency matrices) can be implemented as $\sum^{K}_{i=1} \mathrm{argmax}_{p}~\lambda_{p}(A^{[i]}) \geq \epsilon$, the sum of the minimum positions of no-smaller-than-$\epsilon$ singular value. To illustrate the idea, suppose $\{W^{[i]}_{(2)}\}$ are shared across GCNs, which means $W_{(2)}=W^{[1]}_{(2)}=\dots=W^{[K]}_{(2)}$. As long as the shared $W^{*}_{(2)}$ contains ${{\Theta}_{i}}|^{K}_{i=1}$ in its column span, there exits $W^{[i]*}_{(1)}$ such that $W^{[i]*}_{(1)} W^{*}_{(2)} = {\Theta}_{i}$, which is optimal for Eq.(\ref{eq:losslinear}) with minimum error. But this means no transfer across any GCNs. This can hurt generalization if a GCN has limited data $\mathcal{G}^{[i]}$, in which its single-GCN solution overfits training data, whereas the cross-network solution can leverage other graphs' data to improve generalization. \vspace{0.05in} \noindent \textbf{Extension to the ReLU/softmax setting.} If the capacity of the shared model parameters (i.e., the number of dimensions $d$) is larger than the total capacities, then we can share both ${\{W^{[i]}_{(1)}\}}|^{K}_{i=1}$ and ${\{W^{[i]}_{(2)}\}}|^{K}_{i=1}$. This remains an optimal solution to the joint training problem in the ReLU/softmax setting. Furthermore, there is \emph{no transfer} between any GCNs through the shared model parameters. \subsection{Positive Transfer with Network Alignment} \textbf{Soft regularization}: The loss function can be re-written as: \begin{eqnarray} f & = & (1-\beta) \cdot \alpha^{[A]}~{\| U^{[A]} - \hat{U}^{[A]} \sqrt{\Sigma^{[A]}} \|}^2_\mathrm{F} \nonumber \\ & & +~(1-\beta) \cdot \alpha^{[B]}~{\| U^{[B]} - \hat{U}^{[B]} \sqrt{\Sigma^{[B]}} \|}^2_\mathrm{F} \nonumber \\ & & +~\beta~{\| U^{[A]} R^{[A \rightarrow B]} - A^{[A,B]} U^{[B]} \|}^2_\mathrm{F}. \end{eqnarray} The gradient is \begin{eqnarray} & & \frac{\mathrm{d}~f}{\mathrm{d}~U^{[A]}} = 2~(1-\beta) \cdot \alpha^{[A]}~(U^{[A]} - \hat{U}^{[A]} \sqrt{\Sigma^{[A]}}) \nonumber \\ & & + 2~\beta~(U^{[A]} R^{[A \rightarrow B]} - A^{[A,B]} U^{[B]}) R^{[A \rightarrow B]~\top}. \end{eqnarray} \vspace{0.05in} \noindent \textbf{Alignment reconstruction}: The loss function is: \begin{eqnarray} f & = & (1-\beta) \cdot \alpha^{[A]}~{\| U^{[A]} - \hat{U}^{[A]} \sqrt{\Sigma^{[A]}} \|}^2_\mathrm{F} \nonumber \\ & & +~(1-\beta) \cdot \alpha^{[B]}~{\| U^{[B]} - \hat{U}^{[B]} \sqrt{\Sigma^{[B]}} \|}^2_\mathrm{F} \nonumber \\ & & +~\beta~{\| U^{[A]} R^{[A,B]} U^{[B]\top} - A^{[A,B]} \|}^2_\mathrm{F}. \end{eqnarray} The gradient is \begin{eqnarray} & & \frac{\mathrm{d}~f}{\mathrm{d}~U^{[A]}} = 2~(1-\beta) \cdot \alpha^{[A]}~(U^{[A]} - \hat{U}^{[A]} \sqrt{\Sigma^{[A]}}) \nonumber \\ & & + 2~\beta~(U^{[A]} R^{[A,B]} U^{[B]\top} - A^{[A,B]}) U^{[B]} R^{[A,B]~\top}. \end{eqnarray} \section{Introduction} \label{sec:intro} \input{1introduction} \section{Preliminaries} \label{sec:prelim} \input{2preliminaries} \section{Proposed Methods} \label{sec:methods} \input{3methods} \section{Theoretical Analysis} \label{sec:theory} \input{4theory} \section{Experiments} \label{sec:experiments} \input{5experiments} \section{Related Work} \label{sec:related} \input{6relatedwork} \section{Conclusions} \label{sec:conclusions} \input{7conclusions} \section*{Acknowledgment} This research was supported by National Science Foundation award IIS-1849816. \balance \bibliographystyle{ACM-Reference-Format}
{'timestamp': '2021-06-04T02:10:16', 'yymm': '2106', 'arxiv_id': '2106.01583', 'language': 'en', 'url': 'https://arxiv.org/abs/2106.01583'}
arxiv
\section{Introduction} \label{sec:intro} Convolutional Neural Networks (CNNs) have been achieving exceedingly improved performance for object detection in terms of classifying and localizing a variety of objects in a scene \cite{faster_RCNN,ssd,yolo,RetinaNet}. However, under a domain shift, when the testing data has a different distribution from the training data distribution, the performance of state-of-the-art object detection methods drop noticeably and sometimes significantly. Such domain shift could occur due to capturing the data under different lighting or weather conditions, or due to viewing the same objects from different view points leading to changes in object appearance and background. For example, training data used for autonomous vehicles is normally captured under favorable clear weather conditions whereas testing could take place under more challenging weather (\textit{e.g.} rain, fog). Consequently, methods fail to detect objects as shown in the examples of Figure \ref{fig:cityscapes_examples}(b). In that context, the domain under which training is done is known the \textit{source domain} while the new domain under which testing is conducted is referred to as the \textit{target domain}. \begin{figure}[t] \begin{center} \includegraphics[width=1\linewidth]{figures/cityscapes_example.png} \end{center} \caption{Visual detection examples using the original YOLOv4 method on: (a) clear images and (b) foggy images. (c) Our proposed MS-DAYOLO applied onto foggy images.} \label{fig:cityscapes_examples} \end{figure} One of the challenges that aggravates the domain shift problem is the lack of annotated target domain data. This led to the emergence of the area of \textit {domain adaptation} \cite{duan2012domain,kulis2011you,tzeng2017adversarial,long2016unsupervised}, which has been widely studied to solve the problem of domain shift without the need to annotate data for new target domains. Recently, domain adaptation has been used to improve the performance of object detection due to domain shift \cite{survey}. It attempts to learn a robust object detector using labeled data from the source domain and unlabeled data from the target domain. Most domain adaptation approaches in literature employ adversarial training strategy \cite{GANs}. In particular, a domain classifier is optimized to identify whether a data point from the source or target domain, while the feature extractor of object detector is optimized to confuse the domain classifier. This strategy makes the feature extractor learn domain invariant features. Domain adaptive Faster R-CNN \cite{DA_faster_RCNN} is the first work that employed adversarial training for domain adaptation based object detection. After that, many adversarial-based methods were developed for domain adaptation object detection \cite{zhu2019adapting,wang2019few,saito2019strong,he2019multi}. Equally important, the particular domain adaptation solution used is influenced greatly by the underlying object detection method architecture. In that context, within the area of object detection, domain adaptation has been studied rather extensively for Faster R-CNN object detection and its variants \cite{DA_faster_RCNN,zhu2019adapting,wang2019few,saito2019strong,he2019multi}. Despite its popularity, Faster R-CNN suffers from long inference time to detect objects. As a result, it is arguably not the optimal choice for time-critical, real-time applications such as autonomous driving. On the other hand, one-stage object detectors, and in particular YOLO, can operate quite fast, even much faster than real-time, and this makes them invaluable for autonomous driving and similar time-critical applications. Furthermore, domain adaptation for the family of YOLO architectures have received virtually no attention. Besides the computational advantage of YOLO, the latest version, YOLOv4, has many salient improvements and its object detection performance has improved rather significantly relative to prior YOLO architectures and more important in comparison to Faster R-CNN. All of these factors motivated our focus on the development of a new domain adaptation framework for YOLOv4. In this paper, we propose a novel MultiScale Domain Adaptive YOLO (MS-DAYOLO) that supports domain adaptation at different layers of the feature extraction stage within the YOLOv4 backbone network. In particular, MS-DAYOLO includes a Domain Adaptive Network (DAN) with multiscale feature inputs and multiple domain classifiers. We conducted extensive experiments using popular datasets. These experiments show that our proposed MS-DAYOLO framework provides significant improvements to the performance of YOLOv4 when tested on target domain as shown in the examples of Figure \ref{fig:cityscapes_examples}(c). To the best of our knowledge, this is the first proposed work that improves the performance of YOLO for cross domain object detection. \section{Proposed MS-DAYOLO} YOLOv4 \cite{yolov4} has been released recently as the latest version of the family of the YOLO object detectors. Relative to its predecessor, YOLOv4 has incorporated many new revisions and novel techniques to improve the overall detection accuracy. YOLOv4 has three main parts: backbone, neck, and head as shown in Figure \ref{fig:arch}. The backbone is responsible for extracting multiple layers of features at different scales. The neck collects these features from three different scales of the backbone using upsampling layers and feed them to the head. Finally, the head predicts bounding boxes surrounding objects as well as class probabilities associated with each bounding box. \begin{figure*} \begin{center} \includegraphics[width=1\linewidth]{figures/arch.png} \end{center} \caption{Architecture of the proposed MS- DAYOLO. Domain adaptation network (DAN) is attached to the YOLO object detector only during training in order to learn domain invariant features.} \label{fig:arch} \end{figure*} The backbone (\textit{i.e.}{feature extractor}) represents a major module of the YOLOv4 architecture, and we believe that it makes a significant impact on the overall performance of the detector. In addition to many convolutional layers, it has 23 residual blocks \cite{ResNet}, and five downsampling layers to extract critical layers of features that are used by the subsequent detection stages. Here, we consecrate on the features (F1, F2, and F3 in Figures \ref{fig:arch}) because they are fed to the next stage (neck module). In particular, our goal is to apply domain adaptation to these three features to make them robust against domain shifts at different scales, and hence, have them converge toward domain invariance during domain-adaptation based training. \subsection{Domain Adaptive Network for YOLO} The proposed Domain Adaptive Network (DAN) is attached to the YOLOv4 object detector only during training in order to learn domain invariant features. Indeed, YOLOv4 and DAN are trained in an end-to-end fashion. For inference, and during testing, domain-adaptive trained weights are used in the original YOLOv4 architecture (without the DAN network). Therefore, our proposed framework will not increase the underlying detector complexity during inference, which is an essential factor for many real-time applications such as autonomous driving. DAN uses the three distinct scale features of the backbone that are fed to the neck as inputs. It has several convolutional layers to predict the domain class (either source or target). Then, domain classification loss ($\mathcal{L}_{dc}$) is computed via binary cross entropy as follows: \begin{equation} \label{dc_loss} \mathcal{L}_{dc} = -\sum_{i,x,y} [ t_i \ln p_i^{(x,y)} + (1-t_i) \ln (1-p_i^{(x,y)})] \end{equation} Here, $t_i$ is the ground truth domain label for the i-th training image, with $t_i=1$ for source domain and $t_i=0$ for target domain. $p_i^{(x,y)}$ is predicted domain class probabilities for i-th training image at location $(x,y)$ of the feature map. DAN is optimized to differentiate between the source and target domains by minimizing this loss. On the other hand, the backbone is optimized to maximize the loss to learn domain invariant features. Thus, features of the backbone should be indistinguishable for the two domains. Consequently, this should improve the performance of object detection for the target domain. To solve the joint minimization and maximization problem, we employ adversarial leaning strategy\cite{GANs}. In particular, we achieve this contradictory objectives by using a Gradient Reversal Layer (GRL) \cite{grl,grl_J} between the backbone and the DAN network. GRL is a bidirectional operator that is used to realize two different optimization objectives. In the feed-forward direction, the GRL acts as an identity operator. This leads to the standard objective of minimizing the classification error when performing local backpropagation within DAN. On the other hand, for backpropagation toward the backbone network, the GRL becomes a negative scalar ($\lambda$). Hence, in this case, it leads to maximizing the binary-classification error; and this maximization promotes the generation of domain-invariant features by the backbone. To compute the detection loss ($\mathcal{L}_{det}$) \cite{yolo}, only source images are used because they are annotated with ground-truth objects. Consequently, all three parts of YOLOv4 (\textit{i.e.} backbone, neck and head) are optimized via minimizing $\mathcal{L}_{det}$. On the other hand, both source labeled images and target unlabeled images are used to compute the domain classification loss ($\mathcal{L}_{dc}$) which is used to to optimize DAN via minimizing it, and the backbone via maximizing it. As a result, both $\mathcal{L}_{det}$ and $\mathcal{L}_{dc}$ are used to optimize the backbone. In other words, the backbone is optimized by minimizing the following total lose: \begin{equation} \label{loss_backnone} \mathcal{L}_t = \mathcal{L}_{det} + \lambda \mathcal{L}_{dc} \end{equation} where $\lambda$ is a negative scalar of GRL that balances a trade-off between the detection loss and domain classification loss. In fact, $\lambda$ controls the impact of DAN on the backbone. \subsection{DAN Architecture} Instead of applying domain adaptation for only the final scale of the feature extractor as done in the Domain Adaptive Faster R-CNN architecture \cite{DA_faster_RCNN}, we develop domain adaptation for three scales separately to solve gradient vanishing problem. In other word, applying domain adaptation only to the final scale (F3) does not make significant impact to the previous scales (F1 and F2) due to gradient vanishing problem as there are many layers between them. As a result, we employ a multiscale strategy that connects the three features F1, F2, and F3 of the backbone to the DAN through three corresponding GRLs as shown in Figure \ref{fig:arch}. For each scale, there are two convolutional layers after GRL, the first one reduces the feature channels by half, and the second one predict the domain class probabilities. Finally, a domain classifier layer is used to compute the domain classification loss. \section{Experiments} In this section, we evaluate our proposed MS-DAYOLO. We modified the official source code of YOLOv4 that is based on the darknet platform\footnote{https://github.com/AlexeyAB/darknet}; and we developed new code to implement our proposed method\footnote{https://github.com/Mazin-Hnewa/MS-DAYOLO}. \subsection{Setup} For training, we used the default settings and hyper-parameters that were used in the original YOLOv4 \cite{yolov4}. The network is initialized using the pre-trained weights file. The training data includes two sets: source data that has images and their annotations (bounding boxes and object classes), and target data without annotation. Each batch has 64 images, 32 from the source domain and 32 from target domain. Based on prior works \cite{DA_faster_RCNN, zhu2019adapting,he2019multi} and our experience, we set $\lambda =0.1$ for all experiments. For evaluation, we report Average Precision (AP) for each class as well as mean average precision (mAP) with threshold of 0.5 \cite{2011pascal} using testing data that has labeled images of target domain. We have followed other prior domain adaptive object-detection works that use the same threshold value of 0.5. In an extended future version of this work we plan to study the impact of other threshold values. We compare our proposed method with the original YOLOv4, both applied to the same target domain validation set. It is worth noting that most prior domain-adaptive object detection methods used Faster R-CNN as the baseline object detector \cite{DA_faster_RCNN,zhu2019adapting,wang2019few,saito2019strong,he2019multi}. Consequently, we do not compare our proposed method, which is based on the YOLOv4 detector, with those Faster R-CNN based methods. Such comparison would imply comparing different frameworks with completely different underlying-architectures for object detection. Domain shifts due to changes in weather conditions is one of the most prominent reasons for discrepancy between the source and target domains. Reliable object detection systems in different weather conditions are essential for many critical applications such an autonomous driving. As a result, we focus on presenting our evaluation results of our proposed MS-DAYOLO by studying domain shifts under changing weather condition for autonomous driving. To achieve this, we use different driving datasets: Cityscapes \cite{cityscapes}, Foggy Cityscapes \cite{Foggy_cityscapes}, BDD100K \cite{bdd100k}, and INIT \cite{init}. \subsection{Results and Discussion} \textbf{Clear $\rightarrow$ Foggy}: we discuss the ability of our proposed method to adapt from clear to foggy weather as has been done by many recent works in this area \cite {DA_faster_RCNN,zhu2019adapting,wang2019few,saito2019strong,he2019multi}. Original YOLOv4 is trained using the Cityscapes training set. While MS-DAYOLO is trained using the Cityscapes training set as source domain and the Foggy Cityscapes training set without labels as target domain. The Foggy Cityscapes validation set is used for testing and evaluation. Because Foggy Cityscapes training set is annotated, we are able to train the original YOLOv4 with this set to show the ideal performance (oracle). The Cityscapes dataset has eight classes. However, because the number of ground-truth objects for some classes (truck, bus, and train) is small (\textit{i.e.} less than 500 in training set, and 100 in testing set), the performance measure will be inaccurate for these classes. As a result, we exclude them and compute mAP based on the remaining classes. To show the important of applying domain adaptation to three distinct scales of the backbone network, we conducted an ablation study. First, we applied domain adaptation, separately, to each of the three scales of features that are fed into the neck of the YOLOv4 architecture. Then we apply domain adaptation to different combinations of two scales at a time. Finally, we compared the results with the performance of applying these combinations of the study with the performance of applying our MS-DAYOLO to all three scales. Table \ref{mAP_cityscapes} summarizes the performance results. It is clear that based on these results, we can conclude that applying domain adaptation to all three feature scales improves the detection performance on target domain, and achieves the best result. Moreover, our proposed MS-DAYOLO outperforms the original YOLOv4 approach by significant margin, and it almost reaches the performance of the ideal (oracle) scenario, especially for some object classes in terms of average precision and overall mAP. Figure \ref{fig:cityscapes_examples} shows examples of detection results of the proposed method as compared to the original YOLOv4. \begin{table}[!t] \centering \caption{Quantitative results on adaptation from clear to foggy weather of the Cityscapes dataset. \checkmark means that domain adaptation is applied to the feature scale(s) using our MS-DAYOLO. The classes are P:Person, R:Rider, C:Car, M: Motorcycle, and B: Bicycle. Results in red are obtained using the baseline YOLO for comparison with our method.} \label{mAP_cityscapes} \begin{tabular} {|m{2.6em}|m{0.1em}m{0.1em}m{0.5em}|m{1.4em}m{1.4em}m{1.4em}m{1.4em}m{1.7em}|m{1.7em}|} \hline Method & F1 & F2 & F3 & P & R & C & M & B & mAP \\ \hline YOLO & & & & \textcolor{red}{31.57}& \textcolor{red}{38.27} & \textcolor{red}{46.93} & \textcolor{red}{16.75} & \textcolor{red}{30.32} & \textcolor{red}{32.77}\\ \hline \multirow{7}{*} {Ours} & & & \checkmark & 36.84& 42.84& 53.69& 24.77& 32.35 & 38.10\\ \cline{2-10} & &\checkmark & & 37.08& 41.49 & 54.49& 26.22& 32.43 & 38.34\\ \cline{2-10} & \checkmark & & & 36.28 & 44.22 & 53.10 & 25.81& 35.87 & 39.06 \\ \cline{2-10} & & \checkmark& \checkmark & 36.62& 42.68& 55.70 & 26.09 & 33.52& 38.92 \\ \cline{2-10} & \checkmark & \checkmark& &37.50 & 42.48 & 54.53 &27.84 & 34.75 & 39.42 \\ \cline{2-10} &\checkmark & & \checkmark & 36.41& \textbf{46.06}& 52.19& 22.48 &34.99 &38.43\\ \cline{2-10} &\checkmark & \checkmark& \checkmark &\textbf{38.62} &45.52& \textbf{55.85} & \textbf{28.82} & \textbf{36.46} & \textbf{41.05}\\ \hline \hline \multicolumn{4}{|l|}{Oracle} & 42.35 & 49.50 & 63.59 & 31.10 & 39.68 & 45.24 \\ \hline \end{tabular} \end{table} \textbf{Sunny $\rightarrow$ Rainy}: we also discuss the ability of our proposed method to adapt from sunny to rainy weather using BDD100K \cite{bdd100k} and INIT \cite{init} datasets. We extracted "sunny weather" labeled images for the source data, and "rainy weather" unlabeled images to represent the target data. As before, the original YOLOv4 is trained using only source data (\textit{i.e.} labeled sunny images). Meanwhile, our proposed MS-DAYOLO is trained using both source and target data (\textit{i.e.} labeled sunny images and unlabeled rainy images). In addition, we extracted labeled images from the rainy-weather data for testing and evaluation. The results are summarized in Table \ref{mAP_rainy}. A clear performance improvement is achieved by our method over the original YOLO in both datasets. \begin{table}[!t] \centering \caption{Quantitative results on adaptation from sunny to rainy weather of the BDD100K and INIT datasets. The classes of BDD100K are V: Vehicle, P:Person, TS:Traffic Sign, and TL:Traffic Light. The classes of INIT are P:Person, C: Car, and SLS: Speed Limit Sign.} \label{mAP_rainy} \begin{tabular} {|c|m{2.9em}m{2.9em}m{2.8em}m{2.8em}|c|} \hline \multicolumn{6}{|c|}{BDD100K} \\ \hline Method & V & P & TS & TL & mAP \\ \hline YOLO & 72.54 & 41.54 &56.06 &47.07& 54.30 \\ \hline Ours & \textbf{73.74} & \textbf{45.37} & \textbf{58.32} & \textbf{48.00}& \textbf{56.36} \\ \end{tabular} \vspace{-0.45cm} \end{table} \begin{table}[!t] \centering \label{mAP_init} \begin{tabular} {|c|m{4.2em}m{4.2em}m{4.2em}|c|} \hline \hline \multicolumn{5}{|c|}{INIT} \\ \hline Method & P & C & SLS & mAP\\ \hline YOLO & 44.52&74.48&48.39& 55.80 \\ \hline Ours & \textbf{48.80} &\textbf{76.03} & \textbf{50.00} & \textbf{58.28} \\ \hline \end{tabular} \end{table} \section{Conclusion} In this paper, we proposed a multiscale domain adaptation framework for the popular real time object detector YOLO. Specifically, under our MS-DAYOLO, we applied domain adaptation to three different scale features within the YOLO feature extractor that are fed to the next stage. The proposed method improves the overall detection performance under the target domain because it produces robust domain invariant features that reduce the impact of domain shift. Based on various experimental results, our framework can successfully adapt YOLO to target domains without any need for annotation. Furthermore, the proposed MS-DAYOLO outperformed state-of-the-art YOLOv4 under diverse testing scenarios for autonomous driving applications. \textbf{Acknowledgement:} This work has been supported by the Ford Motor Company under the Ford-MSU Alliance Program. \bibliographystyle{IEEEbib}
{'timestamp': '2022-02-14T02:02:33', 'yymm': '2106', 'arxiv_id': '2106.01483', 'language': 'en', 'url': 'https://arxiv.org/abs/2106.01483'}
arxiv
\section{Introduction}\label{sec:norm-pgd-introduction} \IEEEPARstart{D}{eep} neural networks~(DNNs) have been remarkably successful for a wide range of perceptual problems: image classification~\cite{he2015deep}, object detection~\cite{shaoqing2015fasterrcnn}, speech recognition~\cite{hinton2012deep}, machine translation~\cite{sutskever2014sequence}. Despite their excellent performance in an extensive range of practical applications, DNNs are sensitive to small, imperceptible perturbations in the input data. This intriguing vulnerability was discovered by~\citet{szegedy2014intriguing}. It was found that it is possible to perturb any given image in such a way that deep neural network misclassifies it with high confidence, but the image remains visually indistinguishable from the original image to a human observer. The lack of robustness is not specific to convolutional neural networks~(CNNs) for image recognition problems. Subsequently, it was found that recurrent neural networks~(RNNs) are susceptible to perturbations in text for language understanding task~\cite{liang2018deeptext} and audio for speech recognition task~\cite{carlini2018audio}. The lack of robustness to small, imperceptible perturbations is counter-intuitive. Unlike state-of-the-art deep neural networks models, human vision is remarkably robust to variations in the input, e.g.~changes in the lighting condition or changes in the object shape or pose. For example, if someone wants to conceal his or her identity from the police, the person will have to wear a mask or undergo cosmetic surgery. In comparison, an adversary needs to change only a few pixels in the image to fool a state-of-the-art facial recognition system~\cite{su2019onepixel}. Additionally, the existence of adversarial examples poses a serious concern for the application of deep neural networks in safety and security-critical applications~\cite{papernot2016limitations}. For example, recent studies showed that the attacks could be applied in the physical world~\cite{kurakin2016adversarialexamples,eykholt2018robust}. The problem of adversarial examples has spurred significant interest in the research of deep neural networks. The field of research in the area of robust deep learning can be broadly divided into the research on attacks~\cite{dezfooli2015deepfool,carlini2016towards,croce2019minimally} and the research on the defences~\cite{goodfellow2014explaining,madry2017towards,matyasko2017margin}. Like in an arms race, these two sides compete with each other: new defences introduced to protect against existing attacks; new attacks introduced to counteract existing defences. Since this vulnerability was discovered, dozens of techniques have been proposed to improve robustness to adversarial noise. To no avail, the problem of training a robust deep neural network remains unsolved. It's now even speculated that adversarial examples could fool time-limited human observers~\cite{elsayed2018fool}. The goal of the adversarial attack is to find a minimal $l_p$-norm perturbation that changes the model's prediction. Solving this non-convex constrained minimisation problem has proven to be challenging~\cite{carlini2019evaluating}. Existing attacks, such as C\&W~\cite{carlini2016towards} and EAD~\cite{chen2018ead}, in place of the original constrained problem, solve a sequence of unconstrained problems for multiple values of the regularisation weight $\lambda$ selected using line search or binary search. The attack's optimisation search needs to be restarted multiple times for each value $\lambda$, which increase the computational cost of the attack. Other methods, such as B\&B~\cite{brendel2019accurate} and FAB~\cite{croce2019minimally} attacks, are either limited to the specific norms or produce sub-optimal results. Fast, general and accurate attack, such as PGD~\cite{kurakin2016adversarialexamples,madry2017towards}, reformulates the original norm minimisation problem with non-convex error constraint as a surrogate loss minimisation with convex $l_{p}$-norm perturbation constraint. For this ``simpler'' problem, projected gradient descent attack (PGD) is an optimal first-order adversary~\cite{madry2017towards}. However, PGD attack does not explicitly minimise the perturbation $l_p$-norm. Instead, PGD attack minimises the model's accuracy at the threshold $\epsilon$. PGD attack needs to be restarted multiple times to evaluate the robust accuracy at multiple thresholds. In this work, we introduce a fast and efficient adversarial attack. Our attack directly optimises the original non-convex constrained norm minimisation problem without intensive optimisation restarts. We interpret optimising the Lagrangian of the attack as playing a two-player game. The first player minimises the Lagrangian wrt the adversarial noise, while the second player maximises the Lagrangian wrt the regularisation penalty, which penalises the first player for the violation of the misclassification constraint. Then, we apply primal-dual gradient descent to simultaneously update primal and dual variables to find the minimal adversarial perturbation. In addition, we introduce primal-dual proximal gradient descent attack for non-smooth $l_p$-norm minimisation, such as $l_{\infty}$-, $l_1$- and $l_0$-norms. For RGB images, we propose a group $l_{0}^G$-norm proximal operator, which we use to minimise the number of perturbed pixels. We demonstrate in the experiments that our attack outperforms current state-of-the-art $l_{\infty}$-, $l_2$-, $l_1$- and $l_0$-attacks on {MNIST}, {CIFAR-10} and {Restricted ImageNet} datasets against unregularised and adversarially trained models. The source code to reproduce all our experiments is available at~\url{https://github.com/aam-at/cpgd}. We hope that our attack will be considered as a benchmark for a future comparison between different defence methods. \section{Related work}\label{sec:related-work} A plethora of adversarial attacks and defences against adversarial attacks have been proposed since the discovery of the vulnerability of DNNs to adversarial examples. In this section, we attempt to review the landscape of the research on adversarial attacks. Due to the space constraints, only selected relevant works are discussed. For a detailed overview of this diverse and active field, interested readers may refer to~\cite{yuan2019adversarial}. Adversarial attacks can be broadly categorized based on the attacker's knowledge about the model~(white-box versus black-box attacks), the attack's specificity~(targeted versus non-targeted attacks), and the perturbation measurement~($l_{\infty}$-, $l_2$-, $l_1$-, and $l_0$-norm attacks). White-box attacks have full knowledge of the neural network model, including training data, model architecture, model weights, and model hyperparameters. Adversarial examples are generated using the model's gradients. Black-box attacks have access to the model's outputs but do not know the training data and the model architecture. This assumption is valid for attacking online ML services. Targeted attacks aim to produce a targeted misclassification, whereas the adversarial label for an untargeted attack can be arbitrary except the original one. \subsection{White-box Adversarial Attacks} \cite{szegedy2014intriguing} first discovered the phenomenon of adversarial examples and introduced a targeted gradient-based adversarial attack against DNNs known as {LBFGS-B} method. {LBFGS-B} method is the basis of many attack algorithms. Starting with an input $\mathbf{x}$ with a label $y$, the authors minimised the norm of the perturbation $\mathbf{r}$ subject to the constraint that the neural network misclassifies the adversarial example $\mathbf{x} + \mathbf{r}$ as some target $y_t \neq y$. A surrogate loss function is introduced in place of the original non-differentiable error constraint. Then, an unconstrained optimisation problem is solved using {LBFGS-B} optimiser for multiple values of the constraint regularisation weight $\lambda$, which is selected using a line search. However, this attack is impractical against large models because 1) it uses computationally intensive {LBFGS-B} method; 2) it requires full optimisation for each value of the regularisation weight $\lambda$. \subsubsection{\textbf{$l_{\infty}$-norm attacks}} \cite{goodfellow2014explaining} reformulated the attack's problem as minimising the misclassification surrogate loss subject to the $l_p$-norm perturbation constraint. Then, they noticed that after applying the first-order approximation to the surrogate loss, the normalised loss gradient wrt inputs is the adversarial direction. In particular, the adversarial perturbation for the $l_{\infty}$-norm constraint is the scaled sign of the gradient. This method, known as fast gradient method~(FGM), is inaccurate but extremely fast. \cite{kurakin2016adversarialexamples,madry2017towards} proposed an iterative version of FGM, which is known as basic iterative method~(BIM)~\cite{kurakin2016adversarialexamples} or projected gradient descent~(PGD)~\cite{madry2017towards}. PGD iteratively takes a step in the direction of FGM attack and constrains the perturbation after each update. \cite{madry2017towards} argued that PGD is an optimal first-order adversary. PGD attack is a recommended starting attack for $l_{\infty}$-norm distortions~\cite{carlini2019evaluating}. \cite{dong2018iterative} integrated the momentum into PGD iterative process. Distributionally adversarial attack~(DAA)~\cite{zheng2018distributionally} finds an adversarial data distribution that maximises the generalisation risk. The optimal data distribution is described by PDE, which they solve using particle optimisation. \cite{pooladian2020principled} introduced a proximal log-barrier attack (ProxLogBarrier), which, similar to our work, uses proximal optimisation for non-smooth norms. In comparison with our work, ProxLogBarrier attack: 1) requires an adversarial starting point, while any starting point can be used for our attack; 2) optimises the log-barrier loss, while our primal-dual attack solves for the original error constraint. \subsubsection{\textbf{$l_{2}$-norm attacks}} In seminal work, \citet{carlini2016towards} formally defined the problem of finding adversarial perturbation. They introduced C\&W attack that solves a sequence of unconstrained optimisation problems, similar to~\cite{szegedy2014intriguing}. They investigated how the choice of the optimiser, the surrogate loss function, and handling of the box constraints affect the attack's success. C\&W is the recommended attack for the assessment of DNNs robustness to $l_2$-norm perturbations~\cite{carlini2019evaluating}. C\&W, like {LBFGS-B} attack, requires full optimisation for each value of the regularisation weight $\lambda$, which increases the attack's computational cost. DeepFool~\cite{dezfooli2015deepfool} finds the closest class boundary and takes a step in that direction. DeepFool attack does not enforce box constraints and does not explicitly minimise the norm of the perturbation. The optimisation process stops as soon as adversarial perturbation is found. Fast Adaptive Boundary attack~(FBA)~\cite{croce2019minimally} solves the box-constrained $l_p$-norm projection on the decision hyperplane exactly and introduces a biased backward step to minimise the perturbation norm. Decoupling direction and norm $l_2$-attack~(DDN)~\cite{rony2019decoupling} proposes to adjust the radius of $l_2$-norm ball used for the $l_2$-norm projection. If the perturbation is adversarial/not adversarial, the radius of $l_2$-norm projection ball can be decreased/increased, respectively. \subsubsection{\textbf{$l_{1}$-norm attacks}} \cite{chen2018ead} introduced $l_1$-norm attack known as Elastic-net~(EAD). EAD attack, similar to C\&W, solves a sequence of unconstrained optimisation problems. To minimise non-smooth, subdifferentiable $l_1$-norm, they proposed to use fast iterative shrinkage-thresholding algorithm~(FISTA)~\cite{beck2009thresholding}. EAD attack is recommended $l_1$-norm attack~\cite{carlini2019evaluating}. SparseFool~(SF)~\cite{modas2019sparsefool} is a geometry-inspired $l_1$-norm attack that uses DeepFool attack~\cite{dezfooli2015deepfool} as subprocedure to estimate the local curvature of the decision boundary. They developed an efficient algorithm to compute $l_1$-projection of the perturbation on the decision boundary subject to the box constraints. Sparse $l_1$ descent attack~(SLIDE)~\cite{tramer2019adversarial} is a variant of PGD attack for $l_1$-norm. SLIDE iteratively takes a small step in the direction of the $q$-th percentile of the loss gradient and applies $l_1$-norm projection, which can be computed efficiently in $\mathcal{O}\left(n \log{n} \right)$ time~\cite{duchi2008efficient}. \subsubsection{\textbf{$l_{0}$-norm attacks}} $l_{\infty}$ and $l_2$ adversarial attacks often produce perturbations that change a large number of pixels in the image. Several attack methods have been proposed to minimise non-convex $l_0$-quasinorm. \cite{papernot2016limitations} proposed a targeted adversarial attack, known as Jacobian saliency map attack~(JSMA), which minimises $l_0$-norm perturbation constraint. JSMA uses the Jacobian matrix to select and modify a pair of the most salient pixels in the image. This process is repeated until the adversarial perturbation is found. \cite{su2019onepixel} found that it is possible to change the prediction of the model by modifying a single pixel. To generate adversarial examples, they applied differential evolution~(DE) algorithm on the population of vectors that change a single pixel in the image. \cite{croce2019sparse} introduced $l_0$-norm variant of PGD attack and black-box, score-based $l_0$-norm attack known as CornerSearch~(CS) attack. PGD-$l_0$ attack iteratively takes a small step in the direction of the loss gradient and applies $l_0$-norm projection. CS attack creates a probability distribution of the most salient pixels from which the adversarial perturbation is sampled. \subsection{Black-box adversarial attacks} A black-box adversary has limited knowledge about the model, e.g.~model prediction scores or outputs. Black-box attacks are more difficult to perform than white-box attacks because we do not know the model's gradient. \cite{papernot2016practical}~introduced a practical black-box adversarial attack based on the property that adversarial examples can transfer between models. They trained a substitute model on the model's task. Then, adversarial examples generated for the substitute model are used to attack the target model. \citet{brendel2018decisionbased} introduced a decision-based attack that estimates the decision boundary using rejection sampling. Starting at some adversarial input, they randomly draw a random perturbation from the candidate distribution and minimise the distance to the original input. \cite{guo2019simpleblackbox} sampled a random perturbation from an orthonormal basis of discrete cosine transform~(DCT), which improves query-efficiency of the decision-based attack. Gradient-based attacks should be almost always more precise than gradient-free attacks. However, gradient masking~\cite{papernot2016practical} can fool gradient-based attacks and give a false sense of security~\cite{athalye2018obfuscated}. If the defence obfuscates the gradients, gradient-free attacks often perform better than white-box attacks. \cite{carlini2019evaluating} suggested that defences should be tested on both white-box and black-box adversaries. If the model is more robust to white-box adversaries, then the model obfuscates the gradients. \section{Adversarial Attacks on DNNs}\label{sec:advers-attacks-dnns} In this section, we introduce a general formulation of the attack against deep neural networks in white-box settings, where the attacker has full knowledge about the model. Let $f\left(\cdot \right)$ be the mapping from the space of input pixels to the unnormalised predictive distribution on discrete label output space $f : \mathbb{R}^N \to \mathbb{R}^k$ where $k$ is the number of classes. The network prediction is the label with the highest score $\hat{k}(\mathbf{x})=\argmax f(\mathbf{x})$. For a given input image $\mathbf{x}$ with the label $y$, an adversary aims to find a minimal adversarial perturbation $\mathbf{r}$ wrt some norm $\norm{\cdot}$, such that after adding the perturbation to the original image $\mathbf{x}$ it changes the network prediction $\hat{k}(\mathbf{x} + \mathbf{r}) \neq y$. We can formulate the attack as the following optimisation problem: \begin{equation} \begin{aligned} & \underset{\mathbf{r}}{\text{min}} & & \norm{\mathbf{r}} \\ & \text{s.t.} & & \hat{k}(\mathbf{x} + \mathbf{r}) \neq y \\ & & & \mathbf{x} + \mathbf{r} \in \mathbb{C} \end{aligned}\label{eq:general_perturbation} \end{equation} where $\mathbf{r}$ and $\mathbf{x} + \mathbf{r}$ is the \textit{adversarial} noise and the \textit{adversarial example} respectively; $\mathbb{C}$ is the input domain, e.g. $\left[0, 1 \right]^{N}$ box constraints for the normalised image. The problem above is an example of an untargeted adversarial attack. A targeted adversarial attack searches for the perturbation which changes the network prediction to the specific target: $\hat{k}(\mathbf{x} + \mathbf{r}) = y_{t}$. The optimisation problem in~\Cref{eq:general_perturbation} is a non-convex constrained norm minimisation problem. Solving it is a challenging and non-trivial task because 1) the misclassification constraint is non-convex and non-differentiable; 2) the norm of the perturbation is non-differentiable, e.g. $l_0$- and $l_1$-, and $l_{\infty}$-norms. A plethora of attack methods have been proposed to solve the adversarial attack problem. \citet{szegedy2014intriguing} first introduced a blueprint for a targeted white-box adversarial attack, {LBFGS-B} method, against DNNs in~{\protect\NoHyper\citeyear{szegedy2014intriguing}\protect\endNoHyper}. The authors optimised the following unconstrained minimisation problem: \begin{equation} \begin{aligned} & \underset{\mathbf{r}}{\text{min}} & & \norm{\mathbf{r}} + \lambda \mathcal{L}\left(\mathbf{x} + \mathbf{r}; y\right) \\ & \text{s.t.} & & \mathbf{x} + \mathbf{r} \in \mathbb{C} \end{aligned}\label{eq:szegedy_unconstrained_problem} \end{equation} where $\lambda$ is the regularisation penalty which penalises the violation of the misclassification constraint; $\mathcal{L}$ is a surrogate loss function, which is minimised when $\hat{k}(\mathbf{x} + \mathbf{r}) \neq y$. The solution of the problem in~\Cref{eq:szegedy_unconstrained_problem} for a fixed $\lambda$ can be found using an off-shelf optimiser, e.g. {LBFGS-B} in~\cite{szegedy2014intriguing} or ADAM in~\cite{carlini2016towards}. Finally, a line search or a binary search is performed to find the optimal regularisation weight $\lambda^{*}$, which minimises $\norm{\mathbf{r}}$. Optimisation of~\Cref{eq:szegedy_unconstrained_problem} needs to be restarted for each $\lambda$, which significantly increases the attack cost. Besides that, the optimisation search above requires gradient, so this procedure is not applicable for non-smooth or non-differentiable function minimisation, e.g. $l_{\infty}$- or $l_0$-norms. \citet{goodfellow2014explaining} reformulated the original non-convex constrained minimisation problem as the problem of minimising the differentiable surrogate loss function subject to the convex $l_p$-norm perturbation constraint: \begin{equation} \begin{aligned} & \underset{\mathbf{r}}{\text{min}} & & \mathcal{L}\left(\mathbf{x} + \mathbf{r}; y\right) \\ & \text{s.t.} & & \norm{\mathbf{r}} \leq \epsilon \\ & & & \mathbf{x} + \mathbf{r} \in \mathbb{C} \end{aligned}\label{eq:pgd_attack} \end{equation} They observed that after applying the first-order approximation to the surrogate loss $\mathcal{L}$, the normalised gradient of the loss is the solution of the $l_p$-norm constrained minimisation problem. In particular, the adversarial direction for the $l_{\infty}$-norm constraint is the sign of the loss gradient wrt inputs: $\mathbf{r} = \sign \nabla_{\mathbf{x}} \mathcal{L}(\mathbf{x}; y)$. This method, known as fast gradient sign method~(FGSM), is inaccurate but has dramatically increased the speed of generating adversarial noise. \cite{kurakin2016adversarialexamples,madry2017towards} proposed an iterative version of FGSM attack, known as projected gradient descent~(PGD). PGD iteratively updates the perturbation $\mathbf{r}$ by taking a small step in the direction of the adversarial target and constraints the total perturbation to~$\epsilon$ after each iteration. PGD is a simple, fast and accurate attack. This attack has also been extended to other norms, including non-differentiable $l_{1}$- and $l_0$-norms~\cite{tramer2019adversarial, croce2019sparse}. However, PGD does not explicitly minimise the $l_p$-norm of the perturbation $\mathbf{r}$. PGD attack needs to be restarted $N$ times to evaluate robustness at $N$ distinct thresholds $\epsilon$, which increases the attack's computational cost. \section{Primal-Dual Gradient Descent Attack} Let us revisit the Lagrangian of the original non-convex constrained $l_p$-norm minimisation problem in~\Cref{eq:general_perturbation}: \begin{equation} \mathbb{L}(\mathbf{r}, \lambda) = \norm{\mathbf{r}} + \lambda \mathrm{I}\left[ \hat{k}\left(\mathbf{x} + \mathbf{r}\right) \neq y \right]~\label{eq:lagrangian_general_attack} \end{equation} where $\lambda$ is a dual variable, which controls the weight of the misclassification constraint; $\mathrm{I}$ is an indicator function. For brevity, we omit the domain constraints $\mathbf{x} + \mathbf{r} \in \mathbb{C}$ as we can enforce it easily for typical inputs, e.g.~$\left[0, 1\right]$ box-projection $\mathrm{\Pi}_{\mathbb{C}}$ for natural images. As $\lambda \to \infty$, the solution of the problem in~\Cref{eq:lagrangian_general_attack} converges to the feasible solution of the original non-convex constrained norm minimisation problem. Optimising the Lagrangian in~\Cref{eq:lagrangian_general_attack} can be interpreted as playing a two-player game: the $\mathbf{r}$-player seeks to minimise the Lagrangian wrt primal variable $\mathbf{r}$; the $\lambda$-player wishes to maximise the Lagrangian wrt dual variable $\lambda$. The dual variable $\lambda$ penalises the $\mathbf{r}$-player for the violation of the misclassification constraint. C\&W attack~\cite{carlini2016towards} uses a binary search to find an optimal value of the dual variable $\lambda^{*}$. For a fixed $\lambda$, each iteration of binary search requires full optimisation of the Lagrangian to find an optimal value of the primal variable $\mathbf{r}^{*}$, which increases the attack's running time. We propose a primal-dual gradient algorithm to simultaneously optimise primal and dual variables. Unfortunately, we cannot calculate the constraint gradients to optimise the Lagrangian $\mathcal{L}(\mathbf{r}, \lambda)$ using the first-order algorithm because the misclassification constraint is non-differentiable. In line with the previous research, we express the error constraint in terms of the prediction margin. We define the prediction margin $m_y(\mathbf{x})$ for the input $\mathbf{x}$ with label $y$ as follows: \begin{equation} m_y(\mathbf{x}) = f(\mathbf{x})_y - \underset{i \neq y}{\max} \ f(\mathbf{x})_i \label{eq:prediction_margin} \end{equation} The input $\mathbf{x}$ with the label $y$ is misclassified if and only if $m_y(\mathbf{x}) < 0$. Some popular smooth relaxations of $\textfrac{0}{1}$-indicator function are squared loss, hinge loss, and logistic loss. We adopt logistic loss $\log\left(1 + e^{m_y\left(\mathbf{x}\right)}\right)$ instead of hinge loss $\max\left(0, 1 + m_y\left(\mathbf{x}\right)\right)$ as in~\cite{carlini2016towards} because logistic loss is differentiable everywhere unlike hinge loss. Using our surrogate loss $\mathcal{L}$ for the misclassification constraint, we introduce two proxy-Lagrangians for the $\mathbf{r}$-player and the $\mathbf{\lambda}$-player as follows: \begin{equation} \begin{split} \mathbb{L}_{\mathbf{r}}(\mathbf{r}, \mathbf{\lambda}) &= \lambda_1 \norm{\mathbf{r}} + \lambda_2 \mathcal{L}\left(\mathbf{x} +\mathbf{r}, y\right) \\ \mathbb{L}_{\lambda}(\mathbf{r}, \mathbf{\lambda}) &= \lambda_2 \mathrm{I}\left[ \hat{k}\left(\mathbf{x} + \mathbf{r}\right) \neq y \right] \end{split} \label{eq:proxy-lagrangian} \end{equation} where $(\lambda_{1}, \lambda_2) \in \Lambda$ and $\Lambda \subseteq \mathbb{R}_+^2$ is a 2-dimensional simplex. In the formulation above, we represent $\lambda \in \mathbb{R}_+$ as point in the 2-dimensional simplex $\lambda = \sfrac{\lambda_2}{\lambda_1}$. Note that only the $\mathbf{r}$-player uses surrogate loss in place of the misclassification constraint, while the $\lambda$-player uses original non-differentiable misclassification constraint. The $\lambda$-player chooses how much the $\mathbf{r}$-player should penalize surrogate misclassification constraint, but does so in a way as to satisfy original non-differentiable constraint. The proxy-Lagrangians formulation in~\Cref{eq:proxy-lagrangian} avoids the issue of the non-differentiable error constraint. The $\mathbf{r}$-player wishes to find perturbation $\mathbf{r}$ which minimises $\mathbb{L}_{\mathbf{r}}(\mathbf{r}, \lambda)$, while the $\lambda$-player wants to maximise $\mathbb{L}_{\lambda}(\mathbf{r}, \lambda)$. Unfortunately, the proxy-Lagrangian formulation corresponds to a non-zero-sum game because two players optimise two different functions. Fortunately, this proxy-Lagrangian formulation admits a weaker type of equilibrium, $\Phi$-correlated equilibrium~(see~\cite[Theorem 2]{cotter2019twoplayer} for the details). \begin{algorithm}[!b] \caption{Primal-Dual Gradient Descent Attack~\label{alg:primal_dual_gradient}} \begin{algorithmic}[1] \REQUIRE Image $\mathbf{x}$, label $y$, initial perturbation $\mathbf{r}^{(0)}$, the total number of iterations $T$, learning rate $\theta_{\mathbf{r}}$ and $\theta_{\lambda}$. \ENSURE Adversarial perturbation $\mathbf{r}$. \STATE $\mathbf{r} \gets \mathbf{0}$ \FOR{$k \gets 1$ to $T$} \STATE Let $\nabla_{\mathbf{r}}^{(k)}$ be a gradient of $\mathbb{L}_{\mathbf{r}}(\mathbf{r}^{(k)}, \lambda^{(k)})$ \STATE Let $\nabla_{\lambda}^{(k)}$ be a gradient of $\mathbb{L}_{\lambda}(\mathbf{r}^{(k)}, \lambda^{(k)})$ \STATE Update $\mathbf{r}^{(k+1)} = \mathrm{\Pi}_{\mathbb{C}}^{\mathbf{x}}\left(\mathbf{r}^{(k)} - \theta_{\mathbf{r}} \nabla_{\mathbf{r}}^{(k)} \right)$\label{lst:update-primal} \STATE Update $\lambda^{(k+1)} = \mathrm{\Pi}_{\Lambda} \left(\lambda^{(k)} + \theta_{\lambda} \nabla_{\lambda}^{(k)} \right)$\label{lst:update-dual} \IF{$\hat{k}(\mathbf{x} + \mathbf{r}^{(k + 1)}) \neq y$ \AND $\norm{\mathbf{r}^{(k+1)}} \leq \norm{\mathbf{r}}$}\label{lst:save-best-1} \STATE $\mathbf{r}\label{lst:save-best-2} \gets \mathbf{r}^{(k+1)}$ \ENDIF\label{lst:save-best-3} \ENDFOR \end{algorithmic} \end{algorithm} Next, we describe our primal-dual gradient descent attack~(PDGD) in~\Cref{alg:primal_dual_gradient}. The $\mathbf{r}$-player minimises the external regret, while the $\lambda$-player minimises the swap regret. We perform gradient descent on primal variables using Adam~\cite{kingma2014adam}. Adam optimiser produced the smallest perturbation in our experiments. In~\cref{lst:update-primal}, after each iteration, we project the perturbation $\mathbf{r}$ on the domain constraints $\mathbb{C}$ using operator $\mathrm{\Pi}_{\mathbb{C}}^{\mathbf{x}}$, which we define as follows: $\mathrm{\Pi}_{\mathbb{C}}^{\mathbf{x}}(\mathbf{r}) = \mathrm{\Pi}_{\mathbb{C}}(\mathbf{x} + \mathbf{r}) - \mathbf{x}$. For the $\lambda$-player, we perform gradient ascent in the log domain. Gradient updates in the log domain are equivalent to multiplicative updates, which guarantee that dual variables remain positive. In~\cref{lst:update-dual}, after each update, we project $\lambda$ onto a 2-dimensional simplex. Intuitively, if at an iteration $k$, the misclassification constraint is not satisfied, we can increase the penalty $\lambda_2$ for the $\mathbf{r}$-player. If the constraint is satisfied, we can reduce the penalty weight $\lambda_2$. Finally, we record and store the best perturbation found during the optimisation in~\crefrange{lst:save-best-1}{lst:save-best-3}. Our primal-dual gradient descent attack has two shortcomings. First, we use gradient descent to minimise the external regret of the $\mathbf{r}$-player. Gradient descent for smooth convex functions has a convergence rate of $\mathcal{O}\left(\sfrac{1}{T}\right)$~\cite{boyd2004convex}, where $T$ is the number of gradient iterations. For the non-smooth functions, e.g. $l_1$-norm, the convergence rate of subgradient descent is $\mathcal{O}\left(\sfrac{1}{\sqrt{T}}\right)$, which is considerably slower than sublinear convergence of gradient descent for smooth functions. Secondly, our optimisation algorithm requires gradient, so it cannot be used to minimise non-differentiable functions, such as $l_0$-quasinorm. In the next section, we introduce a proximal formulation of our attack suitable for minimising any $l_p$-norm or function with a closed-form proximity operator, including non-differentiable functions. \section{Primal-Dual Proximal Gradient Descent} In this section, we introduce a proximal formulation of PDGD attack introduced in the previous section. Our primal-dual proximal gradient attack~(PDPGD) can be used to directly minimise any norm or function for which the proximal operator can be computed easily, including but not limited $l_{\infty}$-, $l_2$-, and $l_1$-norms, and $l_0$-quasinorm. First, we review some basics of proximal algorithms before introducing our attack. A detailed overview of proximal algorithms can be found in~\cite{parikh2014proximal}. We define the proximal operator of the scaled function $\lambda f$ where $\lambda > 0$ as follows: \begin{equation} \mathrm{prox}_{\lambda f}(x) = \underset{\mathbf{u}}{\argmin} \left( f(u) + \frac{1}{2\lambda}\norm{u - x}_2^2\right) \label{eq:proximity_operator} \end{equation} The following useful relation holds true for any proximal operator of the proper closed function $f$: \begin{equation} \mathrm{prox}_{\lambda f}(x) + \lambda \mathrm{prox}_{\lambda^{-1}f^{*}}(\nicefrac{x}{\lambda}) = x \label{eq:moreau_decomposition} \end{equation} where $f^{*}$ is the convex conjugate of $f$. The equation above is known as Moreau decomposition. Moreau decomposition is useful for deriving the proximal operators of $l_p$-norm functions. In particular, it implies that for any norm $\norm{\cdot}$: \begin{equation} \mathrm{prox}_{\lambda \norm{\cdot}}(x) + \lambda \mathrm{\Pi}_{\mathcal{B}}(\nicefrac{x}{\lambda}) = x \label{eq:moreau_decomposition_norm} \end{equation} where $\mathrm{\Pi}_{\mathcal{B}}$ is a projection operator on the unit $l_p$ ball $\mathcal{B}$. Let us revisit the $\mathbf{r}$-player proxy-Lagrangian: \begin{equation} \mathbb{L}_{\mathbf{r}}(\mathbf{r}, \mathbf{\lambda}) = \lambda_1 \norm{\mathbf{r}} + \lambda_2 \mathcal{L}\left(\mathbf{x} +\mathbf{r}, y\right) \label{eq:r_player_proxy_lagrangian} \end{equation} where $\mathcal{L}$ is the surrogate loss for the non-differentiable misclassification constraint. The goal of the $\mathrm{r}$-player is to minimise the proxy-Lagrangian function. However, if the norm $\norm{\cdot}$ is non-smooth, first-order subgradient descent needs $\mathcal{O}(\sfrac{1}{\epsilon^2})$ iterations to find $\epsilon$-error local minimum. Moreover, we cannot use first-order algorithms for $l_0$-norm minimisation because the gradient of $l_0$-norm is $\emptyset$ almost everywhere. We can address the above limitations in the framework of the proximal optimisation. First, we rewrite the proxy-Lagrangian for the $\mathbf{r}$-player as follows: \begin{equation} \mathbb{L}_{\mathbf{r}}(\mathbf{r}, \lambda) = \lambda \norm{r} + \mathcal{L}(\mathbf{x} + \mathbf{r}, y) \label{eq:r-player-proximal-lagrangian} \end{equation} where $\lambda \in \mathbb{R}_{+}$ and is equal to $\nicefrac{\lambda_1}{\lambda_2}$; $\mathcal{L}$ is the surrogate loss, e.g.~logistic or hinge loss. Consider a quadratic approximation of the $\mathbf{r}$-player proxy-Lagrangian at iteration $k$ and point $\mathbf{u}$: \begin{equation} \begin{split} \hat{\mathbb{L}}_{\mathbf{r}}^{(k)}(\mathbf{u}, &\lambda) = \lambda \norm{\mathbf{u}} + \mathcal{L}(\hat{\mathbf{x}}^{(k)} , y) \\ &+ \nabla \mathcal{L}(\hat{\mathbf{x}}^{(k)}, y)^T \left(\mathbf{u} - \mathbf{r}^{(k)}\right) + \frac{1}{2t}\norm{\mathbf{u} - \mathbf{r}^{(k)}}^{2}_2 \end{split} \label{eq:proximal_gradient_derivation} \end{equation} where $\mathbf{r}^{(k)}$ and $\hat{\mathbf{x}}^{(k)} = \mathbf{x} + \mathbf{r}^{(k)}$ are the adversarial perturbation and the adversarial example at iteration $k$, respectively. Note that we ignore not necessarily differentiable $l_p$-norm penalty when applying a quadratic approximation. We can find the perturbation at iteration $k+1$ by minimising the quadratic approximation above: \begin{equation} \begin{split} \mathbf{r}^{(k+1)} &= \underset{\mathbf{u}}{\argmin} \, \hat{\mathbb{L}}_{\mathbf{r}}^{(k)}(\mathbf{u}, \lambda) \\ =& \underset{\mathbf{u}}{\argmin} \, \lambda \norm{\mathbf{u}} + \frac{1}{2t} \norm{\mathbf{u} - \left(\mathbf{r}^{(k)} - t \mathcal{L}(\hat{\mathbf{x}}^{(k)}, y)\right)}_2^2 \\ \end{split} \end{equation} which is by the definition of the proximal operator in~\Cref{eq:proximity_operator} equivalent to: \begin{equation} \mathbf{r}^{(k+1)} = \mathrm{prox}_{\lambda \norm{},t} \left(\mathbf{r}^{(k)} - t \nabla \mathcal{L}(\hat{\mathbf{x}}^{(k)}) \right) \end{equation} where $t$ is a step size or a learning rate. The algorithm above is known as proximal gradient. Proximal gradient descent has a convergence rate of $\mathcal{O}\left(\sfrac{1}{T}\right)$ for non-smooth functions minimisation~\cite{parikh2014proximal}, which is faster than subgradient descent with a convergence rate of $\mathcal{O}\left(\sfrac{1}{\sqrt{T}}\right)$. We list our primal-dual proximal gradient~(PDPGD) attack in~\Cref{alg:primal_dual_proximal_gradient}. Compare to PDGD attack in~\Cref{alg:primal_dual_gradient}, PDPGD differs: 1) in~\cref{lst:primal-gradient}, it ignores non-smooth and not necessarily differentiable norm when computing gradient wrt primal variable $\mathbf{r}$; 2) in~\cref{lst:proximal-gradient}, it uses proximal gradient update instead of gradient update when updating primal variable $\mathbf{r}$. PDPGD attack can be used to minimise any function with a closed-form proximal operator. In this paper, we limit our discussion to the minimisation of $l_p$-norm perturbations. Next, we derive and list $l_{\infty}$-, $l_2$-, $l_1$-, and $l_0$-norm proximal operators used for our proximal attack. \begin{algorithm}[!b] \setcounter{ALC@unique}{0} \caption{Primal-Dual Proximal Gradient Descent Attack~\label{alg:primal_dual_proximal_gradient}} \begin{algorithmic}[1] \REQUIRE Image $\mathbf{x}$, label $y$, initial perturbation $\mathbf{r}^{(0)}$, the total number of iterations $T$, learning rate $\theta_{\mathbf{r}}$ and $\theta_{\lambda}$. \ENSURE Adversarial perturbation $\mathbf{r}$. \STATE $\mathbf{r} \gets \mathbf{0}$ \FOR{$k \gets 1$ to $T$} \STATE Let $\nabla_{\mathbf{r}}^{(k)}$ be a gradient of $\mathcal{L}(\mathbf{x} + \mathbf{r}^{(k)}, y)$ where $\mathcal{L}$ is the surrogate loss, e.g. logistic loss\label{lst:primal-gradient} \STATE Let $\nabla_{\lambda}^{(k)}$ be a gradient of $\mathbb{L}_{\lambda}(\mathbf{r}^{(k)}, \lambda^{(k)})$ \STATE Update $\mathbf{r}^{(k+1)} = \mathrm{\Pi}_C^{\mathbf{x}} \left( \mathrm{prox}_{\lambda \norm{\cdot}, \theta_{\mathbf{r}}}\left(\mathbf{r}^{(k)} - \theta_{\mathbf{r}} \nabla_{\mathbf{r}}^{(k)} \right)\right)$\label{lst:proximal-gradient} \STATE Update $\lambda^{(k+1)} = \mathrm{\Pi}_{\Lambda} \left(\lambda^{(k)} + \theta_{\lambda} \nabla_{\lambda}^{(k)} \right)$ \IF{$\hat{k}(\mathbf{x} + \mathbf{r}^{(k+1)}) \neq y$ \AND $\norm{\mathbf{r}^{(k+1)}} \leq \norm{\mathbf{r}}$} \STATE $\mathbf{r} \gets \mathbf{r}^{(k+1)}$ \ENDIF \ENDFOR \end{algorithmic} \end{algorithm} \subsection{$l_\infty$-attack} $l_{\infty}$-norm of the vector $\mathbf{x}$ returns the largest absolute element of the vector $\mathbf{x}$: $l_{\infty}(\mathbf{x}) = \max{\lvert \mathbf{\mathbf{x}}\rvert}$. Using Moreau decomposition in~\Cref{eq:moreau_decomposition_norm}, we can show that: \begin{equation} \boxed{\mathrm{prox}_{\lambda \norm{\cdot}_{\infty}}(\mathbf{x}) = \mathbf{x} - \lambda \mathrm{proj}_{\{\|\cdot\|_1 \leq 1\}}(\sfrac{\mathbf{x}}{\lambda})} \label{eq:linf_proximity_operator} \end{equation} where $\mathrm{proj}$ is a projection operator. $l_1$-norm projection can be computed efficiently in $\mathcal{O}\left(n \log{n} \right)$ time~\cite{duchi2008efficient}. \subsection{$l_2$-attack} Using Moreau decomposition in~\Cref{eq:moreau_decomposition_norm}, we can derive the proximal operator of the $l_2$-norm as follows: \begin{equation} \boxed{\mathrm{prox}_{\lambda \norm{\cdot}_2}(\mathbf{x}) = (1 - \sfrac{\lambda}{\norm{\mathbf{x}}_2})_+ \mathbf{x}} \label{eq:l2_proximity_operator} \end{equation} This operator is known as block soft thresholding operator. \subsection{$l_1$-attack} $l_1$-norm proximal operator is well-known in signal processing~\cite{beck2009thresholding}. It is defined as follows: \begin{equation} \boxed{\mathrm{prox}_{\lambda \norm{\cdot}_1}(\mathbf{x}) = \mathcal{T}_{\lambda}(\mathbf{x})} \label{eq:l1_proximity_operator} \end{equation} where $\mathcal{T}_{\lambda}(\mathbf{x}) = \mathrm{sign}(\mathbf{x}) (\mathbf{x} - \lambda)_+$ is soft-thresholding. \subsection{$l_0$-attack}\label{sec:primal_dual_l_0_prox_oper} $l_0$-norm is non-convex quasinorm. It measures the cardinality of the vector $\mathbf{x}$. The proximal operator of $l_0$-norm minimises the total number of non-zero elements in the vector $\mathbf{x}$, and it is defined as follows: \begin{equation} \boxed{\mathrm{prox}_{\lambda \norm{\cdot}_0}(x) = \mathcal{H}_{\sqrt{2\lambda}}(x)} \label{eq:l0_proximity_operator} \end{equation} where $\mathcal{H}_{\lambda}(x) = \mathrm{I}\left[x - \lambda\right]x$ is a hard-thresholding operator. The goal of the attack for the multichannel images is to minimise the number of non-zero pixels. We define group $l_{0,G}$-norm of the vector $x$ for the groups $\mathcal{G} = \left(g_1, g_2, \ldots, g_G \right)$ as the number of groups for which at least one element of the group is non-zero: \begin{equation} \norm{x}_{0}^G = \sum_{i=1}^{G} \mathrm{I}\left[ \max \abs{x}_{g_{i}} > 0 \right] \label{eq:group_l0_norm} \end{equation} For RGB images, the group partition $\mathcal{G}$ naturally corresponds to the pixels in the image. Then, we can derive the proximal operator of $l_{0,G}$-quasinorm as follows: \begin{equation} \boxed{\mathrm{prox}_{\lambda \norm{\cdot}_0}(x) = \mathcal{H}_{\sqrt{2\lambda}}^{G}(x)} \label{eq:group_l0_proximity_operator} \end{equation} where $\mathcal{H}_{\lambda}^{G}(x) = \mathrm{I}\left[ \max{\abs{x_{g}}} - \lambda\right] x$ is a group hard-thresholding operator which sets all elements in the group to 0 if the maximal element in the group is less than $\lambda$. Minimising $l_0$-norm is NP-hard problem. We also examine $l_p$-norm relaxation of the original $l_0$-norm minimisation problem where $0 < p \leq 1$. We consider $l_{\nicefrac{1}{2}}$-, $l_{\nicefrac{2}{3}}$-, and $l_1$-norm relaxation of $l_0$-norm because 1) it promotes sparsity of the solution; 2) its proximal operators can be computed in a closed-form~(see~\cref{eq:l1_proximity_operator} and~\cite{chen2016computing}). For RGB images, we apply $l_p$-norm proximal operator to the pixel with the maximal value and set other channels to 0 if the maximal pixel is 0 after applying the proximal operator. \section{Experiments} \textbf{Models}: We compare our attack to state-of-the-art attacks on MNIST, {CIFAR-10} and Restricted ImageNet~(R-ImageNet) datasets~\cite{tsipras2018robustness}. For each dataset, we consider a naturally trained model (\textit{plain}) and $l_{\infty}$~($l_{\infty}$-AT) and $l_2$~($l_2$-AT) adversarially trained models as in~\cite{madry2017towards}. The models for {MNIST} and {CIFAR-10} dataset are available at~\url{https://github.com/fra31/fab-attack}, while on R-ImageNet dataset we use models from~\cite{tsipras2018robustness}, which can be downloaded from~\url{https://github.com/MadryLab/robust-features-code}. The models on MNIST achieve the following clean accuracy on the test dataset (first 1000 test images): \textit{plain} 99.17\% (98.7\%), $l_{\infty}$-AT 98.53\% (98.5\%), and $l_2$-AT 98.95\% (98.7\%). The models on {CIFAR-10} achieve the following clean test accuracy (first 1000 test images): \textit{plain} 88.38\% (89.4\%), $l_{\infty}$-AT 79.9\% (80.4\%), and $l_2$-AT 80.44\% (80.7\%). The models on R-ImageNet achieve the following clean validation accuracy (first 1000 images of the validation set): \textit{plain} 94.5\% (94.9\%), $l_{\infty}$-AT 91.62\% (91.5\%), and $l_2$-AT 91.68\% (91.9\%). \textbf{Attacks}: We test the robustness of each model wrt to $l_{\infty}$-, $l_{2}$-, $l_1$-, and $l_0$-norm adversaries. We compare the performance of our attacks to attacks representing state-of-the-art for each norm: Brendel \& Bethge attack~(B\&B, $l_{\infty}$-, $l_2$-, $l_1$-, $l_0$-norms)~\cite{brendel2019accurate}; Carlini-Wagner $l_2$-attack~(C\&W, $l_2$-norm)~\cite{carlini2016towards}; CornerSearch $l_0$-attack~(CS, $l_0$-norm)~\cite{croce2019sparse}; Decoupled Direction and Norm $l_2$-attack~(DDN, $l_2$-norm)~\cite{rony2019decoupling}; DeepFool~(DF, $l_{\infty}$-, and $l_2$-norms)~\cite{dezfooli2015deepfool}; Distributionally Adversarial Attack~(DAA, $l_{\infty}$-norm)~\cite{zheng2018distributionally}; Elastic-net attack~(EAD, $l_1$-norm)~\cite{chen2018ead}; Fast Adaptive Boundary Attack~(FAB, $l_{\infty}$-, $l_2$-, $l_1$-norms)~\cite{croce2019minimally}; Jacobian-based Saliency Map attack~(JSMA, $l_0$-norm)~\cite{papernot2016limitations}; One Pixel attack~(Pixel, $l_0$-norm)~\cite{su2019onepixel}; Projected Gradient Descent~(PGD, $l_{\infty}$-, $l_2$-, $l_1$-, $l_0$-norms)~\cite{kurakin2016adversarialexamples, madry2017towards, tramer2019adversarial, croce2019sparse}; Sparsefool~(SF, $l_1$- and $l_0$-norms)~\cite{modas2019sparsefool}. We use B\&B, C\&W, DDN, and EAD attacks from Foolbox~\cite{rauber2017foolbox}; Pixel and JSMA attacks from ART~\cite{nicolae2018art}; PGD $l_{\infty}$-, $l_2$-, and $l_1$-norm attacks as in Cleverhans~\cite{papernot2018cleverhans}; CS, DF, FAB, and SF attacks with the code from the original papers, while we reimplemented DAA and PGD $l_0$-norm attacks. We conduct all our experiments using Tensorflow~\cite{ttdt2016tensorflow}. The code for the experiments to reproduce all our results is available at~\url{https://github.com/aam-at/cpgd}. For a fair comparison, we perform a hyperparameter search for each attack, model and dataset. We report the results for the best configuration of parameters. For all attacks with multiple restarts, we find optimal parameters using 1 random restart. The parameters optimal for the attack with 1 random restart are used for the attack's experiments with multiple random restarts. Next, we present details about the parameters of all attacks. \textbf{Attack parameters:} \begin{itemize} \item B\&B~\cite{brendel2019accurate} with 1000 iterations on MNIST and {CIFAR-10} and 100\footnote{\label{first}We reduce the number of iterations on R-ImageNet due to the attack's high computational cost.} on R-ImageNet; initial learning rate selected from $\{1.0, 0.1, 0.01\}$; learning rate decay selected from every $\{20, 100\}$ steps. \item C\&W~\cite{carlini2016towards} with 9 binary search steps; 10000 iterations on {MNIST} and {CIFAR-10}, and 1000\cref{first} on R-ImageNet; learning rate 0.01; initial const 0.01, and no early stopping. \item CS~\cite{croce2019sparse} with 1000 iterations; top-100 candidates for sampling; 784 and 1024 maximum sparsity on {MNIST} and {CIFAR-10}. We are unable to run CS on R-ImageNet due to the attack's high memory usage. \item DDN~\cite{rony2019decoupling} with 10000 iterations on MNIST, and 1000 on CIFAR-10 and R-ImageNet; initial epsilon selected from $\{1.0, 0.1\}$; gamma selected from $\{0.1, 0.05, 0.01\}$. \item DF~\cite{dezfooli2015deepfool} with 100 iterations and 0.02 overshoot. \item DAA~\cite{zheng2018distributionally} with Lagrangian Blob method; 500 iterations; epsilon step selected from $\{\epsilon, \sfrac{\epsilon}{2}, \sfrac{\epsilon}{5}, \sfrac{\epsilon}{10}, \sfrac{\epsilon}{25}, \sfrac{\epsilon}{50}, \sfrac{\epsilon}{100} \}$ for every epsilon $\epsilon$; surrogate loss selected from cross-entropy and hinge losses. \item EAD~\cite{chen2018ead} with 9 binary search steps; 10000 iterations on {MNIST} and {CIFAR-10}, and 1000\cref{first} on R-ImageNet; learning rate 0.01; initial const 0.01; beta 0.05; $l_1$ decision rule, and no early stopping. \item FAB~\cite{croce2019minimally} with 100 iterations. The remaining parameters are set to the values recommended in~\cite{croce2019minimally}. \item JSMA~\cite{papernot2016limitations} with gamma set to 1.0 and theta selected from $\{\pm 0.1, \pm 1.0\}$. JSMA requires selecting the target. We attack all targets on {MNIST} and {CIFAR-10}. On R-ImageNet, we attack only the second-highest class due to the attack's high computational cost. \item Pixel~\cite{su2019onepixel} with differential evolution strategy; 400 population size, and 100 iterations. We are unable to provide the results for Pixel attack on R-ImageNet due to its high computational cost. \item PGD~\cite{kurakin2016adversarialexamples,madry2017towards, croce2019sparse} with 500 iterations; epsilon step selected from $\{\epsilon, \sfrac{\epsilon}{2}, \sfrac{\epsilon}{5}, \sfrac{\epsilon}{10}, \sfrac{\epsilon}{25}, \sfrac{\epsilon}{50}, \sfrac{\epsilon}{100} \}$ for every epsilon $\epsilon$; surrogate loss selected from cross-entropy and hinge losses; optimal sparsity levels selected from $\{10\%, 5\%, 1\%\}$ (PGD-$l_{1}$ only). \item SF~\cite{modas2019sparsefool} with 20 iterations; epsilon 0.02; lambda incremented from 1 to 5, so the attack always succeeds. \end{itemize} \textbf{Parameters for our attack}: we set the number of iterations to 500, so the computational cost of our attack is similar to PGD attack with 500 iterations. Yet, the overall complexity of our attack is lower than PGD since PGD attack needs to be restarted for each threshold. For the primal variable $\mathbf{r}$, we use Adam~\cite{kingma2014adam} and Proximal Adam~\cite{melchior2019proximal} in PDGD and PDPGD attacks, respectively. For the dual variable $\lambda$, we perform gradient ascent in the log domain to guarantee that it remains positive. We apply an exponential moving average to smooth the value of the dual variable during optimisation. We select the learning rate for primal variables from $\{1.0, 0.1, 0.01\}$ using 1 random restart. The optimal learning rate for the attack with 1 random restart is used in the experiments with 10 and 100 random restarts. Learning rate and initial value of the dual variable is set to $0.1$ in all experiments. We exponentially and linearly decay the learning rate for the primal and dual variables to $0.01$ and $0.1$ of its initial value. We sample the initial perturbation from a uniform distribution $\mathcal{U} = [-\epsilon, \epsilon]$ with $\epsilon$ set to 0.5 on MNIST, 0.25 on {CIFAR-10}, and 0.1 on {R-ImageNet} datasets. We finetune the perturbation found after $N$-restarts for an additional 500 iterations. \textbf{Evaluation metrics}: We define the \textit{robust accuracy} of the model at a threshold $\epsilon$ as the classification accuracy of the model if the adversary is allowed to perturb the input with the perturbation of $l_p$-norm smaller than the threshold $\epsilon$ in order to change the model prediction. Given a perturbation budget $\epsilon$, an adversarial attack aims to maximise the reduction of the model's accuracy. We fix five thresholds per model and per dataset and calculate the robust accuracy of each attack at five selected thresholds. We compare the attacks using the following statistics for each dataset: i) \textbf{avg. rob. accuracy}: the mean of the robust accuracies achieved by the attack over all models and thresholds (lower is better); ii) \textbf{\# best}: how many times the attack achieves the lowest robust accuracy (it is the most effective); iii) \textbf{avg. difference to best}: for each model/threshold we compute the difference between the robust accuracy of the attack and the best one across all the attacks, then we average over all models/thresholds; iv) \textbf{max difference to best}: as "avg. difference to best", but with the maximum difference instead of the average one. In addition, we compare the average norm of the perturbations if the adversary is allowed to perturb the input without any perturbation bound (perturb only correctly classified inputs). Unbounded adversarial attack aims to minimise the perturbation budget while also achieving a high attack success rate. Please note that the comparison using the average norm of the adversarial perturbation is only available for the attacks that minimise the perturbation norm and excludes PGD and DAA attacks. We compare the attack methods based on their computational complexity in~\Cref{sec:runtime-comparison}. We test the effectiveness of the attacks on MNIST, {CIFAR-10}, and Restricted ImageNet datasets in~\Cref{sec:main-results}. We summarise our main results in~\Cref{tab:all-perf,tab:all-average}. We provide the complete results for all our experiments in supplementary materials, including detailed comparison of the proposed attack with PGD and FAB. \subsection{Runtime Comparison}\label{sec:runtime-comparison} It is difficult to compare the speed of various attack methods due to the differences in the per iteration runtime complexity, the number of iterations required for the attack to converge, and the attacks' implementation details. We perform a two-fold comparison of various attack methods based on the theoretical per iteration runtime complexity and the attack's actual running time on the equivalent hardware. \subsubsection{Runtime Complexity} We measure the per iteration runtime complexity as the number of forward and backward passes per attack's iteration. Yet, counting only the number of the forward and backward passes is insufficient as attacks at each iteration may perform additional non-trivial operations. For example, B\&B solves a second-order cone program at each iteration, significantly increasing the attack's running time. Our attack requires computing $l_p$-norm proximity operator at an additional cost of $O(d \log d)$ for $l_{\infty}$-norm, $O(d)$ for $l_1$- and $l_0$-norms proximity operators, where $d$ is the input's dimensionality. We summarise the results of the comparison in~\Cref{tab:runtime-complexity}. Because the number of the model's parameters significantly larger than the input's dimensionality, the cost of computing proximity operator is negligible. So, the overall complexity of our attack is similar to PGD attack. \begin{table}[!t] \captionsetup[table]{position=t} \renewcommand*{\arraystretch}{1.2} \setlength\tabcolsep{3.8pt} \centering \caption{Runtime complexity comparison of adversarial attacks.~\label{tab:runtime-complexity}} \vspace{-0.2cm} \begin{tabular}{L{0.9cm}|c|c|L{5.5cm}} Attack & \# FW & \# BP & Extra cost \\ \hline B\&B & $1$ & $1$ & Solve SOCP \\ CS & $1$ & $-$ & $-$ \\ C\&W & $1$ & $1$ & $-$ \\ DAA & $1$ & $1$ & Compute pairwise distance matrix $O(d^2)$ \\ DDN & $1$ & $1$ & $l_2$-ball projection $O(d)$ \\ DF & $1$ & $k$ & $l_{p}$-ball projection $O(d)$ \\ EAD & $1$ & $1$ & $l_1$-norm proximity operator $O(d)$ \\ FAB & $2$ & $k$ & $l_p$-ball box projection $O(d \log d)$ \\ JSMA & $1$ & $k$ & $-$ \\ Pixel & $1$ & $-$ & $-$ \\ PGD & $1$ & $1$ & $l_p$-ball projection: $O(d)$ for $l_{\infty}$- and $l_2$-norms; $O(d \log d)$ for $l_1$- and $l_0$-norms \\ SF & $1$ & $-$ & Compute DF and $l_1$-norm projection onto hyperplane \\ \hline Our & 1 & 1 & $l_p$-norm proximity operator: $O(d \log d)$ for $l_{\infty}$-norm, $O(d)$ for $l_1$- and $l_0$-norms \end{tabular} \end{table} \subsubsection{Running Time} We report the running time in seconds on Nvidia Titan V averaged across all models for 1000 points on MNIST, {CIFAR-10} and Restricted ImageNet. Unless otherwise stated, the running time includes all the restarts. For PGD, DAA and Pixel attacks, this is the time for evaluating robust accuracy at five thresholds. Note that when measuring the running time for these attacks, we exploit the fact that the inputs non-robust at the threshold $\epsilon$ are also non-robust at thresholds larger than $\epsilon$. For the other attacks, a single attack is sufficient to compute the robust accuracy at all thresholds. \textbf{MNIST}: B\&B 328s; CS 2611s; C\&W 3758s; DAA-100 4680s; DDN 254s; DF 12s; EAD 4812s; FAB-100 2974s; JSMA 275s; Pixel 41126s; PGD-100 2135s for $l_{\infty}/l_2$ and 2583 for $l_1/l_0$; SF 1301s; Our-10/Our-100 217s/1805s for $l_{\infty}$, 122s/965s for $l_2$ and 176s/1484s for $l_1/l_0$. \textbf{\mbox{CIFAR-10}}: B\&B 1327s; CS 23603s; C\&W 15230s; DAA-100 29030s; DDN 165s; DF 13s; EAD 16222s; FAB-100 20590s; JSMA 1333s; Pixel 22928s; PGD-100 12267s for $l_{\infty}/l_2$ and 12361s for $l_1/l_0$; SF 790s; Our-10/Our-100 1358s/12060s for $l_{\infty}$, 1157s/10054s for $l_2$ and 1316s/11620s for $l_1/l_0$. \textbf{Restricted ImageNet}: B\&B 10942s; C\&W 36451s; DAA-10 87194s; DDN 3703s; DF 173s; EAD 46762s; FAB-10 33757s; JSMA 19551s; PGD-10 32671s for $l_{\infty}/l_2$ and 53858s for $l_1/l_0$; SF 16367s; Our-1/Our-10 6818s/38719s for $l_{\infty}$, 5127s/29335s for $l_2$ and 5644s/30586s for $l_1/l_0$. The running time depends upon the number of attack's iterations. DF is the fastest attack requiring few iterations to succeed, but it is also the least accurate attack as its goal is to find adversarial perturbation as fast as possible without minimising its norm. The running time of our attack is comparable to existing attacks. PGD attack is fast and accurate with the complexity similar to our attack, but it needs to be restarted at each threshold, so the total running time of our attack is lower than PGD. FAB converges faster and requires relatively small number of iterations (100 in our experiments), but the complexity of each iteration is higher than our attack as it requires to compute $k$ gradients at each step. We also report the running time of our lower complexity attack with a reduced number of restarts, which is the fastest when excluding less accurate DF and SF attacks. As we show in the section, our lower complexity attack often outperforms state-of-the-art attacks. \subsection{Main Results}\label{sec:main-results} We compare the attacks on the first 1000 images of {MNIST} and {CIFAR-10} test sets and 1000 images of {Restricted ImageNet} validation set. For each dataset, we evaluate robust accuracy at five thresholds for \textit{plain}, $l_{\infty}$~($l_{\infty}$-AT) and $l_2$~($l_2$-AT) adversarially trained models. We use the same five thresholds that were selected in~\cite{croce2019minimally}. We show adversarial examples generated by our attack for 10 randomly selected MNIST test images in~\Cref{fig:mnist_adversarial_examples}. We report aggregated results for all datasets, models, norms and thresholds in~\Cref{tab:all-perf}, while we provide complete results at each threshold in supplementary materials. Note that we are unable to run CornerSearch and Pixel attacks on R-ImageNet due to high memory usage and high computational cost of the attacks. \begin{figure}[!b] \captionsetup[table]{position=b} \captionsetup[subfloat]{captionskip=1pt} \caption{$l_{\infty}$-, $l_2$-, $l_1$-, and $l_0$-norm adversarial examples for a naturally trained, $l_{\infty}$-, and $l_2$- adversarially trained models on MNIST.~\label{fig:mnist_adversarial_examples}} \setlength\tabcolsep{0pt} \subfloat[][Original images~\label{tab:original_examples_mnist}]{ \begin{tabular}{C{6mm} @{\hspace{3pt}} l} \\[-0.7cm] & \raisebox{-.5\height}{\includegraphics[width=0.90\columnwidth]{orig.png}} \\ \end{tabular} }\\[-2.4ex] \subfloat[][Adversarial examples for naturally trained model~\label{tab:natural_examples_mnist}]{ \begin{tabular}{C{6mm} @{\hspace{3pt}} l} \centered{$l_{\infty}$} & \raisebox{-.5\height}{\includegraphics[width=0.90\columnwidth]{plain_li.png}} \\ \centered{$l_{2}$} & \raisebox{-.5\height}{\includegraphics[width=0.90\columnwidth]{plain_l2.png}} \\ \centered{$l_{1}$} & \raisebox{-.5\height}{\includegraphics[width=0.90\columnwidth]{plain_l1.png}} \\ \centered{$l_{0}$} & \raisebox{-.5\height}{\includegraphics[width=0.90\columnwidth]{plain_l0.png}} \\ \end{tabular} \hfill }\\[-2.4ex] \subfloat[][Adversarial examples for $l_{\infty}$-AT model~\label{tab:linf_examples_mnist}]{ \begin{tabular}{C{6mm} @{\hspace{3pt}} l} \centered{$l_{\infty}$} & \raisebox{-.5\height}{\includegraphics[width=0.90\columnwidth]{linf_li.png}} \\ \centered{$l_{2}$} & \raisebox{-.5\height}{\includegraphics[width=0.90\columnwidth]{linf_l2.png}} \\ \centered{$l_{1}$} & \raisebox{-.5\height}{\includegraphics[width=0.90\columnwidth]{linf_l1.png}} \\ \centered{$l_{0}$} & \raisebox{-.5\height}{\includegraphics[width=0.90\columnwidth]{linf_l0.png}} \\ \end{tabular} }\\[-2.4ex] \subfloat[][Adversarial examples for $l_2$-AT model~\label{tab:l2_examples_mnist}]{ \begin{tabular}{C{6mm} @{\hspace{3pt}} l} \centered{$l_{\infty}$} & \raisebox{-.5\height}{\includegraphics[width=0.90\columnwidth]{l2_li.png}} \\ \centered{$l_{2}$} & \raisebox{-.5\height}{\includegraphics[width=0.90\columnwidth]{l2_l2.png}} \\ \centered{$l_{1}$} & \raisebox{-.5\height}{\includegraphics[width=0.90\columnwidth]{l2_l1.png}} \\ \centered{$l_{0}$} & \raisebox{-.5\height}{\includegraphics[width=0.90\columnwidth]{l2_l0.png}} \\ \end{tabular} } \end{figure} \begin{table*}[!t] \centering \captionsetup[table]{position=t} \captionsetup[subfloat]{captionskip=1pt,justification=centering} \renewcommand*{\arraystretch}{1} \caption{Performance summary (aggregated) of all attacks on MNIST, CIFAR-10 and Restricted Imagenet in~\Cref{tab:mnist-perf}, \Cref{tab:cifar10-perf} and \Cref{tab:imagenet-perf}, respectively. *Note that for Our-10 the "\# best" is computed excluding the results of Our-100.~\label{tab:all-perf}} \vspace{-0.5cm} \subfloat[][MNIST results~\label{tab:mnist-perf}]{ \begin{tabular}{L{25mm}*{8}{|C{14mm} }} \cellcolor{gray!20} \textbf{$l_\infty$-norm} & & DeepFool & B\&B & DAA-100 & PGD-100 & FAB-100 & Our-10 & Our-100 \\ \hline avg. rob. acc. & & 78.46 & 57.51 & 55.93 & 56.24 & 59.47 & 56.00 & \textbf{55.15} \\ \# best & & 0 & 2 & 5 & 3 & 1 & 8$^*$ & \textbf{14} \\ avg. diff. to best & & 23.33 & 2.38 & 0.80 & 1.10 & 4.34 & 0.87 & \textbf{0.02} \\ max diff. to best & & 81.6 & 7.6 & 4.0 & 4.2 & 24.6 & 3.9 & \textbf{0.3} \\ \hline \multicolumn{9}{c}{}\\[-0.05cm] \cellcolor{gray!20}\textbf{$l_2$-norm} & DeepFool & C\&W & DDN & B\&B & PGD-100 & FAB-100 & Our-10 & Our-100 \\ \hline avg. rob. acc. & 67.4 & 48.13 & 42.81 & 39.57 & 45.65 & 34.66 & \textbf{33.91} & \textbf{33.05} \\ \# best & 0 & 1 & 2 & 2 & 1 & 4 & 12$^*$ & \textbf{14} \\ avg. diff. to best & 34.35 & 15.09 & 9.76 & 6.52 & 12.6 & 1.61 & 0.87 & \textbf{0.01} \\ max diff. to best & 91.9 & 63.9 & 53.3 & 30.9 & 66.3 & 5.0 & 4.1 & \textbf{0.1} \\ \hline \multicolumn{9}{c}{}\\[-0.05cm] \cellcolor{gray!20}\textbf{$l_1$-norm} & & SparseFool & EAD & B\&B & PGD-100 & FAB-100 & Our-10 & Our-100 \\ \hline avg. rob. acc. & & 74.33 & 45.36 & 48.85 & 58.59 & 37.75 & \textbf{34.19} & \textbf{32.15} \\ \# best & & 0 & 1 & 0 & 0 & 0 & 12$^*$ & \textbf{15} \\ avg. diff. to best & & 42.18 & 13.21 & 16.69 & 26.44 & 5.6 & 2.03 & \textbf{0.0} \\ max diff. to best & & 91.9 & 50.8 & 52.6 & 80.3 & 19.0 & 8.2 & \textbf{0.0} \\ \hline \multicolumn{9}{c}{}\\[-0.05cm] \cellcolor{gray!20}\textbf{$l_0$-norm} & SparseFool & JSMA & Pixel & B\&B & PGD-100 & CornerSearch & Our-10 & Our-100 \\ \hline avg. rob. acc. & 80.43 & 84.98 & 77.03 & 58.37 & 56.09 & 49.99 & \textbf{43.15} & \textbf{40.57} \\ \# best & 0 & 0 & 0 & 0 & 0 & 2 & 6$^*$ & \textbf{14} \\ avg. diff. to best & 38.83 & 44.55 & 36.61 & 17.94 & 15.66 & 9.57 & 2.73 & \textbf{0.15} \\ max diff. to best & 92.5 & 96.1 & 94.3 & 57.0 & 65.9 & 36.0 & 11.9 & \textbf{2.2} \\ \hline \end{tabular} }\\ \vspace{-0.2cm} \subfloat[][CIFAR-10 results~\label{tab:cifar10-perf}]{ \raggedright \begin{tabular}{L{25mm}*{8}{|C{14mm} }} \cellcolor{gray!20} \textbf{$l_\infty$-norm}& & DeepFool & B\&B & DAA-100 & PGD-100 & FAB-100 & Our-10 & Our-100 \\ \hline avg. rob. acc. & & 40.63 & 32.75 & 31.72 & 31.65 & 31.61 & \textbf{31.24} & \textbf{30.83} \\ \# best & & 0 & 0 & 0 & 2 & 0 & 13$^*$ & \textbf{14} \\ avg. diff. to best & & 9.81 & 1.93 & 0.89 & 0.83 & 0.78 & 0.41 & \textbf{0.01} \\ max diff. to best & & 17.4 & 3.0 & 1.7 & 1.7 & 1.4 & 1.1 & \textbf{0.1} \\ \hline \multicolumn{9}{c}{}\\[-0.05cm] \cellcolor{gray!20}\textbf{$l_2$-norm}& DeepFool & C\&W & DDN & B\&B & PGD-100 & FAB-100 & Our-10 & Our-100 \\ \hline avg. rob. acc. & 44.81 & 37.49 & 37.77 & 38.49 & 36.90 & 36.63 & \textbf{36.09} & \textbf{35.89} \\ \# best & 0 & 0 & 1 & 0 & 2 & 1 & 14$^*$ & \textbf{14} \\ avg. diff. to best & 8.92 & 1.60 & 1.89 & 2.60 & 1.01 & 0.75 & 0.20 & \textbf{0.01} \\ max diff. to best & 14.8 & 2.8 & 4.7 & 4.5 & 2.2 & 1.4 & 0.6 & \textbf{0.1} \\ \hline \multicolumn{9}{c}{}\\[-0.05cm] \cellcolor{gray!20}\textbf{$l_1$-norm} & & SparseFool & EAD & B\&B & PGD-100 & FAB-100 & Our-10 & Our-100 \\ \hline avg. rob. acc. & & 40.53 & 20.76 & 22.79 & 26.46 & 21.49 & \textbf{19.59} & \textbf{18.36} \\ \# best & & 0 & 0 & 0 & 0 & 0 & 12$^*$ & \textbf{15} \\ avg. diff. to best & & 22.17 & 2.40 & 4.43 & 8.10 & 3.13 & 1.23 & \textbf{0.00} \\ max diff. to best & & 35.9 & 4.9 & 9.1 & 13.8 & 6.5 & 2.5 & \textbf{0.0} \\ \hline \multicolumn{9}{c}{}\\[-0.05cm] \cellcolor{gray!20}\textbf{$l_0$-norm} & SparseFool & JSMA & Pixel & B\&B & PGD-100 & CornerSearch & Our-10 & Our-100 \\ \hline avg. rob. acc. & 48.45 & 69.15 & 51.66 & 47.86 & 35.23 & 30.51 & \textbf{27.33} & \textbf{25.00} \\ \# best & 0 & 0 & 0 & 0 & 0 & 4 & 10$^*$ & \textbf{11} \\ avg. diff. to best & 25.91 & 46.61 & 29.12 & 25.32 & 12.69 & 7.97 & 4.79 & \textbf{2.46} \\ max diff. to best & 45.7 & 68.6 & 53.3 & 39.7 & 16.4 & 20.6 & 13.0 & \textbf{11.5} \\ \hline \end{tabular} }\\ \vspace{-0.2cm} \subfloat[][Restricted ImageNet results~\label{tab:imagenet-perf}]{ \raggedleft \begin{tabular}{L{25mm}*{8}{|C{14mm} }} \cellcolor{gray!20} \textbf{$l_\infty$-norm}& & DeepFool & B\&B & DAA-10 & PGD-10 & FAB-10 & Our-1 & Our-10 \\ \hline avg. rob. acc. & & 36.99 & 29.26 & 27.99 & \textbf{27.39} & 28.50 & 28.05 & 27.54 \\ \# best & & 0 & 0 & 2 & 7 & 0 & 5 & \textbf{9} \\ avg. diff. to best & & 9.72 & 1.99 & 0.72 & \textbf{0.11} & 1.23 & 0.78 & 0.27 \\ max diff. to best & & 18.5 & 4.5 & 1.8 & \textbf{0.5} & 2.6 & 2.9 & 2.1 \\ \hline \multicolumn{8}{c}{}\\[-0.05cm] \cellcolor{gray!20}\textbf{$l_2$-norm} & DeepFool & C\&W & DDN & B\&B & PGD-10 & FAB-10 & Our-1 & Our-10 \\ \hline avg. rob. acc. & 45.80 & 42.25 & 32.87 & 36.17 & 32.70 & 34.57 & \textbf{32.09} & \textbf{31.21} \\ \# best & 0 & 0 & 0 & 0 & 1 & 0 & 10 & \textbf{14} \\ avg. diff. to best & 14.67 & 11.12 & 1.74 & 5.03 & 1.57 & 3.44 & 0.95 & \textbf{0.08} \\ max diff. to best & 28.4 & 43.9 & 5.1 & 10.0 & 5.0 & 8.0 & 2.9 & \textbf{1.2} \\ \hline \multicolumn{8}{c}{}\\[-0.05cm] \cellcolor{gray!20}\textbf{$l_1$-norm} & & SparseFool & EAD & B\&B & PGD-10 & FAB-10 & Our-1 & Our-10 \\ \hline avg. rob. acc. & & 67.51 & 36.05 & 41.46 & 58.89 & 41.79 & 38.19 & \textbf{35.21} \\ \# best & & 0 & 6 & 0 & 0 & 0 & 2 & \textbf{10} \\ avg. diff. to best & & 32.83 & 1.37 & 6.78 & 24.21 & 7.11 & 3.51 & \textbf{0.53} \\ max diff. to best & & 61.6 & 6.4 & 10.3 & 54.5 & 16.6 & 8.2 & \textbf{3.1} \\ \hline \multicolumn{8}{c}{}\\[-0.05cm] \cellcolor{gray!20}\textbf{$l_0$-norm} & SparseFool & JSMA & Pixel & B\&B & PGD-10 & CornerSearch & Our-1 & Our-10 \\ \hline avg. rob. acc. & 49.18 & 79.82 & - & 46.28 & 46.56 & - & \textbf{33.40} & \textbf{28.75} \\ \# best & 0 & 0 & - & 0 & 0 & - & 14 & \textbf{15} \\ avg. diff. to best & 20.43 & 51.07 & - & 17.53 & 17.81 & - & 4.65 & \textbf{0.00} \\ max diff. to best & 40.1 & 74.2 & - & 25.9 & 36.0 & - & 9.0 & \textbf{0.0} \\ \hline \end{tabular} \hspace{1.74cm} } \end{table*} Our attack is the strongest as it most substantially reduces the robust accuracy compared with other attacks~(see~\cref{tab:all-perf}). In particular, it outperforms other attacks in 11 out of 12 cases in terms of the average robust accuracy. The second best attack varies depending upon the dataset and norm, which shows that our attack is accurate and general. PGD $l_{\infty}$-norm attack on Restricted ImageNet is the only attack to outperform our method. The improvement over the state-of-the-art attacks is most significant for our $l_1$- and $l_0$-norm attacks. For example, our $l_1$- and $l_0$-norm attack reduces the average robust accuracy by 17.4\% and 23.2\% on MNIST against FAB-100 and CornerSearch attacks, respectively. Our fast lower complexity attack with 10 random restarts on MNIST and {CIFAR-10} and 1 random restart on Restricted ImageNet outperforms other attacks in 9 out of 12 cases. \begin{table}[!t] \captionsetup[table]{position=t} \captionsetup[subfloat]{captionskip=1pt} \renewcommand*{\arraystretch}{1.05} \caption{Average norm of the perturbation found by the attacks (when successful, excluding the already misclassified points) for every model on MNIST, CIFAR-10 and Restricted ImageNet.~\label{tab:all-average}} \addtocounter{table}{-1} \setlength\tabcolsep{3.8pt} \centering \subfloat[][Average norm of the perturbation on MNIST]{ \begin{tabular}{@{\hspace{2pt}} c @{\hspace{2pt}} | @{\hspace{4pt}} *{7}{r}} \\[-0.5cm] \cellcolor{gray!20}$l_{\infty}\times 10^{-1}$ & & & DF & B\&B & FAB-100 & Our-10 & Our-100 \\ \hline plain & & & 0.82 & 0.65 & 0.66 & \textbf{0.63} & \textbf{0.63} \\ $l_\infty$-at & & & 5.28 & 3.2 & 3.27 & \textbf{3.18} & \textbf{3.16} \\ $l_2$-at & & & 2.59 & 1.72 & 1.7 & \textbf{1.67} & \textbf{1.66} \\ \hline \multicolumn{7}{c}{}\\[-1.2ex] \cellcolor{gray!20}$l_2$ & DF & C\&W & DDN & B\&B & FAB-100 & Our-10 & Our-100 \\ \hline plain & 1.13 & 1.01 & 1.0 & 1.01 & 0.99 & \textbf{0.98} & \textbf{0.98} \\ $l_\infty$-at & 5.03 & 2.08 & 1.71 & 1.4 & 1.12 & \textbf{1.11} & \textbf{1.06} \\ $l_2$-at & 3.08 & 2.34 & 2.29 & 2.35 & 2.25 & \textbf{2.20} & \textbf{2.18} \\ \hline \multicolumn{7}{c}{}\\[-1.2ex] \cellcolor{gray!20}$l_1$ & \multicolumn{2}{r}{Sparsefool} & EAD & B\&B & FAB-100 & Our-10 & Our-100 \\ \hline plain & \multicolumn{2}{r}{8.71} & 6.21 & 6.59 & 6.04 & \textbf{6.03} & \textbf{5.87} \\ $l_{\infty}$-at & \multicolumn{2}{r}{207.70} & 6.73 & 6.32 & 3.48 & \textbf{2.59} & \textbf{2.32} \\ $l_2$-at & \multicolumn{2}{r}{16.52} & 11.96 & 13.97 & 12.15 & \textbf{11.40} & \textbf{10.93} \\ \hline \multicolumn{7}{c}{}\\[-1.2ex] \cellcolor{gray!20}$l_0$ & \multicolumn{2}{r}{Sparsefool} & JSMA & B\&B & CS & Our-10 & Our-100 \\ \hline plain & \multicolumn{2}{r}{12.45} & 13.76 & 7.66 & 8.74 & \textbf{7.01} & \textbf{6.76} \\ $l_{\infty}$-at & \multicolumn{2}{r}{249.06} & 59.30 & 11.29 & 3.85 & 4.27 & \textbf{3.82} \\ $l_2$-at & \multicolumn{2}{r}{21.35} & 26.61 & 15.14 & 17.28 & \textbf{12.28} & \textbf{11.72} \\ \hline \end{tabular} }\\ \subfloat[][Average norm of the perturbation on CIFAR-10]{ \begin{tabular}{@{\hspace{2pt}} c @{\hspace{2pt}} | @{\hspace{4pt}} *{7}{r}} \\[-0.55cm] \cellcolor{gray!20}$l_{\infty}\times 10^{-2}$ & & & DF & B\&B & FAB-100 & Our-10 & Our-100 \\ \hline plain & & & 0.77 & 0.57 & 0.56 & \textbf{0.55} & \textbf{0.54} \\ $l_\infty$-at & & & 3.13 & 2.5 & 2.37 & \textbf{2.34} & \textbf{2.32} \\ $l_2$-at & & & 2.59 & 1.98 & 1.94 & \textbf{1.90} & \textbf{1.88} \\ \hline \multicolumn{7}{c}{}\\[-1.2ex] \cellcolor{gray!20}$l_2 \times 10^{-1}$ & DF & C\&W & DDN & B\&B & FAB-100 & Our-10 & Our-100 \\ \hline plain & 2.72 & 2.13 & 2.11 & 2.15 & 2.06 & \textbf{2.04} & \textbf{2.02} \\ $l_\infty$-at & 9.42 & 7.28 & 7.51 & 7.62 & 7.15 & \textbf{6.99} & \textbf{6.95} \\ $l_2$-at & 9.06 & 7.12 & 7.38 & 7.22 & 6.98 & \textbf{6.85} & \textbf{6.82} \\ \hline \multicolumn{7}{c}{}\\[-1.2ex] \cellcolor{gray!20}$l_1$ & \multicolumn{2}{r}{Sparsefool} & EAD & B\&B & FAB-100 & Our-10 & Our-100 \\ \hline plain & \multicolumn{2}{r}{6.99} & 2.90 & 2.83 & 2.86 & \textbf{2.67} & \textbf{2.58} \\ $l_{\infty}$-at & \multicolumn{2}{r}{10.74} & 5.63 & 6.53 & 6.07 & \textbf{5.38} & \textbf{5.09} \\ $l_2$-at & \multicolumn{2}{r}{13.77} & 7.79 & 8.78 & 8.02 & \textbf{7.50} & \textbf{7.16} \\ \hline \multicolumn{7}{c}{}\\[-1.2ex] \cellcolor{gray!20}$l_0$ & \multicolumn{2}{r}{Sparsefool} & JSMA & B\&B & CS & Our-10 & Our-100 \\ \hline plain & \multicolumn{2}{r}{17.73} & 21.29 & 6.80 & 3.98 & \textbf{3.16} & \textbf{2.86} \\ $l_{\infty}$-at & \multicolumn{2}{r}{9.09} & 25.03 & 9.60 & 5.76 & \textbf{4.38} & \textbf{3.99} \\ $l_2$-at & \multicolumn{2}{r}{27.46} & 26.13 & 9.78 & 6.50 & \textbf{5.07} & \textbf{4.60} \\ \hline \end{tabular} }\\ \subfloat[][Average norm of the perturbation on Restricted ImageNet]{ \begin{tabular}{@{\hspace{2pt}} c @{\hspace{2pt}} | @{\hspace{4pt}} *{7}{r}} \\[-0.55cm] \cellcolor{gray!20}$l_{\infty}\times 10^{-2}$ & & & DF & B\&B & FAB-10 & Our-1 & Our-10 \\ \hline plain & & & 0.25 & 0.19 & 0.19 & \textbf{0.19} & \textbf{0.18} \\ $l_\infty$-at & & & 2.16 & 1.75 & 1.71 & \textbf{1.68} & \textbf{1.67} \\ $l_2$-at & & & 1.87 & 1.58 & 1.54 & \textbf{1.53} & \textbf{1.51} \\ \hline \multicolumn{8}{c}{}\\[-1.2ex] \cellcolor{gray!20}$l_2$ & DF & C\&W & DDN & B\&B & FAB-10 & Our-1 & Our-10 \\ \hline plain & 0.54 & 0.75 & 0.40 & 0.42 & 0.41 & \textbf{0.39} & \textbf{0.38} \\ $l_\infty$-at & 3.43 & 2.34 & 2.28 & 2.41 & 2.35 & \textbf{2.17} & \textbf{2.10} \\ $l_2$-at & 4.53 & 3.65 & 3.56 & 3.78 & 3.67 & \textbf{3.56} & \textbf{3.54} \\ \hline \multicolumn{8}{c}{}\\[-1.2ex] \cellcolor{gray!20}$l_1$ & \multicolumn{2}{r}{Sparsefool} & EAD & B\&B & FAB-10 & Our-1 & Our-10 \\ \hline plain & \multicolumn{2}{r}{87.56} & 15.61 & 16.67 & 21.25 & 15.65 & \textbf{13.48} \\ $l_{\infty}$-at & \multicolumn{2}{r}{138.35} & \textbf{40.42} & 52.48 & 52.78 & 53.14 & 47.87 \\ $l_2$-at & \multicolumn{2}{r}{374.02} & 166.27 & 188.17 & 179.35 & 169.74 & \textbf{165.71} \\ \hline \multicolumn{8}{c}{}\\[-1.2ex] \cellcolor{gray!20}$l_0$ & \multicolumn{2}{r}{Sparsefool} & JSMA & B\&B & CS & Our-1 & Our-10 \\ \hline plain & \multicolumn{2}{r}{52.06} & 211.77 & 33.60 & - & \textbf{22.96} & \textbf{19.21} \\ $l_{\infty}$-at & \multicolumn{2}{r}{80.33} & 372.33 & 62.14 & - & \textbf{53.66} & \textbf{41.84} \\ $l_2$-at & \multicolumn{2}{r}{131.27} & 629.18 & 191.86 & - & \textbf{123.90} & \textbf{117.80} \\ \hline \end{tabular}\hspace{1.3cm} } \end{table} \addtocounter{table}{1} Robust accuracy measures the model's robustness at a specific threshold $\epsilon$. Robust norm gives a full picture of the model's robustness as a continuous function of the perturbation's size $\epsilon$. In~\Cref{tab:all-average}, we report the average $l_p$-norm of the adversarial perturbations found by the attacks~(when successful) for every dataset, model and norm. We exclude the points that the models already misclassify. All attacks, except DF attack on MNIST dataset against $l_{\infty}$-AT model, have a 100\% success rate, so we do not include the attack's success rate in the table results. Our attack finds the smallest norm adversarial perturbation in 35 out of 36 cases~(see~\cref{tab:all-average}). The improvements for $l_1$- and $l_0$-norm minimisation are particularly significant. For example, our $l_1$-norm attack reduces the average robust norm of $l_{\infty}$-AT model on MNIST by 50\% compared to the second-best attack FAB-100 (a reduction from 3.48 to 2.32). Our $l_0$-norm attack reduces the average robust norm of $l_2$-AT model on MNIST by 29.2\% compared to the second-best attack B\&B (reduction from 15.14 to 11.72). EAD $l_1$-attack against $l_{\infty}$-AT model on Restricted ImageNet is the only attack to outperform our method when comparing the average robust $l_1$-norm (an increase from 40.42 to 47.87). We also report the results of our attack with the reduced number of random restarts. Our lower complexity attack with 10 random restarts outperforms all other attacks in 23 out of 24 cases on MNIST and {CIFAR-10} datasets. Our-1 outperforms all other attacks in 9 out of 12 cases on R-ImageNet dataset. \textbf{To summarize, our main results are:} \begin{itemize} \item Our $l_{\infty}$-norm attack reduces the average robust norm~/~robust accuracy by $\nicefrac{1.4\%}{1.5\%}$ on MNIST, $\nicefrac{2.2\%}{2.5\%}$ on CIFAR-10 and $\nicefrac{2.2\%}{-0.5\%}$ on R-ImageNet compared to the second-best attack. {PGD-10} on R-ImageNet is the only attack to outperform our attack in terms of the average robust accuracy. \item Our $l_2$-norm attack reduces the average robust norm / robust accuracy by $\nicefrac{3.8\%}{4.9\%}$ on MNIST, $\nicefrac{2.5\%}{2.0\%}$ on {CIFAR-10} and $\nicefrac{4.2\%}{4.8\%}$ on R-ImageNet compared to the second-best attack. \item Our $l_1$-norm attack reduces the average robust norm~/ robust accuracy by $\nicefrac{21.7\%}{17.4\%}$ on MNIST, $\nicefrac{9.7\%}{13\%}$ on {CIFAR-10} and $\nicefrac{0.2\%}{2.4\%}$ on R-ImageNet compared to the second-best attack. EAD on R-ImageNet against $l_{\infty}$-AT is the only attack to outperform our attack in terms of the average robust norm. \item Our $l_0$-norm attack reduces the average robust norm / robust accuracy by $\nicefrac{14.5\%}{23.2\%}$ on {MNIST}, $\nicefrac{41.6\%}{22.0\%}$ on {CIFAR-10} and $\nicefrac{45.0\%}{61.0\%}$ on R-ImageNet compared to the second-best attack. \end{itemize} Overall, our attack is the best attack to reduce the robust accuracy and the robust norm compared to state-of-the-art attacks with a similar computational budget. Our attack is fast, accurate and general as it works for all $l_p$-norms in $p \in \{0, 1, 2, \infty\}$. It outperforms all algorithms, including even one that is specialised in individual norms. Our lower complexity attack with the reduced number of restarts is the second-best attack and requires a fraction of the running time / computational cost. \section{Conclusion} Fast and accurate estimation of the robust norm and robust accuracy of deep neural networks is crucial for comparing models. However, evaluating the DNNs robustness has proven to be challenging. The original non-convex constrained norm minimisation problem is difficult to solve. In this work, we introduce an adversarial attack that efficiently solves the original attack's problem. We interpret optimising the Lagrangian of the adversarial attack as playing a two-player game. The first player minimises the Lagrangian wrt the adversarial noise; the second player maximises the Lagrangian wrt the regularisation penalty, which penalises the first player for violating the misclassification constraint. We apply a primal-dual gradient descent algorithm to simultaneously update primal and dual variables to find the minimal optimal adversarial perturbation. For non-smooth $l_p$-norm minimisation, such as $l_{\infty}$-, $l_1$-, and $l_0$-norms, we introduce primal-dual proximal gradient descent attack. We also derive group $l_{0,G}$-norm proximal operator, which we use to minimise the number of perturbed pixels. Our method is fast, accurate and general. In the experiments on MNIST, CIFAR-10 and Restricted ImageNet, we show that our attack outperforms state-of-the-art $l_{\infty}$-, $l_2$-, $l_1$- and $l_0$-norm attacks in terms of robust norm and robust accuracy in 35 out 36 and 11 out of 12 cases, respectively. In future work, we plan to extend the proposed attack to multiple norm perturbations and combine our attack with adversarial training defence. \ifCLASSOPTIONcaptionsoff \newpage \fi
{'timestamp': '2021-06-04T02:08:04', 'yymm': '2106', 'arxiv_id': '2106.01538', 'language': 'en', 'url': 'https://arxiv.org/abs/2106.01538'}
arxiv
\section{Conclusion} \new{Dagger is an efficient and reconfigurable hardware acceleration platform for RPCs, specifically targeting interactive cloud microservices. In addition to showing the benefits of hardware offload for RPCs to reconfigurable FPGAs, we also demonstrate that using memory interconnects instead of PCIe as the NIC I/O interface offers significant benefits. Most importantly, our work shows that such close coupling of programmable networking devices with processors is already feasible today. Dagger achieves $1.3-3.8\times$ better per-core RPC throughput compared to previous DPDK- and RDMA-based solutions, it provides $\mu$-scale latency, and it can be easily ported to third-party applications, such as memcached and MICA, significantly improving their median and tail latencies. We also show the reconfigurability feature of our proposal by running an example of a multi-tier application and tuning both the software and hardware parts of the stack for each individual microservice to get high end-to-end performance. } \section{Dagger Design} \label{sec:dagger} \subsection{High-Level Architecture and Design Principles} We design Dagger with the unique network properties and requirements of microservices in mind, discussed in Section~\ref{sec:network_footprint}. Although Dagger is optimized for microservices, it is still beneficial for traditional interactive cloud applications, as we will show in Section~\ref{sec:evaluation}. Dagger's top-level architecture is shown in Figure~\ref{fig:top_level}. Dagger is based on three main design principles: i) \textit{full hardware offload}, ii) \textit{tight coupling}, and iii) \textit{reconfigurability}. \begin{figure}[h] \centering \vspace{-5pt} \begin{subfigure}{1\linewidth} \includegraphics[width=1\linewidth]{top_level.pdf} \label{fig:top_level_diagram} \end{subfigure}% \begin{subfigure}{1\linewidth} \includegraphics[width=1\linewidth]{rpc_unit.pdf} \label{fig:rpc_unit} \end{subfigure}% \vspace{-12pt} \caption{\new{Top-level architecture of Dagger (top) and zoom-in of the PRC unit (bottom) -- \normalfont{the bar on top shows approximate mapping of the Dagger stack onto the Thrift RPC~\cite{Thrift} stack. }}} \label{fig:top_level} \end{figure} First, Dagger offloads the entire RPC stack in hardware, to eliminate all interference between application logic and network processing in the host CPU. The remaining software components of Dagger running on the host CPU are lightweight, and are only responsible for the connection set-up and for exposing the RPC API to applications. The software stack implements the API with zero-copying and directly places incoming RPC requests and responses to dedicated buffers (queues, rings) accessible by the hardware which is synthesized on an FPGA (shown by the NIC module in Figure~\ref{fig:top_level}). The rest of the processing is handled by the NIC. The second design principle of Dagger is tightly coupling the hardware-accelerated network fabric with the host CPU. In contrast to existing high-performance and/or programmable NICs, which leverage PCIe-based interfaces, Dagger uses NUMA memory interconnects as the interface with the host processor to optimize the transfer of small fine-grained RPCs, by piggybacking on the hardware coherence protocol. The NUMA memory interconnect (Intel UPI in our current implementation) is encapsulated into the CCI-P protocol stack, as shown by the triangle in Figure~\ref{fig:top_level}. CCI-P~\cite{CCIP} is a protocol stack between the host CPU and the FPGA designed by Intel, which in addition to UPI, also wraps-up two PCIe links. Finally, the design of Dagger focuses on reconfigurability by leveraging an FPGA as the physical medium. Our current design is based on the Intel OPAE HDK that defines two regions of programmable logic: the blue and the green bitstreams. The former is fixed in the FGPA configuration and is not exposed to the FPGA users. This includes the implementation of system components, such as the CCI-P interface IP, Ethernet PHY, clock generation infrastructure, etc. The blue bitstream is managed by the cloud providers, and undergoes periodic updates. The green bitstream is used to implement the user logic and is fully programmable, with a pre-synthesized bitstreams. We implement the Dagger NIC in the green region, as shown in Figure~\ref{fig:top_level}. Our design is modular and configurable: different hardware parameters and components can be selected via SystemVerilog macros/parameters and synthesized. We call this \textit{hard configuration}, and use it only for coarse-grained control decisions. For example, Dagger supports multiple different CPU-NIC interfaces; the choice of the specific scheme is performed via hard configuration, by selecting the corresponding IP blocks and configuring the design with them. Similarly, the choice of the transport layer, sizes of on-chip caches (e.g. connection caches), flow FIFOs, etc., are also enabled by hard configuration. Since hard configuration requires preparing dedicated bitstreams, and it incurs overheads to reprogram the FPGA, some fine-grained control decisions are still made via soft configuration. Soft configuration is based on soft register files accessible by the host CPU via PCIe MMIOs, and the corresponding control logic (Soft-Reconfiguration Unit in Figure~\ref{fig:top_level}). Dagger uses soft configuration to control the batch size of CCI-P data transfers, provision the transmit and receive rings, configure their number and sizes, configure the number of active RPC flows, choose a load balancing scheme, etc. Soft reconfiguration comes with certain logic overheads, however, it enables fast and fine-grained tuning of various parameters of the Dagger framework at runtime. The remaining blocks shown in Figure~\ref{fig:top_level} (top) are the Connection Manager used for setting up connections and storing all connection-related metadata, the Packet Monitor that collects various networking statistics, and auxiliary components, such as FIFOs, for proper synchronization of different blocks in the RPC pipeline. The Host Coherent Cache (HCC) is another important auxiliary unit in Dagger. HCC is a small (128 KB) direct-mapped cache implemented in the blue bitstream, which is fully coherent with the host's memory, via the CCI-P stack. HCC is used to hold cache connection states and the necessary structures for the transport layer on the NIC, while the actual data resides in the host memory. This way we avoid requiring dedicated DRAM hardware for the FPGA. This makes NIC cache misses cheaper compared to PCIe-based NICs, since the CCI-P stack provides hardware support for data consistency between the host DRAM and the HCC. \subsection{\new{Dagger API and Threading Model}} \label{sec:threading_model} \new{The API is designed following the standard client-server architecture of cloud applications, and is inspired by the Thrift RPC~\cite{Thrift} framework as well as the Google Protocol Buffers interface, primarily for compatibility reasons, since many microservices rely on either of these APIs. Other RPC APIs, such as gRPC~\cite{gRPC} or Finagle~\cite{finagle} can also be supported by the design. Similarly to commercial RPC stacks, Dagger comes with its own Interface Definition Language (IDL) and code generator. We adopt the Google Protobuf IDL for Dagger; an example of our interface definition scheme is shown in Listing~\ref{d_idl_listing}.} \vspace{0.1in} \definecolor{keywordcolor}{HTML}{cc33ff} \lstdefinestyle{customcpp}{ aboveskip=0in, belowskip=0in, abovecaptionskip=0.08in, belowcaptionskip=0.2in, captionpos=b, xleftmargin=\parindent, language=C++, morekeywords={GetRequest, GetResponse, KeyValueStore, SetRequest, SetResponse, int32}, showstringspaces=false, basicstyle={\small\linespread{0.6}\fontseries{sb}\normalsize\ttfamily}, keywordstyle=\bfseries\color{keywordcolor}, commentstyle=\itshape\color{green!40!black}, } \begin{lstlisting}[style=customcpp, label=d_idl_listing, caption=Dagger IDL on an example of a KVS service.] Message GetRequest { Message GetResponse { int32 timestamp; int32 timestamp; char[32] key; char[32] value; } } Service KeyValueStore { rpc get(GetRequest) returns(GetResponse); rpc set(SetRequest) returns(SetResponse); } \end{lstlisting} \new{The code generator parses target IDL files and produces client and server stubs which wrap up the low-level RPC structures being written/read to/from the hardware into the high-level service API function calls. The latter defines two main classes: the \textit{RpcThreadedServer} and the \textit{RpcClientPool} for each client-server pair. The \textit{RpcClientPool} encapsulates a pool of RPC clients (\textit{RpcClient}) that concurrently call remote procedures registered in the corresponding \textit{RpcThreadedServer} as \textit{RpcServerThread} objects wrapping server event loops and dispatch threads. Dagger supports both asynchronous (non-blocking) and synchronous (blocking) calls. In the former case, each \textit{RpcClient} contains the associated \textit{CompletionQueue} object which accumulates completed requests. The \textit{CompletionQueue} might also invoke arbitrary continuation callback functions upon receiving RPC responses, if so desired.} \new{The Dagger threading model is co-designed across hardware and software and is fully configurable, as is shown in Figure~\ref{fig:threading_model}.} \begin{figure}[h] \centering \setlength{\belowcaptionskip}{-10pt} \includegraphics[width=1\linewidth]{threading_model.pdf} \vspace*{-15pt} \caption{\new{Dagger threading model -- \normalfont {the green Rx/Tx flows correspond to hardware flows on the NIC (only single direction flows are shown for brevity; in the real system, each NIC runs both Rx and Tx flows).}}} \label{fig:threading_model} \end{figure} \new{Dagger provisions multiple flows (queues) on the NIC, such that each flow is 1-to-1 mapped to the corresponding RX/TX ring in software. The rings themselves are 1-to-1 mapped to \textit{RpcClient}'s and \textit{RpcServerThread}'s. The number of NIC flows, and therefore RX/TX rings, determines the degree of concurrency in the Dagger hardware, and is programmable via hard configuration. Note that the number of flows need not necessarily be equal to the number of CPU cores. However, in the basic scheme, shown in Figure~\ref{fig:threading_model}, the number of NIC flows is decided based on the number of logical CPU cores, such that each core gets a dedicated parallel flow on the NIC. Similarly to FaRM, Dagger runs RPC handlers in dispatch threads to avoid inter-thread communication overheads. Also, with a small change in software, it can be configured to run RPC handlers in separate worker threads if required for long-running RPCs; this does not require any hardware changes. } \new{Our threading model allows opening an arbitrary number of connections on each \textit{RpcClient}. In this case, the connections on a certain \textit{RpcClient} share the same RX/TX ring, so following the RDMA terminology, Dagger implements the Shared Receive Queue (SRQ) model~\cite{MPI}. Note that with the programmable threading model, Dagger can be configured to run in a single flow mode with a single RX/TX ring shared between multiple CPU cores. This enables models similar to~\cite{RPCValet} which target addressing load imbalance. At the other extreme, provisioning flows and rings on a per-connection basis is also possible, although such a scheme scales poorly and suffers from high load imbalance. } \new{Dagger manages connections entirely in hardware which further reduces CPU load and improves the look-up of connection information for active flows. The NIC includes the Connection Manager (CM) module, as shown in Figure~\ref{fig:top_level}. The connection table interface maps connection IDs (c\_id) onto tuples <src\_flow, dest\_addr, load\_balancer>. The src\_flow field specifies the ID of the flow receiving requests from the client. The NIC reads this information to ensure that the responses are steered to the same flows where requests came from. The dest\_addr and load\_balancer fields define the address of the destination host and preferred load balancing scheme for requests withing this connection. } \new{The CM is designed as a simple direct-mapped cache with specific memory organization. In order to make the cache access concurrent and avoid stalls in the RPC flows, the cache breaks the above interface tuple into three tables indexed by the $\ceil[\big]{log(N)}$ LSBs (where N is the table size) of the connection ID providing 1W3R functionality. This is required because at the same time (cycle), three independent hardware agents might read from the cache: the RPC outgoing flow (to get the destination credentials), the incoming flow (to get the flow or load balancer), and the CM itself (to open and close connections). The size N of the cache is adjustable with hard configuration and can be chosen based on the expected number of connections the application might open. If some application requires many connections, N can be set to a high value giving more connection cache space to this application in favor of other NIC memory structures. Given the available size of FPGA on-chip memory (53Mb total minus 8.8Mb in the green region) and the size of the current connection tuple (8-12B)x3, the FPGA can be configured to cache at most 153K connections; sufficient for most application scenarios. In addition, the connection cache can be easily backed by DRAM (either externally attached to the FPGA or by the host DRAM) to allow more connections with certain performance penalty due to NIC cache misses. Although this functionality is not yet implemented in our current design, we plan to integrate it as part of future work (see the red lines in Figure~\ref{fig:top_level}).} \subsection{NUMA Interconnects as NIC Interfaces} \label{sec:memory_interconnects} PCIe links have acted as the default NIC I/O interfaces for the past several decades. Despite the bus being a standard peripheral interconnect in any modern processor, a lot of prior work has shown that PCIe is not efficient as a NIC I/O interface~\cite{Cambridge, stanford_mmio}. The inefficiency is mainly introduced in the transmission path, when the NIC is fetching network packets from the host memory. In the simplest case, commercial NICs use DMA transfers initiated by MMIO doorbell transactions to read packet descriptors and payloads from the software buffers; an approach known as the \textit{doorbell method}~\cite{rdma_1}. However, the na\"ive doorbell scheme experiences inefficiencies when targeting small requests. The MMIO transactions are slow, mainly because they are implemented as non-cacheable writes, and expensive: every MMIO request should be explicitly issued by the processor. To reduce the overhead of MMIOs, modern high-performance NICs, such as Mellanox RDMA NICs, implement doorbell batching~\cite{rdma_1}, an optimizations that allows grouping multiple requests into a single DMA transaction initiated with a single MMIO. While this solution noticeably increases the performance of doorbells, it still relies on MMIO messages and is only applicable when requests can be aggressively batched, which is not always possible for latency-sensitive flows. Another proposal~\cite{stanford_mmio} suggests eliminating DMAs, and transferring data only using MMIOs when requests fit in the MMIO's MTU, usually 1 cache line. This improves latency since data are transferred within a single transaction, however, performance is still limited by the low throughput of MMIOs, and during high load, this can overload the processor. The fundamental limitation of PCIe protocols is that their design is primarily geared towards Producer-Consumer dataflow models~\cite{CXL}. The standard doorbell model works well under streaming flows and large data transfers. However, RPC requests do not always conform to such patterns. As we showed in Section~\ref{sec:network_footprint}, RPC sizes in microservices, and in other datacenter applications~\cite{HOMA}, are small, ranging from a few bytes and up to few kilo-bytes. In addition, the strict latency requirements of interactive services often disqualify batching, forcing NICs to handle fine-grained data chunks rather than streaming flows. This issue is further exacerbated when RPC frameworks do not just send requests, but also involve some amount of data processing. For example, Thrift RPC was designed to work with complex data objects that are not uniform in memory; for example, they might contain nested structures and references to other objects. In this case, RPCs must be (de)serialized~\cite{OptimusPrime}, with existing PCIe models being very inefficient in fetching such non-uniformly placed objects. The standard doorbells used in all PCIe-attached NICs require expensive and CPU-inefficient data transformations before sending data to the NIC~\cite{OptimusPrime}. The main insight in leveraging memory interconnects as the NIC I/O is that they allow data transfers to be handled entirely in hardware. The memory consistency state machines (NUMA cache coherence protocols) implemented as a part of the processor's memory subsystem are designed to provide efficient and fast data flows between coherent agents; processors, or more generally, NUMA nodes. Making the NIC act as another NUMA node would allow it to closely integrate its I/O into the processor's memory subsystem, therefore providing a pure hardware CPU-NIC interface without the need for explicit notifications of data updates from the processor. This improves the CPU efficiency of sending small RPCs, since the only operation the processor needs to do is write the RPC requests/responses to the buffer it shares with the NIC, with the actual transfer handled entirely by the interconnect state machines. This increased CPU's efficiency significantly improves per-core RPC throughput (Section~\ref{sec:evaluation}). The exact scheme of data movements inside coherent busses depends on the specific NUMA interconnect model. Some specifications, such as the upcoming peripheral memory interconnect CXL~\cite{CXL}, allow non-cacheable writes to the device memory, meaning that the CPU can directly write RPCs to the NIC, so in addition to improved CPU efficiency, the model also reduces latency, since only one bus transaction is required to send data to the device. Note that we do not compare the \textit{physical} performance of PCIe with respect to memory busses in this work. The peak bandwidth of both interconnects is implementation specific and depends on the number of lanes in the physical layer and the generation of the interconnect. Moreover, some memory interconnects are based on PCIe, so they use the same physical medium with the same bandwidth. All sources of performance gain shown in this work come from the difference in the \textit{logical} upper-level communication models enabled by PCIe vs NUMA protocols. However, the theoretical bandwidth of the UPI bus which we use as the memory interconnect goes up to 19.2 GB/s; slightly higher than the 15.74 GB/s of the PCIe Gen3x16. \subsection{Implementation of the NIC Interface} \label{sec:cpu_nic_interface} The NIC I/O interface consists of the receiving and transmitting paths as seen from the NIC. The CPU-NIC interface diagram is shown in Figure~\ref{fig:cpu_nic_interface}. \begin{figure}[h] \vspace{-5pt} \centering \setlength{\belowcaptionskip}{-10pt} \includegraphics[width=1\linewidth]{interface.pdf} \caption{CPU-NIC interface diagram -- \normalfont {RX path: TX controller writes new RPC requests/responses {\large \textcircled{\small 2}} to a free entry in the TX buffer {\large \textcircled{\small 1}}. The RX FSM on the FPGA fetches RPC objects from the TX buffer over CCI-P {\large \textcircled{\small 3}}; it also does the bookkeeping {\large \textcircled{\small 4}} to release previously-fetched entries. TX path: the TX FSM puts newly-received RPC objects to the RX buffer, and asynchronously fetches the next free entries during bookkeeping {\large \textcircled{\small 6}}. The RPC payload is finally copied to the completion queue {\large \textcircled{\small 7}}.}} \label{fig:cpu_nic_interface} \end{figure} Dagger provisions network buffers (RX/TX rings) on per-NIC flow basis. Each RX/TX pair reflects the communication channel between a single \textit{RpcClient} and the corresponding \textit{RpcThreadedServer} wrapping the dispatch thread. Such buffer provisioning enables lock-free access to the rings from the client and server threads~\cite{NeBuLa}. As stated above, the same \textit{RpcClient} can run multiple threads (each within a separate connection) therefore making them to share the corresponding RX/TX rings. In that case, explicit locking in the \textit{RpcClient} RX/TX path is required to ensure consistent data transfer. The RX/TX ring are used for incoming and outgoing RPCs, respectively. The stack is symmetric, the same architecture serves both requests and responses, i.e., the same NIC and the software stack can be used for both RPC clients and servers. Request types are distinguished by the \textit{request type} field that is a part of every RPC packet. RX/TX rings are comprised of RX/TX buffers and free buffers. The former store RPC payloads for all requests until the NIC/completion queue acknowledges receiving the data by placing the ID of the corresponding RX/TX buffer entry into the free buffer. The size of the TX rings is determined by the rate of incoming RPCs and the time it takes for the NIC to fetch data and is configured during the NIC initialization. In our current prototype, the CCI-P-based memory interconnect, based on Intel UPI, delivers data from the software buffers to the NIC within 400 ns with another 400 ns required for sending back the bookkeeping information. The CCI-P bus can support up to 128 outstanding requests before reaching its bandwidth limit, so Dagger sends multiple asynchronous requests, while the bookkeeping information of in flight requests is pending. The size in the number of requests of the TX rings per flow is $\ceil[\big]{Thr_{per\_flow} * 0.8 / 10^6}$, where $Thr_{per\_flow}$ is the desired throughput of the flow. For $Thr_{per\_flow}$ = 12.4 Mrps (the maximum throughput a single CPU core can sustain in our system), the size of the TX rings should be at least $10\times$ the mean RPC size to avoid flow blocking. Given the typical sizes of RPCs in microservices, every flow requires 0.64-12.8 KB of TX buffers. The RX rings accumulate a batch of requests before sending them to the completion queue. Therefore, the RX buffer size is equal to $B\times$ the mean RPC size, where $B$ is the width of CCI-P batching. In our experiments, the maximum sustained throughput is achieved with batching of $B=4$. Below we detail the hardware design of the receiving and transmitting paths in Dagger. \subsubsection{Receiving path (RX)} We implement three standard PCIe-based methods for fetching RPC data from the processor: doorbell, doorbell batching, and MMIO-based transfer, also known as WQE-by-MMIO in~\cite{rdma_1}, alongside with our proposed method based on memory interconnects. The doorbell transfer is based on standard PCIe DMAs initiated via MMIO transactions. We use the DMA engine provided by the Intel OPAE HDK that operates over CCI-P. The doorbell batching is implemented by grouping CCI-P DMAs into single transactions and initiating the entire batch with a single doorbell. In the MMIO-based method, RPC requests and responses are transferred by writing them to a shared buffer allocated as an MMIO memory region on the FPGA. A typical MMIO write on most processors and NICs is a Write-Combine transaction. Write-Combine is used to avoid generating multiple PCIe transactions when writing data of a cache line size (64B), since processors normally commit word-aligned store instructions (8B). A Write-Combine buffer accumulates multiple stores and sends cache line-long chunks when the buffer is full or is being explicitly flushed. We modify this scheme with parallel store instructions based on the AVX-256 ISA extension and we do not use Write-Combining; this allows us to further reduce the MMIO latency. In this mode, Dagger writes every 64B of RPC requests using two \_mm256\_store\_si256 stores. The memory interconnect-based interface in Dagger is implemented over the Intel UPI coherent bus. Unfortunately, since CCI-P is the first commercially-available implementation of the UPI bus on an FPGA, the corresponding IP core, which is a part of the blue region of the FPGA bitstream and is therefore not accessible to users, only allows accessing CPU memory via memory polling. Given this limitation, Dagger starts by polling its local cache which is coherent with the processor's LLC and relies on invalidation messages to bring new data from software buffers. However, since the FPGA allocates data in its local cache in this case, it causes the CPU to lose ownership of the corresponding cache lines therefore hurting the data transfer's efficiency. For this reason, Dagger dynamically switches to direct polling of the processor's LLC when the load becomes high, as defined by a programmable threshold. Note that the current limitation of transferring data through polling is not fundamental to Dagger's design, but rather an implementation artifact of the currently-available realization of a memory interconnect on an FPGA. The next generation of FPGAs (Intel Agilex) already integrates a more advanced interconnect IP based on the CXL~\cite{CXL} specification. As mentioned above, the CXL protocol supports direct data writes from CPUs to the FPGA's memory without the need for memory polling. \subsubsection{Transmitting path (TX)} \label{sec:tx_path} The transmission path has some additional complexity compared to the RX path due to the need for load balancing and scheduling/distribution of flows over the active queues. Figure~\ref{fig:tx_paths}A shows the architecture of Dagger's TX path. \begin{figure}[h] \vspace{-5pt} \centering \setlength{\belowcaptionskip}{-10pt} \includegraphics[width=1\linewidth]{tx_path.pdf} \caption{(A) Architecture and (B) Implementation of TX path. } \label{fig:tx_paths} \end{figure} Incoming RPCs should be distributed across the available receiving rings (RX buffers in Figure~\ref{fig:cpu_nic_interface}), and within a ring, the requests can be batched for more efficient data transfer, if a service's latency target permits it. Distribution of requests across rings is handled by the Load Balancer (as a part of the RPC unit, refer to Figure~\ref{fig:top_level} (bottom)) that directs incoming RPCs to the corresponding Flow FIFOs. Each RX buffer gets a dedicated Flow FIFO on the NIC. The Load Balancer currently supports two request distribution schemes: dynamic uniform steering and static load balancing. In the first case, incoming RPCs are evenly distributed across the available flows. In the static balancing, the RPCs are distributed based on the information stored in the corresponding connection tuple on the server. In addition, we leave some room in the design for implementation of application-specific load balancers (e.g. the Object-Level core affinity mechanism in MICA~\cite{MICA}). The Flow Scheduler then picks a Flow FIFO that already contains enough requests to form a transmission batch and instructs the CCI-P transmitter to send the batch to the corresponding ring. The architecture in Figure~\ref{fig:tx_paths}A is implemented in hardware, as shown in Figure~\ref{fig:tx_paths}B. Since Dagger's RPCs are at least 64 Bytes long, storing them in FIFOs for each flow and then multiplexing the flows is not practical, and adds complexity to the design. Instead, Dagger implements a request buffer, shown as the green table in Figure~\ref{fig:tx_paths}, which stores all incoming RPCs in a lookup table indexed by the slot\_id. The Free Slot FIFO is designed to keep track of free entries in the request buffer. The Flow FIFOs in this case only contain references (slot\_ids) to the actual RPC data in the table. When sending data, the CCI-P transmitter directly reads RPC payloads from the request table based on the references read from the corresponding Flow FIFO. The size of the request table is equal to $B * N_{flows}$ entries, where B is the CCI-P batching and $N_{flows}$ is the total number of NIC flows. \subsection{RPC Pipeline} \label{sec:rpc_pipelne} The CPU-NIC interface is the first unit of the RPC pipeline; the other two being the RPC module and Transport layer (Figure~\ref{fig:top_level}). The architecture of the RPC module is zoomed-in in Figure~\ref{fig:top_level} (bottom). It implements request serialization/de-serialization between ready-to-use RPC objects, as read from the processor and the network. If compression/encryption is required, the corresponding logic can optionally be integrated into the unit. In addition, the RPC module also contains a set of load balancers that decide which flow to steer incoming requests. The choice of the load balancer is controlled at server granularity, i.e. each server can specify the load balancer it requires when registering connections on it. The Protocol is the last module of the RPC unit. It is designed to implement RPC-optimized protocol layers such as congestion control, piggybacking acknowledgement, transactions built into the RC stack, etc., and is currently idle. Systems similar to TONIC~\cite{TONIC} can be used to implement the Protocol unit. The RPC unit is connected (over FIFOs, for synchronization) with the Transport layer which implements a version of the UDP/IP protocol and sends outgoing serialized RPC requests to the Ethernet network. Since data transformations and RPC transport protocols are not the focus of this work, we simplify these parts of the pipeline. Our current implementation only supports RPCs with continuous arguments that do not contain references to other objects and application-specific data-structures requiring custom serialization, and the Protocol unit is currently idle - it simply forwards all packets to the network. In the following-up work, we plan to extend Dagger with reliable transports and with RPC-specific congestion control mechanisms which has been shown to be more efficient in datacenter networks than TCP~\cite{DBLP:conf/nsdi/KaliaKA19}. \subsection{Dagger Implementation} \label{sec:implementation} We implement Dagger on an Intel Broadwell CPU/FPGA hybrid architecture. The host processor is a server-class Intel Xeon E5-2600v4 CPU integrated with an Arria 10 GX1150 FPGA. The hardware part (Dagger NIC) is written in SystemVerilog using the Intel OPAE HDK library. The software part is designed in C++11 and is compiled by GCC under under the O3 optimization level. The Dagger IDL code generator is written in Python 3.7. The software modules of our RPC stack run in user space, and the NIC buffers are allocated by the FPGA driver in the application virtual address space. The most important implementation parameters of the Dagger NIC design are summarized in Table~\ref{tab:implementation_details}. \begin{table}[] \begin{threeparttable} \caption{Implementation specifications of Dagger NIC.} \label{tab:implementation_details} \begin{tabular}{l||l} \hline \multicolumn{1}{c||}{\textbf{Parameter}} & \textbf{Value} \\ \hline \hline CPU-NIC interface clock frequency, MHz & 200 - 300 \\ RPC unit clock frequency, MHz & 200 \\ Transport clock frequency, MHz & 200 \\ Max number of NIC flows \tnote{1} & 512 \\ FPGA resource usage, LUT (K) \tnote{2} & 87.1 (20\%) \\ FPGA resource usage, BRAM blocks (M20K)\tnote{2} & 555 (20\%) \\ FPGA resource usage, registers (K) \tnote{2} & 120.8 \\ \hline \end{tabular} \begin{tablenotes}\footnotesize \item[1] Assuming 65K entries in the connection cache and ensuring the FPGA BRAM and logic utilization do not exceed 50\% \item[2] Including the blue region; UPI-based NIC I/O with 64 NIC flows and 65K entries in the connection cache \vspace{-8pt} \end{tablenotes} \end{threeparttable} \end{table} \subsection{Limitations} \label{sec:limitations} An important limitation of the current design is the lack of support for efficient RPC reassembling to enable transfer of requests larger than the cache line size. In contrast to PCIe DMA, memory interconnects implement relaxed memory consistency models, which is one of the key reasons behind their efficiency. Therefore, the MTU of a typical memory interconnect is only a single cache line~\cite{NeBuLa}. A na\"ive solution to address the issue of sending larger RPCs is to reassemble requests in software. However, this will introduce CPU overheads and violate our first design principle. Another solution, as proposed in NeBuLa, leverages Content Addressable Memory (CAM) for on-chip reassembling in hardware. Unfortunately, CAMs are expensive in terms of area and energy, and it is challenging to implement them with low overheads on an FPGA. Efficient RPC reassembling in hardware is a challenging issue, and we plan to address it as part of future work. As of now, Dagger only features software-based RPC reassembling. \section{Discussion} \label{sec:discussions} \new{As shown in Dagger's evaluation, relying on memory interconnects for high performance datacenter networking is beneficial, however one might argue that integrating FPGAs/NICs over conventional PCIe busses imposes fewer constraints over the type of CPU a system can use. Additionally, while PCIe is more widely adopted as a peripheral interconnect in today's processors, this trend is increasingly changing. First, the UPI/QPI interconnect is natively supported by all modern datacenter processors (e.g., Xeon family), and any FPGA which implements the UPI/QPI specification can be integrated in it. As of today, we are aware of two such FPGA families: Intel Broadwell Arria 10 (used in this work) and the new Stratix 10 DX device. A similar technology is also being developed by IBM. Their OpenCAPI~\cite{OpenCAPI} cache-coherent CPU-FPGA interface is already used in recent research work on disaggregated memory~\cite{ibm_disaggr}. Second, there is an ongoing collaborative effort from multiple hardware vendors to derive a specification for a new peripheral interface with cache coherency support (CXL) for future devices. Similar efforts in academia have yielded systems like ETH's Enzian~\cite{ETHEnzian}, which closely couples an FPGA with an ARM-based datacenter CPU over the Cavium coherent interconnect CCPI~\cite{cavium}. We believe, Enzian can also be a good physical medium for Dagger. } \new{Virtualization of network interfaces is another topic around Dagger's design. NIC virtualization enables efficient sharing of a single physical interface between multiple tenants, such as different guest operating systems. Given that Dagger is based on an FPGA and it can be tuned for different applications based on their network characteristics and requirements, it provides an excellent framework to enable virtualization. As seen from Table~\ref{tab:implementation_details}, the Dagger NIC occupies less than 20\% of the available FPGA space when synthesized with a relatively large number of flows and connection cache space. This demonstrates that the same FPGA device can accommodate multiple instances of the NIC at the same time as we show in Section~\ref{sec:eval_microservices}. Each instance can be used as a ``virtual but physical'' NIC for the corresponding tenant, and it can be configured based on the network provisioning requirements of each tenant. } \new{Additionally, we note that the BRAM memory of FPGAs is one of the key resources enabling reconfigurability and efficiency in Dagger. By leveraging the FPGA to manage on-chip memory one can flexibly split the available memory capacity (53Mb for the FPGA used in Dagger) at very fine granularity, therefore improving the efficiency of NIC caches which is crucial, since NIC cache misses are one of the main performance bottlenecks in commercial NICs~\cite{rdma_1}. This is especially important in the aforementioned virtualized environment. For example, with FPGAs, it is possible to allocate more connection cache memory for NIC instances serving tenants with a large number of connections, or more packet buffer space for tenants experiencing large network footprints. Such on-chip NIC cache management can be easily done at the NIC instance granularity. } \new{Finally, Dagger-like designs enable efficiently co-designing RPC stacks with transactions in hardware. For instance, in our example of the Flight Registration application in Section~\ref{sec:eval_microservices}, the \textit{Airport} service concurrently processes requests from both the \textit{Check-in} service and \textit{Staff Frontend}. As of now, we implement a lock-based concurrency control mechanism in software which comes with certain overheads in the OS. Alternatively, given the fully programmable nature of FPGAs, one can run synchronization protocols at the RPC level, on the Dagger NIC, such that all requests being received by the service are already serialized. Applications with more complicated transactional semantics (e.g., Paxos, 2PC, etc.) can specifically benefit from this support. } \section{Evaluation} \label{sec:evaluation} \subsection{Methodology} We evaluate Dagger along five dimensions. First, we compare Dagger with prior work on efficient RPC processing based on user-space networking and RDMA. Second, we evaluate different CPU-NIC interfaces and show the performance benefits of memory interconnects over PCIe. Third, we show how Dagger scales with the number of CPU threads. In addition, we demonstrate that Dagger can be easily integrated with existing datacenter applications, such as memcached and MICA, offering dramatic latency improvement under realistic workloads. Finally, we run a simple microservice application on top of Dagger showing that our RPC stack is indeed suitable for multi-tier systems. Table~\ref{tab:platform_spec} shows the specification of the hardware platform used. \begin{table}[h] \caption{Hardware specifications of experimental platform. } \label{tab:platform_spec} \begin{tabular}{llll} \hline \multicolumn{4}{l}{\textbf{CPU: Intel Xeon E5-2600v4}} \\ \hline & Cores & & \begin{tabular}[c]{@{}l@{}}12 cores (OOO), 2 threads per core, \\ 2.4 GHz, 14 nm\end{tabular} \\ & LLC & & 30720 kB, 64 B \\ & Additional features & & AVX-2, DDIO, VT-x \\ & OS & & \begin{tabular}[c]{@{}l@{}}CentOS Linux,\\ Kernel Linux 3.10.0\end{tabular} \\ \hline \multicolumn{4}{l}{\textbf{Interconnect: CCI-P: 2x PCIe and 1x UPI}} \\ \hline & PCIe & & \begin{tabular}[c]{@{}l@{}}Gen3x8, 7.87 GB/s, 2 links,\\ total bandwidth 15.74 GB/s\end{tabular} \\ & UPI & & \begin{tabular}[c]{@{}l@{}}9.6 GT/s (19.2 GB/s), 1 link,\\ total bandwidth 19.2 GB/s\end{tabular} \\ \hline \multicolumn{4}{l}{\textbf{FPGA: Arria 10 GX1150}} \\ \hline & Max frequency & & 400 MHz \\ \hline \end{tabular} \end{table} Due to the limitation on the number of FPGA-enabled machines on the Intel vLab cluster, we instantiate two identical Dagger NICs on the same FPGA and connect them to each other via a loop-back network. We then give the NICs fair round-robin access to the CCI-P bus by multiplexing it. Note that since the main contribution of Dagger is in CPU-NIC interface and the RPC pipeline, the absence of physical networking does not affect our findings. \subsection{Performance Comparison across RPC Platforms} We compare the performance of Dagger's RPC acceleration fabric with four related proposals, based on DPDK user-space networking IX~\cite{IX}, raw user-space networking eRPC~\cite{DBLP:conf/nsdi/KaliaKA19}, RDMA FaSST~\cite{FASST}, and the in-memory integrated NIC NetDIMM~\cite{NetDIMM}. Table~\ref{tab:eval_3} shows the median round trip latency and the throughput achieved by each system. We also show the TOR (Top of Rack) delay assumed in each work, the size of the being transferred objects, and their type. Note that if the object type is ``msg'', this means that the system does not implement the RPC layers of the networking stack, and the reported results do not include the overhead of RPC processing. \setlength\belowcaptionskip{-1ex} \begin{table}[h!] \begin{threeparttable} \centering \caption{Median round trip time (RTT) and throughput of single-core RPCs compared to related work \tnote{1}. } \label{tab:eval_3} \begin{tabular}{c|c|c|c|c||c} \hline & \textbf{IX} & \textbf{\begin{tabular}[c]{@{}c@{}}FaSST\end{tabular}} & \textbf{\begin{tabular}[c]{@{}c@{}}eRPC\end{tabular}} & \textbf{\begin{tabular}[c]{@{}c@{}}Net-\\DIMM\end{tabular}} & \textbf{\begin{tabular}[c]{@{}c@{}}Dagger\end{tabular}} \\ \hline \hline \textbf{Objects} & \begin{tabular}[c]{@{}c@{}}64B\\ msg\end{tabular} & \begin{tabular}[c]{@{}c@{}}48B\\ RPC\end{tabular} & \begin{tabular}[c]{@{}c@{}}32B\\ RPC\end{tabular} & \begin{tabular}[c]{@{}c@{}}64B\\ msg\end{tabular} & \begin{tabular}[c]{@{}c@{}}64B\\ RPC\end{tabular} \\ \textbf{\begin{tabular}[c]{@{}c@{}}TOR \\ delay\end{tabular}} & N/A & 0.3 us & 0.3 us & 0.1 us & 0.3 us \\ \textbf{\begin{tabular}[c]{@{}c@{}}RTT, us\end{tabular}} & 11.4 & 2.8 & 2.3 & 2.2 & 2.1 \\ \textbf{\begin{tabular}[c]{@{}c@{}}Thr., \\ Mrps\end{tabular}} & 1.5 & 4.8 \tnote{2} & 4.96 \tnote{2} & N/A & 12.4 \\ \hline \end{tabular} \begin{tablenotes}\footnotesize \item[1] Performance numbers are provided from corresponding papers \item[2] Recorded in symmetric experimental settings \end{tablenotes} \end{threeparttable} \end{table} As seen from Table~\ref{tab:eval_3}, Dagger shows $1.3 - 2.5\times$ (depending on experimental settings) higher per-core RPC throughput than the RDMA-based solution, FaSST, and the DPDK-based eRPC. The gain partially comes from offloading the entire RPC stack on hardware and leaving only a single memory write in the critical RPC path on the processor. In addition, approximately 14\% of performance improvement is enabled by replacing the doorbell batching model with our memory interconnect-based interface. Note that neither PCIe's nor UPI's physical bandwidth is saturated in this experiment, so these 14\% come from the better messaging model enabled by memory interconnects. Table~\ref{tab:eval_3} also shows that Dagger achieves the lowest median round trip time of $2.1us$, while significantly improving throughput compared to both user-space and kernel-level networking. This is better than FaSST, and even the integrated solution NetDIMM, and is comparable with eRPC. \subsection{Comparison of CPU-NIC Interfaces} Figure~\ref{fig:eval_1} shows the comparison of Dagger's end-to-end single-core latency and throughput for different CPU-NIC interfaces. Unless otherwise specified, the PCIe CPU-NIC interface is based on a single PCIe Gen3x8 link. The maximum theoretical (physically bounded) throughput is 122 Mrps for 64 Byte RPCs on all cores. \begin{figure}[h] \vspace{-5pt} \centering \includegraphics[scale=0.43]{bar_chart.pdf} \vspace*{-5mm} \caption{Dagger's single-core throughput and latency for different CPU-NIC interfaces (RX path) when transferring 64 Bytes RPCs -- \normalfont {B denotes request batching. }} \label{fig:eval_1} \end{figure} As seen from Figure~\ref{fig:eval_1}, the lowest median and tail latency over a PCIe bus is achieved when the RX path uses MMIO writes, which is reasonable, since in this case all RPCs are being written within a single PCIe transaction. However, the method fails to deliver high throughput, with the best reported result being 4.2 Mrps. A similar throughput of 4.3 Mrps but with higher median latency is reported when Dagger is using non-batched doorbells showing that their performance is limited by the rate of initiating MMIOs. The only way to increase the efficiency of doorbells is to use batching which enables reaching a throughput of 10.8 Mrps for batch of $B = 11$. The memory interconnect-based transfer (UPI in Figure~\ref{fig:eval_1}) achieves single-core throughput of 12.4 Mrps with $B = 4$, and demonstrates noticeably lower median and tail latency. Note that the latency improvement does not exclusively come from the reduced number of bus transactions for the transfer using the memory interconnect. We conduct another experiment in which we access an address in the shared memory over PCIe (using DMA) and over UPI. The PCIe DMA gives us $450 us$ of median one-way latency while the UPI read achieves $400 us$. This shows that UPI is physically slightly faster than PCIe. \new{Finally, we measured the maximum single-core throughput of Dagger at 16.5 Mrps, with best-effort request processing by allowing arbitrary packet drops by the server. } \subsection{Latency vs Throughput} Figure~\ref{fig:eval_2} (left) shows Dagger's latency under different loads with the memory interconnect-based NIC. \setlength\belowcaptionskip{-1ex} \begin{figure}[h!] \vspace{-8pt} \centering \begin{minipage}[b]{0.49\linewidth} \centering \includegraphics[width=\linewidth]{thr_lat_results.pdf} \end{minipage} \hfill \begin{minipage}[b]{0.49\linewidth} \centering \includegraphics[width=\linewidth]{th_vs_cores.pdf} \end{minipage} \caption{Latency-Throughput curves for single-core asynchronous round-trip 64B RPCs (left) and multi-core scalability of sending 64B requests (right) -- \normalfont {B denotes batching, dotted lines show the saturation point. The black line shows end-to-end RPC throughput, the dashed line denotes estimated linear scalability, and the red line shows the results of the UPI bus's scalability with raw idle requests. }} \label{fig:eval_2} \end{figure} With CCI-P batching $B = 1$, Dagger achieves the lowest median latency (round trip time) of $1.8 us$, which remains stable across the entire load range, up to the throughput saturation point of 7.2 Mrps. When increasing batching to $B = 4$, Dagger's throughput increases to 12.4 Mrps with a latency of $2.8 us$. Note that when the load is low, the request latency is relatively high since the RPC pipeline needs to wait until the batch is full. Dagger leverages soft configuration to adjust the batch size dynamically when the load becomes high so that the throughput advantages of batching do not come at a latency cost (as shown by the green dashed line in Figure~\ref{fig:eval_2} (left)). \subsection{Thread Scalability} Figure~\ref{fig:eval_2} (right) plots the scalability of Dagger with the number of CPU threads (logical cores). The system throughput scales linearly up to 4 threads (2 physical cores) and remains flat at 42 Mrps. Note that since we run both the RPC client and server on the same CPU, this effectively translates to 84 Mrps as seen by the processor. This result is $\approx23\%$ higher than the performance reported in the FaSST paper on the CIB cluster, and is $3.5\times$ better than IX under the same number of cores. The saturation results signal that the current bottleneck is not the processor. The NIC itself, which is capable of processing up to 200 Mrps, is also far from saturated. To better understand the scalability of Dagger, we run another experiment in which we send idle memory read requests over the UPI interconnect, the results of which are shown in Figure~\ref{fig:eval_2} (right) in red. The throughput of idle memory reads also scales linearly up to 80 Mrps with 7 threads, and stays flat when one more thread is added. Note that the UPI bus has the total physical bandwidth of 19.2 GB/s (Table~\ref{tab:platform_spec}) which is significantly more than 80Mrps for 64 Byte RPCs. Based on this experiment, we conclude that the current bottleneck is the implementation of the UPI end-point on the FPGA in the blue region. Since this region is encrypted, we are not able to optimize it in the current prototype, however, the upcoming generation of Intel Agilex FPGAs will have a dedicated hard IP core for memory interconnects, which should address this scalability issue. \subsection{End-to-End Evaluation on KVS systems} \label{sec:kvs_eval} We evaluate the end-to-end performance of Dagger on two real KVS systems: memcached~\cite{memcached} and MICA~\cite{MICA}. Memcached is a popular in-memory key-value store, widely used in microservices~\cite{DeathStarBench,Sriraman2018SA,OptimusPrime}. In this experiment, we run the original version of memcached over Dagger with the UPI-based I/O instead of the native transport protocol based on TCP/IP for SET and GET commands. We modify only $\approx$50 LOC of the Memcached source code in order to integrate it with Dagger. We also keep the original memcached protocol to verify the integrity and correctness of the data. \new{While memcached is a suitable application because of its wide adoption in both industry and academia, it is relatively slow ($\approx$12$\times$ slower than Dagger). Therefore, the performance of memcached over Dagger is bottlenecked by memcached itself, which does not allow Dagger to achieve its full potential. In order to make the evaluation more comprehensive, we also port MICA over Dagger, another well-known KVS system in the academic community. MICA is designed specifically to provide high throughput for small requests, and, in contrast to memcached, it can be, under certain workloads, network-bounded. We run MICA over Dagger with no changes to the original codebase; we simply implement a MICA server application which integrates it with Dagger with $\approx$200 LOC.} \new{To evaluate the KVS systems, we generate two types of datasets similar to the ones used to evaluate MICA~\cite{MICA}: tiny (8B keys and 8B values) and small (16B keys and 32B values). We populate both memcached and MICA KVS with 10M and 200M unique key-value pairs respectively, and access them over the Dagger fabric, following a Zipfian distribution~\cite{zipf} with skewness of 0.99. For MICA, we use their original benchmark and workload generator~\cite{MICASource}. We load both systems with two types of workloads: write-intense (set/get = 50\%/50\%) and read-intense (set/get = 5\%/95\%). We adjust the workload generator such that the number of packet drops on the server is always < 1\%. The results of running memcached and MICA with Dagger on a single core are shown in Figure~\ref{fig:eval_4}.} \setlength\belowcaptionskip{-1ex} \begin{figure}[h!] \vspace{-6pt} \centering \begin{minipage}[b]{0.49\linewidth} \centering \includegraphics[width=\linewidth]{kvs_single_core_latency.pdf} \end{minipage} \hfill \begin{minipage}[b]{0.49\linewidth} \centering \includegraphics[width=\linewidth]{kvs_single_core_thr.pdf} \end{minipage} \vspace{-6pt} \caption{\new{Performance of memcached and MICA running over Dagger: request latency (left) and throughput (right) -- \normalfont {latency results recorded under the write-intensive workload and the peak single-core throughput. }}} \label{fig:eval_4} \end{figure} \new{Figure~\ref{fig:eval_4} (left) shows the latency of the KVS systems running over Dagger. Latency is defined as the round-trip time between the moment when a request is issued by a core and when the result is received. We measure latency for the write-intensive (set/get = 50\%/50\%) workload in a similar way to~\cite{MICA} to ensure a fair comparison. Memcached achieves the lowest median latency of $2.8 us$, and a $99^{th}$ percentile latency of $6.9 us$, when running under a $0.6 Mrps$ load on a single core for tiny requests. For small requests, the results are slightly higher. The MICA KVS shows a better tail latency of $5.4 us$ and $5.7 us$ for tiny and small requests, respectively. It is $4.4 - 5.2\times$ lower than the latency numbers reported in the original MICA work when running it over the lightweight DPDK-based networking stack. This result shows that Dagger can offer dramatic latency reduction in high performance KVS systems compared to optimized user-space networking. } \new{The KVS throughput results are shown in Figure~\ref{fig:eval_4} (right). With the workload that we use, the systems are still bottlenecked by the key-value store. Dagger can reach up to $12.4 Mrps$ of single-core throughput, where memcached and MICA had a limit of $0.6 - 1.6$ and $4.8 - 7.8$ Mrps, respectively. For this reason, the single-core throughput improvement of Dagger remains hidden. At the same time, these results show that integrating our RPC stack does not add any additional throughput overhead compared to software-based networking systems. To better load MICA, we also test it under a distribution with skewness of 0.9999, which yields even higher data locality, and therefore better cache utilization. With such a workload, Dagger achieves a throughput of 10.2 Mrps and 9.8 Mrps for read- and write-intensive workloads with the same latency numbers, as in Figure~\ref{fig:eval_4}, therefore bringing the performance of MICA closer to the peak performance of Dagger. } \new{We do not show results of multi-core scalability for MICA, since the extensive amount of LLC contention introduces considerable instability in the results. The contention is caused by running both client and server on the same CPU, without the possibility to partition the cache, therefore allowing them to share the same portion of LLC. The client runs the workload generator which reads 1.49GB of data at a very high rate from its internal buffer making the LLC traffic very high. As part of future work, we plan to deploy Dagger to a cluster environment with physically distributed FPGAs to avoid client-server colocation, and measure more representative multi-core throughput results. } \vspace{-5pt} \subsection{End-to-End Evaluation on Microservices} \label{sec:eval_microservices} Finally, we evaluate Dagger on an end-to-end application built with microservices. We design a simple multi-tier service with 8 microservices which implements a Flight Registration service, shown in Figure~\ref{fig:eval_5}. \begin{figure}[h] \centering \includegraphics[width=1\linewidth]{microservice_eval_a.pdf} \caption{Flight Registration microservice architecture -- \normalfont{the passenger front-end generates uniformly random passenger registration requests to the Check-in service. The Check-in service then consults the Flight service for flight information data, the Baggage service for the status of the passenger's baggage, and the Passport service to check the passenger's identity. The Passport service issues nested requests to the Citizens database (based on MICA~\cite{MICA}). Upon receiving all responses, the Check-in service registers the passenger in the Airport database (also based on MICA cache). The latter is additionally accessible by the Staff front-end, which is used to asynchronously check all records in the system.}} \label{fig:eval_5} \end{figure} We design the Flight Registration service such that it exhibits different types of dependencies across tiers (one-to-one, one-to-many, many-to-one), and includes both chain and fanout dependencies. All services communicate with each other over RPC calls and run different threading models to show the flexibility of Dagger. In particular, the \textit{Passenger} and \textit{Staff Frontend} services run non-blocking RPCs to avoid throughput bottlenecks due to high request propagation times. Similarly, the \textit{Check-in} service issues non-blocking requests to the \textit{Flight}, \textit{Baggage}, and \textit{Passport} services, but it later blocks until it receives all the responses before proceeding with blocking calls to the \textit{Airport} service. The \textit{Passport} service also runs blocking RPCs to the Citizens database. In our first experiment, each RPC server processes requests in the dispatch thread to benefit from its low-latency, zero-copy operation. \begin{figure}[h] \centering \setlength{\belowcaptionskip}{-10pt} \includegraphics[width=1\linewidth]{microservice_eval_b.pdf} \caption{Virtualization of the Dagger NIC to serve multiple tiers running on the same physical machine -- \normalfont{the PCIe/UPI arbiter provides fair round-robin sharing of the CCI-P bus between tenants; the Switch performs simple L2 packet switching based on the pre-defined static switching table.}} \label{fig:virtualization} \end{figure} Similarly to our previous experiments, and due to the limitations of the cluster, we run all services on the same machine and over the same physical FPGA. Such a setup requires virtualization pf the NIC to ensure that each tier gets an independent Dagger NIC therefore reflecting the real distributed setup when each tier runs on a separate physical or virtual machine. By placing all tiers on the same machine we additionally show how the Dagger NIC can be virtualized. Our NIC is virtualizable by putting multiple instances of it on the same FPGA and giving them fair round-robin sharing of the system bus and memory. Each instance of the NIC is serving a dedicated microservice tier, i.e., in this experiment, we instantiate 8 copies of the Dagger NIC, as shown in Figure~\ref{fig:virtualization}. The NICs are connected with each other over our simple model of a ToR networking switch with a static switching table. In Section~\ref{sec:discussions}, we give more details on virtualization and show how different microservice tiers can benefit from it. As previously mentioned, we first run the Flight Registration service with the \textit{Simple} threading model in which each service handles RPC requests directly in dispatch threads along with the networking I/O. The results of this experiment are summarized in the first row in Table~\ref{tab:microservces_results}. \begin{table}[h] \begin{threeparttable} \caption{Summary of performance results for the Flight Registration service. } \label{tab:microservces_results} \begin{tabular}{l|l|l|l|l} \hline \multicolumn{1}{c|}{\multirow{2}{*}{\begin{tabular}[c]{@{}c@{}}Threading\\ model\end{tabular}}} & \multicolumn{1}{c|}{\multirow{2}{*}{\begin{tabular}[c]{@{}c@{}}Highest load,\\ Krps \tnote{1} \end{tabular}}} & \multicolumn{3}{c}{Lowest latency, us} \\ \cline{3-5} \multicolumn{1}{c|}{} & \multicolumn{1}{c|}{} & Median & 90th & 99th \\ \hline \hline Simple & 2.7 & 13.3 & 20.2 & 23.8 \\ \hline Optimized & 48 & 23.4 & 27.3 & 33.6 \\ \hline \end{tabular} \begin{tablenotes}\footnotesize \item[1] Recorded when the total number of request drops across all tiers does not exceed 1\%. \end{tablenotes} \end{threeparttable} \end{table} As seen from Table~\ref{tab:microservces_results}, the maximum throughput with the \textit{Simple} threading model is limited to $2.7 Krps$, however, the system shows low $\mu$s-scale end-to-end latency. In order to profile the application, we design a lightweight request tracing system and integrate it with Dagger. Our analysis reveals that the system is bottlenecked by the resource-demanding and long-running \textit{Flight} service. Handling such RPCs in dispatch threads limits the overall throughput since they block the NIC's RX rings from reading new requests. One well-known way~\cite{RAMCloud} to address this issue is to use different dispatch and worker threads for networking IO and RPC handling. Similar intuition applies to the \textit{Check-in} and \textit{Passport} services. Those are not resource-intensive, but they issue multiple nested blocking RPC calls, and therefore run for a relatively long time. In our next experiment, we configure the \textit{Flight}, \textit{Check-in}, and \textit{Passport} service's RPC servers to run request processing in worker threads (\textit{Optimized} threading model). The results in the second row in Table~\ref{tab:microservces_results} show that such a change in the threading model dramatically increases the overall application throughput by up to 17$\times$. Note that the latency became larger in this case due to the overhead of inter-thread communication and additional request queueing between the dispatch and worker threads. Figure~\ref{fig:microservices_eval} shows a more comprehensive view onto the system behaviour when running with the \textit{Optimized} threading model. The 8-tier Flight Registration service running over Dagger achieves a median and tail latency of $23$ and $33 us$ respectively before the throughput saturation point of $25 Krps$. When throughput crosses the saturation point, the tail latency soars sharply, while the median latency stays at the level of $23 - 26 us$. We do not increase the load further due to the quickly growing number of request drops after that point. \begin{figure}[h] \centering \setlength{\belowcaptionskip}{-5pt} \includegraphics[width=1\linewidth]{microservice_eval_results_b.pdf} \vspace*{-6mm} \caption{Latency/load curves for the Flight Registration service with the \textit{Optimized} threading model -- \normalfont{the figure on the left shows a zoomed-in view of the latency over the load up to 30 Kqps in linear scale. }} \label{fig:microservices_eval} \end{figure} In addition to configuring the software part of Dagger to run different threading models, we also configure the NICs differently. All services in our Flight Registration benchmark besides the \textit{Airport} and \textit{Citizens} services are stateless and they do not cache any data. For this reason, the round-robin dynamic RPC load balancer works best for them and we configure the corresponding NICs to use it. In contrast, the two mentioned services are stateful, and they run the MICA KVS in the backend. However, MICA does not work correctly with round-robin/random load balancers due to the way it partitions the object heap across CPU cores/NIC flows. MICA requires that all requests with the same keys always go to the same partition, and in the original work, it uses Flow Director to steer requests to cores/partitions. In this experiment, we implement our own application-specific Object-Level~\cite{MICA} load balancer for MICA tiers by applying the hash function to each request's key on the FPGA before steering them to the flow FIFOs, and instantiate it inside the Dagger NICs serving the corresponding tiers. This shows how NICs running hardware-offloaded RPCs on FPGAs can be flexibly programmable to satisfy the needs of different applications. More hardware parameters of the NICs can be further fine-tuned for each individual microservice as we briefly discuss in Section~\ref{sec:discussions}. \section{Introduction} \label{sec:intro} Modern cloud applications are increasingly turning to the microservices programming model to improve their agility, elasticity, and modularity~\cite{uTune,DeathStarBench,Cockroft16,Sriraman2018SA,Cockroft15,twitter_decomposing,Gan18,Gan19b,Lazarev20,Chen19,xcontainers,Zhang19,Gan21,Zhang21,Delimitrou13,Delimitrou14,Gan18c,Delimitrou15,Delimitrou16,Delimitrou17}. Microservices break complex monolithic applications, which implement the entire functionality as a single service, into many fine-grained and loosely-coupled tiers. This improves design modularity, error isolation, and facilitates development and deployment. However, since microservices communicate with each other over the network, they also introduce significant communication overheads~\cite{DeathStarBench,OptimusPrime}. Given that individual microservices typically involve a small amount of computation, networking ends up being a large fraction of their overall latency~\cite{DeathStarBench, Sriraman2018SA}. Furthermore, since microservices depend on each other, performance unpredictability due to network congestion can propagate across dependent tiers and degrade the end-to-end performance~\cite{Gan19b,causeinfer,microscope,explainit,sosp03blackbox}. Microservices typically communicate with each other over Remote Procedure Calls (RPC)~\cite{Thrift,gRPC,finagle}. Unfortunately, existing RPC frameworks were not designed specifically for microservices, whose network requirements and traffic characteristics differ from traditional cloud applications, and therefore introduce significant overheads to their performance. The strict latency requirements, fine-grained requests, wide diversity, and frequent design cadence of microservices put a lot of pressure on the network system, and makes rethinking networking with microservices in mind a pressing need. Most of the existing commercial RPC frameworks are implemented on top of commodity OS networking, such as Linux TCP/IP. While this ensures generality, such systems suffer from considerable overheads across all levels of the system stack~\cite{IX,OptimusPrime}. These overheads accumulate over deep microservice call paths, and result in end-to-end QoS violations. While this affects all microservices, it is especially challenging for interactive tiers, which optimize for low tail latency, instead of average throughput. The past decade has seen increased interest both from academia and industry for lower latency and higher throughput networking systems. One line of work focuses on optimizing transport protocols~\cite{HOMA, mTCP, DCTCP,pFABRIC}, while another moves networking to user space~\cite{IX, DBLP:conf/nsdi/KaliaKA19, Seastar,mTCP}, or offloads it to specialized adapters~\cite{FARM, FASST,Ming2012UserspaceRO, AccelTCP,HotNet}. Network programmability has also gained traction through the use of SmartNICs~\cite{P_Costa, E3,msft} to tune the network configuration to the performance requirements of target applications. Despite the performance and efficiency benefits of these approaches, they are limited in the type of interfaces they use between the host CPU and the NIC. Almost all commercially available NICs are viewed by the processor as PCIe-connected peripheral devices. Unfortunately, PCIe interconnects require multiple bus transactions, memory synchronizations, and expensive MMIO requests for every request to the NIC~\cite{rdma_1, Cambridge, stanford_mmio, NetDIMM}. As a result, the per-packet overhead in these optimized systems is still high; this is especially noticeable for fine-grained workloads with deep call paths, like microservices. This paper presents \textit{Dagger}, an FPGA-based reconfigurable RPC stack integrated into the processor's memory subsystem over a NUMA interconnect. Integrated and near-memory NICs have already shown promise in reducing the overheads of PCIe, and improving networking efficiency~\cite{NetDIMM, soNUMA, NeBuLa}. However, prior integrated NICs are based on ASICs that lack reconfigurability, and require taping out custom chips, which is expensive and time consuming for frequently-changing networking configurations at datacenter scale. Widely-used RPC stacks for microservices, such as Thrift RPC~\cite{Thrift}, gRPC~\cite{gRPC}, offer a rich variety of transport options, (de)serialization methods, and threading models. Hardware-based RPC stacks can only be practical in the context of microservices if they allow the same flexibility. To this end, we propose an \textit{integrated} and \textit{reconfigurable} FPGA-accelerated networking fabric, capable of supporting realistic and end-to-end RPC frameworks. Dagger is based on three key design principles: (1) The NIC implements the entire RPC stack in hardware, while the software is only responsible for providing the RPC API. This way, we remove CPU-related overheads from the critical path of RPC flows, and free more CPU resources for the high concurrency of microservices. (2) Dagger leverages memory interconnects to communicate with the processor. We show that in contrast to PCIe protocols that were initially designed for the Producer-Consumer dataflow pattern, memory interconnects offer a better communication model that is especially beneficial for transferring ready-to-use RPC objects. We also argue that integrating NICs via memory interconnects is more practical than previously-proposed methods of closely-coupling NICs with CPUs, since processors today come with exposed memory busses, with the next generation of server-class CPUs already offering dedicated peripheral memory interconnects~\cite{CXL}. (3) Finally, Dagger is based on an FPGA, so its design is fully programmable. This allows it to adjust to the performance and resource requirements of a given microservice. We build Dagger on an Intel Broadwell CPU/FPGA hybrid architecture, similar to those available in public clouds, such as Intel HARP. We show that offloading the entire RPC stack to hardware enables better CPU efficiency, which results in higher per-core RPC throughput and lower request latency. In addition, we demonstrate the benefits of closely-coupling hardware RPC stacks with applications through memory interconnects. Dagger improves the per-core RPC throughput up to 1.3-3.8$\times$ compared to prior work, based on both optimized software RPC frameworks~\cite{DBLP:conf/nsdi/KaliaKA19} and specialized hardware adapters~\cite{FASST}. Dagger reaches 12.4 - 16.5 Mrps of per core throughput, and it scales up to 42 Mrps with only 4 physical threads on two CPU cores, while achieving state-of-the-art $\mu$s-scale end-to-end latency. In addition, we show that Dagger can be easily integrated into existing datacenter applications with minor changes to the codebase. \new{Our experiments with memcached and MICA KVS using Dagger as the communication layer show that it achieves median and $99^{th}$ percentile tail latency of 3.2 and 7.8 us respectively for memcached and 3.5 us and 5.7 us for MICA, while also achieving a throughput of 5.2 Mrps~\cite{memcached} on a single core. This result is $11.4\times$ lower than the latency of memcached over a native transport based on the Linux kernel networking, and $4.4 - 5.2\times$ lower than of MICA over a highly-optimized, DPDK-based user space networking stack. Finally, we demonstrate that Dagger can accommodate multi-tier microservice applications with diverse requirements and threading models by porting an 8-tier Flight Registration service on top of Dagger, and showing significant performance benefits compared to native execution. } \section{Characterizing Networking in Microservices} \label{sec:network_footprint} \subsection{Networking Overheads in Microservices} We first study the network characteristics and requirements of interactive, cloud microservices. We use two end-to-end services from the DeathStarBench benchmark suite~\cite{DeathStarBench}, shown in Figures~\ref{fig:social_network} and~\ref{fig:media_service}; a Social Network, and a Media Serving application. We first profile the impact of the RPC stack on the per-tier and end-to-end latency for Social Network, for a representative subset of its microservices, shown in Figure~\ref{fig:networking_fraction}. $s1$ is a \texttt{Media} tier processing embedded images and videos in user posts, $s2$ is the \texttt{User} tier responsible for managing a user's account and interfacing with the backend storage tiers, $s3$ is the \texttt{UniqueID} tier assigning a unique identifier to a new user post, $s4$ represents the \texttt{Text} service to add text to a new post, $s5$ is the \texttt{UserMention} tier to link to another user's account in a post, and finally $s6$ corresponds to the \texttt{UrlShorten} microservice, which shortens links embedded in user posts. \begin{figure}[h] \vspace{-5pt} \centering \includegraphics[width=1\linewidth]{latency_breakdown.png} \vspace*{-5mm} \caption{Networking as a fraction of median (top) and 99th prc. tail (bottom) latency -- \normalfont{the input load increases progressively from the left-most to the right-most set of figures. The bars denote latency breakdown as recorded in the following individual microservices: s1: Media, s2: User, s3: UniqueID, s4: Text, s5: UserMention, s6: UrlShorten; e2e bar shows the breakdown for the end-to-end latency.} } \label{fig:networking_fraction} \end{figure} We break down communication overheads to RPC and TCP/IP processing, and show both median (top) and tail latency (bottom) for different load levels, from the left-most to the right-most figures. Across all tiers, communication accounts for a significant fraction of a microservice's latency, 40\% on average, and up to 80\% for the light in terms of computation \texttt{User} and \texttt{UniqueID} tiers. This also translates to a large fraction of end-to-end application latency going towards networking, despite many microservices overlapping with each other. The latency breakdown for the end-to-end application is shown in the right-most bar of each subfigure in Figure~\ref{fig:networking_fraction}; communication accounts for at least third of the median and tail end-to-end latency. RPC processing is a large part of communication, and, for some services it is even larger than the TCP/IP stack when looking at tail latency, showing that accelerating the TCP/IP layer alone is not sufficient. A couple of microservices, such as \texttt{Text} and \texttt{UserMention} are more computationally intense, and therefore, their processing time is substantially longer than the communication latency. However, since microservices typically form deep call graphs, long delays in the upstream services can cause request queueing in downstream tiers, incurring cascading QoS violations~\cite{Gan19b}. The time devoted to networking increases considerably for higher loads (right plots in Figure~\ref{fig:networking_fraction}), especially when looking at tail latency, due to excessive queueing across the networking stack. Not only does this degrade application performance, but the multiple layers of queueing in the network subsystem introduce performance unpredictability, making it hard for the application to meet its end-to-end QoS target. \new{Note that since we cannot explicitly break down the time between queueing and processing at the application layer, for high loads, e.g., QPS=800, our profiler shows high percentages for RPC processing time; most of this time corresponds to queueing. We observe that the microservice's CPU utilization does not increase proportionally with load, in part because of back pressure from the downstream services. Such aggressive queueing in the RPC layer causes significant memory pressure and high memory interference with other tasks, making tail latency even more unpredictable and high. Overall, Figure~\ref{fig:networking_fraction} shows that networking, both the RPC layer and transport, in microservices is a major performance bottleneck, especially for tiers with a small amount of compute. The results are similar for the other end-to-end services as well} \subsection{Network Characteristics of Microservices} We now analyse the network footprint of microservices. We profile the same Social Network and Media Serving applications~\cite{DeathStarBench}, and show the histogram of their RPC sizes in Figure~\ref{fig:rpc_sizes}. The workload generator follows request distributions representative of real cloud services implemented with microservices~\cite{DeathStarBench}. Specifically, the request mix includes queries for users creating new posts (\textit{Compose Post}), for reading their own timeline (\textit{Read Home Timeline}, or another user's timeline \textit{Read User Timeline}). Depending on the request type, a different subgraph of microservices is invoked~\cite{deathstarbench_github}. \begin{figure}[h] \vspace{-5pt} \centering \includegraphics[width=1\linewidth]{RPC_size_plot.pdf} \vspace*{-5mm} \caption{Distribution of RPC request and response sizes in Social Network and Media Applications (left); breakdown of RPC sizes for individual microservices (right) -- \normalfont{s1 - s6 are the same as in Figure~\ref{fig:networking_fraction} for Social Network. } } \label{fig:rpc_sizes} \end{figure} Figure~\ref{fig:rpc_sizes} (left) shows the cumulative distribution function (CDF) of RPC sizes for each end-to-end service. 75\% of all RPC requests are smaller than 512B. Responses are even more compact, with more than 90\% of packets being smaller then 64B. Commodity networking systems experience poor performance when it comes to transferring small packets due to high per-packet overheads~\cite{HOMA, DBLP:conf/nsdi/KaliaKA19}. This highlights the need for rethinking datacenter networking with the unique properties of microservices in mind. Additionally, Figure~\ref{fig:rpc_sizes} (right) shows that different microservices in the same application have very different RPC sizes. For example, the median RPC size in the \textit{Text} service is 580B, while the \textit{Media}, \textit{User}, and \textit{UniqueID} services never have RPCs larger than 64B. Such wide variation in RPC sizes across microservices shows that ``one-size-fits-all'' is a poor fit for microservice networking. Balancing between optimizing for large versus small packets is a long standing problem in networking. To achieve the best for this trade-off, Dagger employs reconfigurable hardware acceleration using FPGAs, to ensure that the networking stack can be tailored to the needs and characteristics of a given set of active microservices. \subsection{CPU Contention between Logic and Networking} The small size of microservices means that a server can concurrently host a large number of microservices, promoting resource efficiency. On the negative side, multi-tenancy also introduces resource interference, especially when CPU cores are used for both microservice logic and network processing. To quantify the resource contention between application logic and networking, we bind network interrupt service routines for each of the NIC's queues to a fixed set of N logical CPU cores ($N = 4$ in this experiment). We then run the Social Network service: (1) on the other $N$ CPU cores within the same NUMA node so that their execution does not interfere with networking, and (2) on the same $N$ cores as networking to observe the impact of interference. The resulting end-to-end request latency in each case is shown in Figure~\ref{fig:resource_contention}. \begin{figure}[h] \vspace{-5pt} \centering \includegraphics[width=1\linewidth]{contention_plot.png} \vspace*{-5mm} \caption{Impact of the CPU resource interference between networking and application logic on end-to-end tail latency -- \normalfont{solid bars show latency when network processing and application logic run on different physical cores, while shaded bars show latency when network processing and application logic threads share the same CPU cores. } } \label{fig:resource_contention} \end{figure} The experiment shows that when both application logic and network processing contend for the same CPU resources, end-to-end latency (both median and tail) suffers. As expected, interference becomes worse as the system load increases, especially when it comes to tail latency, which is more sensitive to performance unpredictability. Note that in addition to the network interrupt handling layer, RPC processing also interferes with application processing. Since the RPC stack is technically a part of the application logic in the service's default implementation, we are not able to isolate its impact; however, the high resource contention of Figure~\ref{fig:resource_contention} already justifies the need for offloading the networking stack from the host processor. Dedicating, alternatively, cores specifically for network processing is not resource efficient, since network load fluctuates over time, dedicated networking cores are still prone to CPU-related overheads, and they can introduce interference in the last level cache (LLC) and main memory subsystems. This analysis highlights three unique requirements for networking systems aimed at microservice deployments. First, RPC processing should be offloaded to dedicated hardware, to avoid CPU-related overheads and interference with the application logic. Second, systems should be optimized for small requests/responses, which dominate the network traffic of microservices. Finally, communication frameworks should be programmable to handle the diverse needs of microservices, and adjust to their frequent changes. \section{Related Work} \label{sec:related} Designing low-latency networking systems including optimizations for small requests is not a new problem. Both industry and academia have contributed various proposals to this end. In this section, we briefly review prior work on networking acceleration, and discuss how it resembles and differs from our proposal. We classify related work into three categories: (1) software solutions, (2) systems leveraging specialized commercial hardware adapters, and (3) proposals of new hardware architectures for efficient networking. \vspace{0.05in} \noindent{\bf{Software-based solutions: }} At the software level, most research has focused on transport protocol optimizations for low latency and/or high throughput~\cite{DCTCP, mTCP, HOMA, pFABRIC, RestructuringCC}. This includes optimizing the congestion control mechanisms, flow scheduling, connection management, etc. In addition to transport optimizations, some proposals also suggest moving networking from the kernel to user space by leveraging, for example, DPDK~\cite{DPDK, HOMA, mTCP, IX, TAS} or raw NIC driver APIs~\cite{DBLP:conf/nsdi/KaliaKA19}. Although these proposals demonstrate their efficiency in improving the performance of datacenter networks, they are still subject to system overheads due to their software-only and CPU-based implementation. \vspace{0.05in} \noindent{\bf{Specialized commercial adapters:}} As an alternative to software/ algorithmic-only optimizations, another line of work proposed to leverage RDMA hardware to offload network processing to specialized adapters, and use the remote memory abstraction to implement higher-level communication primitives, such as RPCs~\cite{FARM, FASST, DaRPC}. This approach improves CPU efficiency, and as a consequence also incurs lower latency and higher throughput. Despite this, there are two main issues with existing RDMA-related work. First, prior work does not implement a fully-offloaded RPC protocol; commodity RDMA adapters only offload the networking part, i.e., up to the transport layer and RDMA protocols, keeping the execution of RPC layers on the host CPU. Second, all RDMA NICs are seen as peripheral devices from the perspective of the host CPUs, and are interconnected with the latter over PCIe busses that have been shown to be inefficient, especially when the metric of interest is latency and network packets are small~\cite{rdma_1, stanford_mmio, Cambridge}. Therefore, bringing NICs closer to CPUs and/or memory is required to enable efficient and fast communication in datacenters. \begin{figure}[h] \centering \includegraphics[width=0.46\textwidth]{social_network.pdf} \caption{\new{Social Network microservice architecture~\cite{DeathStarBench} -- \normalfont{client requests first reach a front-end load balancer, which evenly distributes them across the $N$ webserver instances. Then, depending on the type of user request, mid-tiers will be invoked to create a post, read a user's timeline, follow/unfollow users, or receive recommendations on new users to follow. At the right-most of the figure, the requests reach the back-end databases, implemented both with in-memory caching tiers (memcached/Redis), and persistent databases (MongoDB). }}} \label{fig:social_network} \end{figure} \vspace{-5pt} \begin{figure}[h] \centering \includegraphics[width=0.46\textwidth]{media_service.pdf} \caption{\new{Media Serving microservice architecture~\cite{DeathStarBench} -- \normalfont{client requests first reach a front-end load balancer, which evenly distributes them across the $N$ webserver instances. Then, depending on the type of user request, mid-tiers will be invoked to browse information about a movie, create a new movie review, or get recommendations on movies a user may enjoy. At the right-most of the figure, the requests reach the back-end databases, implemented both with in-memory caching tiers (memcached and Redis), and persistent databases (MongoDB). }}} \label{fig:media_service} \end{figure} \noindent{\bf{Integrated special-purpose networking hardware:}} To address the aforementioned issues, a recent line of research proposed to tightly integrate NICs with the processor and memory. In particular, NetDIMM~\cite{NetDIMM} investigates the potential of physical integration of NICs into DIMM memory hardware. However, NetDIMM does not focus on RPC stacks, and it requires designing custom ASICs inside the DIMM hardware, which is hard to achieve at scale in a short term. Another solution to this end is soNUMA~\cite{soNUMA}, which proposes to scale-out coherent NUMA memory interconnects at the datacenter level, therefore bringing cluster machines closer to each other. NeBuLa~\cite{NeBuLa} similarly discusses the implementation of a hardware-offloaded RPC stack on top of soNUMA. NeBuLa introduces a novel mechanism for delivering RPC payloads directly into a processor's L1 cache, and also proposes an efficient in-LLC buffer management and load balancing method that reduces network queueing, and improves the tail latency of RPC requests. However, as with NetDIMM, both NeBuLa and soNUMA require fabrication of custom hardware that is physically integrated with the processor and memory subsystem, and reorganizing the entire datacenter network architecture, which is challenging to achieve at datacenter scale, especially given the frequent design and deployment changes of microservices. Another closely-related work, Optimus Prime~\cite{OptimusPrime}, presents the design of an RPC data transformation accelerator which reduces the CPU pressure from expensive (de)serialization operations common in datacenter communication systems. At a high level, Dagger implements an RPC stack, fully offloaded to hardware. The FPGA-based design makes it amenable to the frequent updates present in microservices, and customizable to their diverse needs. In addition, Dagger leverages commercially-available memory interconnects as the interface between the processor and the \textit{Ethernet} NIC, so, in contrast to previous solutions requiring custom hardware and/or specifically designed datacenter networks, our proposed system can be integrated into existing cloud infrastructures without the need for chip tapeouts. We also demonstrate that third party applications, such as memcached can be easily ported to Dagger, with minimal changes to the their codebase. \new{Even though Dagger's implementation is based on an FPGA, it is fundamentally different from other FPGA/SmartNIC-related proposals~\cite{msft, NICA, Floem, TONIC} and industrial NICs. All existing networking devices are either ``Smart'' in the way they process packets but remain PCIe-attached, or are more closely-integrated to the main CPU but not programmable, only implementing simple packet delivery functionality. From this perspective, Dagger is the first attempt to leverage FPGAs which are \textit{closely-coupled} with processors over memory interconnects as \textit{programmable networking devices} to implement the networking stack all the way up to the application layer (RPCs). This new approach opens up many system challenges and opportunities to customize networking fabrics to the frequently-evolving interactive cloud services, in a high-performance and efficient manner. In addition, our proposal comes with out-of-the-box support for multi tenancy and co-location. We show how a single physical FPGA adapter can host multiple independent NICs serving different tenants running on the same host. }
{'timestamp': '2021-06-04T02:05:36', 'yymm': '2106', 'arxiv_id': '2106.01482', 'language': 'en', 'url': 'https://arxiv.org/abs/2106.01482'}
arxiv
\section{Introduction} Since its proposal by \citet{bahdanau_neural_2015}, so-called neural attention has become the backbone of many state-of-the-art deep learning models. This is true in particular in natural language processing (NLP), where the Transformer model of \citet{vaswani_attention_2017} has become ubiquitous. This ubiquity is such that much of the last few years' NLP breakthroughs have been due to developing new training regimes for Transformers \citep[etc.]{radford_language_2018,devlin_bert_2019,yang_xlnet_2019,liu_roberta_2019,wang_glue_2019,joshi_spanbert_2020,lan_albert_2020,brown_language_2020}. Like most modern deep neural networks, theoretical understanding of the Transformer has lagged behind the rate of Transformer-based performance improvements on AI tasks like NLP. Recently, several authors have noted Transformer operations' relationship to other, better-understood topics in deep learning theory, like the similarities between attention and convolution \citep{ramachandran_stand-alone_2019,cordonnier_relationship_2020} and the design of the residual blocks in multi-layer Transformers (e.g., \citet{lu_understanding_2019}; see also the reordering of the main learned (fully-connected or attentional) operation, elementwise nonlinearity, and normalization in the original Transformer authors' official reference codebase \citep{vaswani_tensor2tensor_2018} and in some more recent studies of deeper Transformers \citep{wang_learning_2019-1} to the ``pre-norm'' ordering of normalize, learned operation, nonlinearity, add residual ordering of modern (``v2'') Resnets \citep{he_identity_2016}). In this paper, we propose a new lens to understand the central component of the Transformer, its ``dot-product attention'' operation. In particular, we show dot-product attention can be characterized as a particular class of kernel method \citep{scholkopf_learning_2002}. More specifically, it is a so-called \emph{indefinite} and \emph{asymmetric} kernel method, which refer to two separate generalizations of the classic class of kernels that does not require the classic assumptions of symmetry and positive (semi-) definiteness \citep[etc.]{ong_learning_2004,balcan_theory_2008,zhang_reproducing_2009,wu_asymmetric_2010,loosli_learning_2016,oglic_learning_2018,oglic_scalable_2019}. We in fact show in Theorem \ref{th:approx} below that dot-product attention can learn any asymmetric indefinite kernel. This insight has several interesting implications. Most immediately, it provides some theoretical justification for one of the more mysterious components of the Transformer model. It also potentially opens the door for the application of decades of classic kernel method theory towards understanding one of today's most important neural network models, perhaps similarly to how tools from digital signal processing are widely used to study convolutional neural networks. We make a first step on this last point in this paper, proposing a generalization of prior kernel methods we call ``binary'' kernel machines, that learns how to predict distinct values for pairs of elements across two input sets, similar to an attention model. The remainder of this paper is organized as follows. Section \ref{sec:background} reviews the mathematical background of both Transformers and classic kernel methods. Section \ref{sec:rkbs_def} presents the definition of kernel machines on reproducing kernel Banach spaces (RKBS's) that we use to characterize Transformers. In particular we note that the Transformer can be described as having an infinite-dimensional feature space. Section \ref{sec:characterization} begins our theoretical results, explicitly describing the Transformer in terms of reproducing kernels, including explicit formulations of the Transformer's kernel feature maps and its relation to prior kernels. Section \ref{sec:learner} discusses Transformers as kernel learners, including a new representer theorem and a characterization of stochastic-gradient-descent-trained attention networks as approximate kernel learners. In Section \ref{sec:more_kernels}, we present empirical evidence that the infinite-dimensional character of the Transformer kernel may be somewhat responsible for the model's effectiveness. Section \ref{sec:conclusion} concludes and summarizes our work. \section{Background and Related Work} \label{sec:background} \subsection{Transformer Neural Network Models} The Transformer model \citep{vaswani_attention_2017} has become ubiquitous in many core AI applications like natural language processing. Here, we review its core components. Say we have two ordered sets of vectors, a set of ``source'' elements $\{{\bm{s}}_1, {\bm{s}}_2, \dots, {\bm{s}}_{S}\}$, ${\bm{s}}_j \in \mathbb{R}^{d_s}$ and a set of ``target'' elements $\{{\bm{t}}_1, {\bm{t}}_2, \dots, {\bm{t}}_{T}\}$, ${\bm{t}}_i \in \mathbb{R}^{d_t}$. In its most general form, the neural-network ``attention'' operation that forms the backbone of the Transformer model is to compute, for each ${\bm{t}}_i$, a ${\bm{t}}_i$-specific embedding of the source sequence $\{{\bm{s}}_j\}_{j=1}^S$.\footnote{ Often, the source and target sets are taken to be the same, ${\bm{s}}_i={\bm{t}}_i \; \forall i$. This instance of attention is called self attention.} The particular function used in the Transformer is the so-called ``scaled dot-product'' attention, which takes the form \begin{align} \begin{gathered} \label{eq:scaleddotproduct_attn} a_{ij} = \frac{({\bm{W}}^Q {\bm{t}}_i)^\mathsf{T} ({\bm{W}}^K {\bm{s}}_j)}{\sqrt{d}} \qquad \alpha_{ij} = \frac{\exp(a_{ij})}{\sum_{j=1}^{S} \exp(a_{ij})} \qquad {\bm{t}}'_i = \sum_{j=1}^S \alpha_{ij} {\bm{W}}^V {\bm{s}}_j \end{gathered} \end{align} where ${\bm{W}}^V, {\bm{W}}^K \in \mathbb{R}^{d_s \times d}$, and ${\bm{W}}^Q \in \mathbb{R}^{d_t \times d}$ are learnable weight matrices, usually called the ``value,'' ``key,'' and ``query'' weight matrices, respectively. Usually multiple so-called ``attention heads'' with independent parameter matrices implement several parallel computations of \eqref{eq:scaleddotproduct_attn}, with the Cartesian product (vector concatenation) of several $d$-dimensional head outputs forming the final output ${\bm{t}}_i'$. Usually the unnormalized $a_{ij}$'s are called attention scores or attention logits, and the normalized $\alpha_{ij}$'s are called attention weights. In this paper, we restrict our focus to the dot-product formulation of attention shown in \eqref{eq:scaleddotproduct_attn}. Several other alternative forms of attention that perform roughly the same function (i.e., mapping from $\mathbb{R}^{d_s} \times \mathbb{R}^{d_t}$ to $\mathbb{R}$) have been proposed \citep[etc.]{bahdanau_neural_2015,luong_effective_2015,velickovic_graph_2018,battaglia_relational_2018} but the dot-product formulation of the Transformer is by far the most popular. \subsection{Kernel Methods and Generalizations of Kernels} Kernel methods \citep[etc.]{scholkopf_learning_2002,steinwart_support_2008} are a classic and powerful class of machine learning methods. The key component of kernel methods are the namesake \emph{kernel functions}, which allow the efficient mapping of input data from a low-dimensional data domain, where linear solutions to problems like classification or regression may not be possible, to a high- or infinite-dimensional embedding domain, where linear solutions can be found. Given two nonempty sets ${\mathcal{X}}$ and ${\mathcal{Y}}$, a kernel function $\kappa$ is a continuous function $\kappa: {\mathcal{X}} \times {\mathcal{Y}} \to \mathbb{R}$. In the next few sections, we will review the classic symmetric and positive (semi-) definite, or Mercer, kernels, then discuss more general forms. \subsubsection{Symmetric and Positive Semidefinite (Mercer) kernels} If ${\mathcal{X}}={\mathcal{Y}}$, and for all $x_i, x_j \in {\mathcal{X}}={\mathcal{Y}}$, a particular kernel $\kappa$ has the properties \begin{subequations} \label{eq:mercer} \begin{gather} \kappa(x_i, x_j) = \kappa(x_j, x_i) \label{eq:symmetry} \\ {\bm{c}}^\mathsf{T} {\bm{K}} {\bm{c}} \geq 0 \quad \forall \; {\bm{c}} \in \mathbb{R}^n; \quad i,j = 1, \dots, n; \quad n \in {\mathbb{N}} \label{eq:psd} \end{gather} \end{subequations} where ${\bm{K}}$ in \eqref{eq:psd} is the Gram matrix, defined as ${K}_{ij} = \kappa(x_i, x_j)$, then $\kappa$ is said to be a Mercer kernel. Property \eqref{eq:symmetry} is a symmetry requirement, and \eqref{eq:psd} is a condition of positive (semi-) definiteness. For Mercer kernels, it is well-known that, among other facts, (i) we can define a Hilbert space of functions on ${\mathcal{X}}$, denoted $\H_\kappa$ (called the reproducing kernel Hilbert space, or RKHS, associated with the reproducing kernel $\kappa$), (ii) $\H_\kappa$ has for each $x$ a (continuous) unique element $\delta_x$ called a point evaluation functional, with the property $f(x) = \delta_x(f) \; \forall f \in \H_\kappa$, (iii) $\kappa$ has the so-called \emph{reproducing property}, $\langle f, \kappa(x, \cdot) \rangle_{\H_\kappa} = f(x) \; \forall f \in \H_\kappa$, where $\langle \cdot, \cdot \rangle_{\H_\kappa}$ is the inner product on $\H_\kappa$, and (iv) we can define a ``feature map'' $\Phi: {\mathcal{X}} \to {\mathcal{F}}_\H$, where ${\mathcal{F}}_\H$ is another Hilbert space sometimes called the feature space, and $\kappa(x, y) = \langle \Phi(x), \Phi(y) \rangle_{{\mathcal{F}}_\H}$ (where $\langle \cdot, \cdot \rangle_{{\mathcal{F}}_\H}$ is the inner product associated with ${\mathcal{F}}_\H$). This last point gives rise to the kernel trick for RKHS's. From a machine learning and optimization perspective, kernels that are symmetric and positive (semi-) definite (PSD) are desirable because those properties guarantee that empirical-risk-minimization kernel learning problems like support vector machines (SVMs), Gaussian processes, etc. are convex. Convexity gives appealing guarantees for the tractability of a learning problem and optimality of solutions. \subsubsection{Learning with non-Mercer kernels} Learning methods with non-Mercer kernels, or kernels that relax the assumptions \eqref{eq:mercer}, have been studied for some time. One line of work \citep[etc.]{lin_study_2003,ong_learning_2004,chen_training_2008,luss_support_2008,alabdulmohsin_support_2015,loosli_learning_2016,oglic_learning_2018,oglic_scalable_2019} has focused on learning with symmetric but indefinite kernels, i.e., kernels that do not satisfy \eqref{eq:psd}. Indefinite kernels have been identified as reproducing kernels for so-called reproducing kernel Kre\u{\i}n spaces (RKKS's) since \citet{schwartz_sous-espaces_1964} and \citet{alpay_remarks_1991}. Replacing a Mercer kernel in a learning problem like an SVM with an indefinite kernel makes the optimization problem nonconvex in general (as the kernel Gram matrix ${\bm{K}}$ is no longer always PSD). Some early work in learning with indefinite kernels tried to ameliorate this problem by modifying the spectrum of the Gram matrix such that it again becomes PSD \citep[e.g.,][]{graepel_classification_1998,roth_optimal_2003,wu_analysis_2005}. More recently, \citet{loosli_learning_2016,oglic_learning_2018}, among others, have proposed optimization procedures to learn in the RKKS directly. They report better performance on some learning problems when using indefinite kernels than either popular Mercer kernels or spectrally-modified indefinite kernels, suggesting that sacrificing convexity can empirically give a performance boost. This conclusion is of course reminiscent of the concurrent experience of deep neural networks, which are hard to optimize due to their high degree of non-convexity, yet give superior performance to many other methods. Another line of work has explored the application of kernel methods to learning in more general Banach spaces, i.e., reproducing kernel Banach spaces (RKBS's) \citep{zhang_reproducing_2009}. Various constructions to serve as the reproducing kernel for a Banach space (replacing the inner product of an RKHS) have been proposed, including semi-inner products \citep{zhang_reproducing_2009}, positive-definite bilinear forms via a Fourier transform construction \citep{fasshauer_solving_2015}, and others \citep[etc.]{song_reproducing_2013,georgiev_construction_2014}. In this work, we consider RKBS's whose kernels may be neither symmetric nor PSD. A definition of these spaces is presented next. \section{General reproducing kernel Banach spaces} \label{sec:rkbs_def} Recently, \citet{georgiev_construction_2014}, \citet{lin_reproducing_2019}, and \citet{xu_generalized_2019} proposed similar definitions and constructions of RKBS's and their reproducing kernels meant to encompass prior definitions. In this paper, we adopt a fusion of the definitions and attempt to keep the notation as simple as possible to be sufficient for our purposes. \begin{definition}[\textbf{Reproducing kernel Banach space} ({\citealp[Definition 2.1]{xu_generalized_2019}; \citealp[Definitions 1.1 \& 1.2]{lin_reproducing_2019}; \citealp{georgiev_construction_2014}})] \label{def:rkbs} \label{def:rkbs_xuye} Let ${\mathcal{X}}$ and ${\mathcal{Y}}$ be nonempty sets, $\kappa$ a measurable function called a kernel, $\kappa: {\mathcal{X}} \times {\mathcal{Y}} \to \mathbb{R}$, and ${\mathcal{B}}_{\mathcal{X}}$ and ${\mathcal{B}}_{\mathcal{Y}}$ Banach spaces of real measurable functions on ${\mathcal{X}}$ and ${\mathcal{Y}}$, respectively. Let $\Bmap{\cdot}{\cdot}: {\mathcal{B}}_{\mathcal{X}} \times {\mathcal{B}}_{\mathcal{Y}} \to \mathbb{R}$ be a nondegenerate bilinear mapping such that \begin{subequations} \label{eq:kernel_def} \begin{alignat}{2} &\kappa(x, \cdot) \in {\mathcal{B}}_{\mathcal{Y}} && \forall \; x \in {\mathcal{X}}; \label{eq:fix_x} \\ &\Bmap{f}{\kappa(x, \cdot)} = f(x) \quad && \forall \; x \in {\mathcal{X}}, f \in {\mathcal{B}}_{\mathcal{X}}; \label{eq:repr1} \\ &\kappa(\cdot, y) \in {\mathcal{B}}_{\mathcal{X}} && \forall \; y \in {\mathcal{Y}}; \textnormal{ and} \label{eq:fix_y} \\ &\Bmap{\kappa(\cdot, y)}{g} = g(y) && \forall \; y \in {\mathcal{Y}}, g \in {\mathcal{B}}_{\mathcal{Y}}. \label{eq:repr2} \end{alignat} \end{subequations} Then, ${\mathcal{B}}_{\mathcal{X}}$ and ${\mathcal{B}}_{\mathcal{Y}}$ are a pair of reproducing kernel Banach spaces (RKBS's) on ${\mathcal{X}}$ and ${\mathcal{Y}}$, respectively, and $\kappa$ is their reproducing kernel. \end{definition} Line \eqref{eq:fix_x} (resp. \eqref{eq:fix_y}) says that, if we take $\kappa$, a function of two variables $x \in {\mathcal{X}}$ and $y \in {\mathcal{Y}}$, and fix $x$ (resp. $y$), then we get a function of one variable. This function of one variable must be an element of ${\mathcal{B}}_{\mathcal{Y}}$ (resp. ${\mathcal{B}}_{\mathcal{X}}$). Lines \eqref{eq:repr1} and \eqref{eq:repr2} are the \emph{reproducing properties} of $\kappa$. For our purposes, it will be useful to extend this definition to include a ``feature map'' characterization similar to the one used in some explanations of RKHS's \citep[Chapter 2]{scholkopf_learning_2002}. \begin{definition}[\textbf{Feature maps for RKBS's} ({\citealp[Theorem 2.1]{lin_reproducing_2019}; \citealp{georgiev_construction_2014}})] \label{def:featuremaps} For a pair of RKBS's as defined in Definition \ref{def:rkbs}, suppose that there exist mappings $\Phi_{\mathcal{X}}: {\mathcal{X}} \to {\mathcal{F}}_{\mathcal{X}}, \Phi_{\mathcal{Y}}: {\mathcal{Y}} \to {\mathcal{F}}_{\mathcal{Y}}$, where ${\mathcal{F}}_{\mathcal{X}}$ and ${\mathcal{F}}_{\mathcal{Y}}$ are Banach spaces we will call the feature spaces, and a nondegenerate bilinear mapping $\Fmap{\cdot}{\cdot}: {\mathcal{F}}_{\mathcal{X}} \times {\mathcal{F}}_{\mathcal{Y}} \to \mathbb{R}$ such that \begin{equation} \kappa(x, y) = \Fmap{\Phi_{\mathcal{X}}(x)}{\Phi_{\mathcal{Y}}(y)} \; \forall \; x \in {\mathcal{X}}, y \in {\mathcal{Y}}. \label{eq:kernel} \end{equation} In this case, the spaces ${\mathcal{B}}_{\mathcal{X}}$ and ${\mathcal{B}}_{\mathcal{Y}}$ can be defined as \citep{xu_generalized_2019,lin_reproducing_2019} \begin{subequations} \label{eq:banach_spaces} \begin{align} {\mathcal{B}}_{\mathcal{X}} &= \left\{ f_v: {\mathcal{X}} \to \mathbb{R}: f_v(x) \triangleq \Fmap{\Phi_{\mathcal{X}}(x)}{v} \; ; v \in {\mathcal{F}}_{\mathcal{Y}}, x \in {\mathcal{X}} \right\} \label{eq:banach_spaces_x} \\ {\mathcal{B}}_{\mathcal{Y}} &= \left\{ g_u: {\mathcal{Y}} \to \mathbb{R}: g_u(y) \triangleq \Fmap{u}{\Phi_{\mathcal{Y}}(y)} \; ; u \in {\mathcal{F}}_{\mathcal{X}}, y \in {\mathcal{Y}} \right\}. \label{eq:banach_spaces_y} \end{align} \end{subequations} \end{definition} \begin{remark} \label{rem:manifolds} We briefly discuss how to understand the spaces given by \eqref{eq:banach_spaces}. Consider \eqref{eq:banach_spaces_x} for example. It is a space of real-valued functions of one variable $x$, where the function is also parameterized by a $v$. Picking a $v \in {\mathcal{F}}_{\mathcal{Y}}$ in \eqref{eq:banach_spaces_x} defines a manifold of functions in ${\mathcal{B}}_{\mathcal{X}}$. This manifold of functions with fixed $v$ varies with the function $\Phi_{\mathcal{X}}$. Evaluating a function $f_v$ in this manifold at a point $x$ is defined by taking the bilinear product of $\Phi_{\mathcal{X}}(x)$ and the chosen $v$. This also means that we can combine \eqref{eq:kernel} and \eqref{eq:banach_spaces} to say \begin{equation} \kappa(x, y) = \Fmap{\Phi_{\mathcal{X}}(x)}{\Phi_{\mathcal{Y}}(y)} = \Bmap{f_{\Phi_{\mathcal{X}}(x)}}{g_{\Phi_{\mathcal{Y}}(y)}} \quad \text{for all } x \in {\mathcal{X}}, y \in {\mathcal{Y}}. \label{eq:kernel_identity} \end{equation} for all $x \in {\mathcal{X}}$ and $y \in {\mathcal{Y}}$. \end{remark} \begin{remark} If $\Phi_{\mathcal{X}}(x)$ and $\Phi_{\mathcal{Y}}(y)$ can be represented as countable sets of real-valued measurable functions, $\{\phi_{\mathcal{X}}(x)_\ell\}_{\ell \in {\mathbb{N}}}$ and $\{\phi_{\mathcal{Y}}(y)_\ell\}_{\ell \in {\mathbb{N}}}$ for $(\phi_{{\mathcal{X}}})_\ell: {\mathcal{X}} \to \mathbb{R}$ and $(\phi_{{\mathcal{Y}}})_\ell: {\mathcal{Y}} \to \mathbb{R}$ (i.e., ${\mathcal{F}}_{\mathcal{X}}, {\mathcal{F}}_{\mathcal{Y}} \subset \prod_{\ell \in {\mathbb{N}}} \mathbb{R}$); and $\Fmap{{\bm{u}}}{{\bm{v}}} = \sum_{\ell \in {\mathbb{N}}} {u}_\ell {v}_\ell$ for ${\bm{u}} \in {\mathcal{F}}_{\mathcal{X}}, {\bm{v}} \in {\mathcal{F}}_{\mathcal{Y}}$; then the ``feature map'' construction, whose notation we borrow from \citet{lin_reproducing_2019}, corresponds to the ``generalized Mercer kernels'' of \citet{xu_generalized_2019}. \end{remark} \section{Dot-Product Attention as an RKBS Kernel} \label{sec:characterization} We now formally state the formulation for dot-product attention as an RKBS learner. Much like with RKHS's, for a given kernel and its associated RKBS pair, the feature maps (and also the bilinear mapping) are not unique. In the following, we present a feature map based on classic characterizations of other kernels such as RBF kernels (e.g., \citet{steinwart_explicit_2006}). \begin{proposition} \label{prop:rkbs} The (scaled) dot-product attention calculation of \eqref{eq:scaleddotproduct_attn} is a reproducing kernel for an RKBS in the sense of Definitions \ref{def:rkbs} and \ref{def:featuremaps}, with the input sets ${\mathcal{X}}$ and ${\mathcal{Y}}$ being the vector spaces from which the target elements $\{{\bm{t}}_i\}_{i=1}^T, {\bm{t}}_i \in \mathbb{R}^{d_t}$ and source elements $\{{\bm{s}}_j\}_{j=1}^S, {\bm{s}}_j \in \mathbb{R}^{d_s}$ are drawn, respectively; the feature maps \begin{subequations} \label{eq:transformer_feature_maps} \begin{align} \Phi_{\mathcal{X}}({\bm{t}}) &= \sum_{n=0}^\infty \: \sum_{p_1 + \cdots + p_d = n} \! \frac{ \sqrt{ \frac{n!}{p_1! \cdots p_d!} } \prod_{\ell=1}^d ({q}_\ell)^{p_\ell} }{d^{\nicefrac{1}{4}}} \label{eq:transformer_feature_map_x} \\ \Phi_{\mathcal{Y}}({\bm{s}}) &= \sum_{n=0}^\infty \: \sum_{p_1 + \cdots + p_d = n} \! \frac{ \sqrt{ \frac{n!}{p_1! \cdots p_d!} } \prod_{\ell=1}^d ({k}_\ell)^{p_\ell} }{d^{\nicefrac{1}{4}}} \label{eq:transformer_feature_map_y} \end{align} \end{subequations} where ${q}_\ell$ is the $\ell$th element of ${\bm{q}} = {\bm{W}}^Q {\bm{t}}$, ${k}_\ell$ is the $\ell$th element of ${\bm{k}} = {\bm{W}}^K {\bm{s}}$, ${\bm{W}}^Q \in \mathbb{R}^{d \times d_t}$ ${\bm{W}}^K \in \mathbb{R}^{d \times d_s}$, with $d \leq d_s, d_t$ and $\rank({\bm{W}}^Q) = \rank({\bm{W}}^K) = d$; the bilinear mapping $\Fmap{\Phi_{\mathcal{X}}({\bm{t}})}{\Phi_{\mathcal{Y}}({\bm{s}})} = \Phi_{\mathcal{X}}({\bm{t}}) \cdot \Phi_{\mathcal{Y}}({\bm{s}})$; and the Banach spaces \begin{subequations} \label{eq:transformer_banach_spaces} \begin{align} {\mathcal{B}}_{\mathcal{X}} &= \left\{ f_{\bm{k}}({\bm{t}}) = \exp \left( ( {\bm{W}}^Q {\bm{t}})^\mathsf{T} {\bm{k}} / \sqrt{d} \right) \; ; \; {\bm{k}} \in {\mathcal{F}}_{\mathcal{Y}}, {\bm{t}} \in {\mathcal{X}} \right\} \label{eq:transformer_banach_x} \\ {\mathcal{B}}_{\mathcal{Y}} &= \left\{ g_{{\bm{q}}} ({\bm{s}}) = \exp \left( {\bm{q}}^\mathsf{T} ({\bm{W}}^K {\bm{s}}) / \sqrt{d} \right) \; ; \; {\bm{q}} \in {\mathcal{F}}_{\mathcal{X}}, {\bm{s}} \in {\mathcal{Y}} \right\} \label{eq:transformer_banach_y} \end{align} \end{subequations} with the ``exponentiated query-key kernel,'' \begin{equation} \kappa({\bm{t}}, {\bm{s}}) = \Fmap{\Phi_{\mathcal{X}}({\bm{t}})}{\Phi_{\mathcal{Y}}({\bm{s}})} = \Bmap{f_{\Phi_{\mathcal{Y}}({\bm{s}})}}{g_{\Phi_{\mathcal{X}}({\bm{t}})}} = \exp \left( \frac{({\bm{W}}^Q {\bm{t}})^\mathsf{T} ({\bm{W}}^K {\bm{s}})}{\sqrt{d}} \right) \label{eq:transformer_kernel} \end{equation} the associated reproducing kernel. \end{proposition} The proof of Proposition \ref{prop:rkbs} is straightforward and involves verifying \eqref{eq:transformer_kernel} by multiplying the two infinite series in \eqref{eq:transformer_feature_maps}, then using the multinomial theorem and the Taylor expansion of the exponential. In the above and when referring to Transformer-type models in particular rather than RKBS's in general, we use ${\bm{t}}, {\bm{s}}, {\bm{q}}$, and ${\bm{k}}$ for $x, y, u$, and $v$, respectively, to draw the connection between the elements of the RKBS's and the widely-used terms ``target,'' ``source,'' ``query,'' and ``key.'' The rank requirements on ${\bm{W}}^Q$ and ${\bm{W}}^K$ mean that $\overline{\spn}(\{\Phi_{\mathcal{X}}({\bm{t}}), {\bm{t}} \in {\mathcal{X}}\}) = {\mathcal{F}}_{\mathcal{X}}$ and $\overline{\spn}(\{\Phi_{\mathcal{Y}}({\bm{s}}), {\bm{s}} \in {\mathcal{Y}}\}) = {\mathcal{F}}_{\mathcal{Y}}$. This in turn means that the bilinear mapping is nondegenerate. \begin{remark} Now that we have an example of a pair of RKBS's, we can make more concrete some of the discussion from Remark \ref{rem:manifolds}. Examining \eqref{eq:transformer_banach_x}, for example, we see that when we select a ${\bm{k}} \in {\mathcal{F}}_{\mathcal{Y}}$, we define a manifold of functions in ${\mathcal{B}}_{\mathcal{X}}$ where ${\bm{k}}$ is fixed, but ${\bm{W}}^Q$ can vary. Similarly, selecting a ${\bm{q}} \in {\mathcal{F}}_{\mathcal{X}}$ defines a manifold in ${\mathcal{B}}_{\mathcal{Y}}$. Selecting an element from both ${\mathcal{F}}_{\mathcal{X}}$ and ${\mathcal{F}}_{\mathcal{Y}}$ locks us into one element each from ${\mathcal{B}}_{\mathcal{X}}$ and ${\mathcal{B}}_{\mathcal{Y}}$, which leads to the equality in \eqref{eq:kernel_identity}. \end{remark} \begin{remark} Examining \eqref{eq:transformer_banach_spaces}-\eqref{eq:transformer_kernel}, we can see that the element drawn from ${\mathcal{F}}_{\mathcal{Y}}$ that parameterizes the element of ${\mathcal{B}}_{\mathcal{X}}$, as shown in \eqref{eq:transformer_banach_x}, is a function of $\Phi_{\mathcal{Y}}$ (and vice-versa for \eqref{eq:transformer_banach_y}). This reveals the exact mechanism in which the Transformer-type attention computation is a generalization of the RKBS's considered by \citet{fasshauer_solving_2015}, \citet{lin_reproducing_2019}, \citet{xu_generalized_2019}, etc., for applications like SVMs, where one of these function spaces is considered fixed. \end{remark} \begin{remark} Since the feature maps define the Banach spaces \eqref{eq:banach_spaces}, the fact that the parameters ${\bm{W}}^Q$ and ${\bm{W}}^K$ are learned implies that Transformers learn parametric representations of the RKBS's themselves. This is in contrast to classic kernel methods, where the kernel (and thus the reproducing space) is usually fixed. In fact, in Theorem \ref{th:approx} below, we show that (a variant of) the Transformer architecture can approximate any RKBS mapping. \end{remark} \begin{remark} The symmetric version of the exponentiated dot product kernel is known to be a reproducing kernel for the so-called Bargmann space \citep{bargmann_hilbert_1961} which arises in quantum mechanics. \end{remark} \begin{remark} Notable in Proposition \ref{prop:rkbs} is that we define the kernel of dot-product attention as including the exponential of the softmax operation. The output of this operation is therefore not the attention scores $a_{ij}$ but rather the unnormalized attention weights, $\bar{\alpha}_{ij} = \alpha_{ij} \sum_j \alpha_{ij}$. Considering the exponential as a part of the kernel operation reveals that the feature spaces for the Transformer are in fact infinite-dimensional in the same sense that the RBF kernel is said to have an infinite-dimensional feature space. In Section \ref{sec:more_kernels}, we find empirical evidence that this infinite dimensionality may be partially responsible for the Transformer's effectiveness. \end{remark} \section{Transformers as kernel learners} \label{sec:learner} \subsection{The binary RKBS learning problem and its representer theorem} Most kernel learning problems take the form of empirical risk minimization problems. For example, if we had a learning problem for a finite dataset $(x_1, z_1), \dots, (x_n, z_n), x_i \in {\mathcal{X}}, z_i \in \mathbb{R}$ and wanted to learn a function $f: {\mathcal{X}} \to \mathbb{R}$ in an RKHS $\H_\kappa$, the learning problem might be written as \begin{equation} f^* = \argmin_{f \in \H_\kappa} \frac{1}{n} \sum_{i=1}^n L \left(x_i, z_i, f(x_i)\right) + \lambda R(\|f\|_{\H_\kappa}) \label{eq:rkhs_learner} \end{equation} where $L: {\mathcal{X}} \times \mathbb{R} \times \mathbb{R} \to \mathbb{R}$ is a convex loss function, $R: [0, \infty) \to \mathbb{R}$ is a strictly increasing regularization function, and $\lambda$ is a scaling constant. Recent references that consider learning in RKBS's \citep{georgiev_construction_2014,fasshauer_solving_2015,lin_reproducing_2019,xu_generalized_2019} consider similar problems to \eqref{eq:rkhs_learner}, but with the RKHS $\H$ replaced with an RKBS. The kernel learning problem for attention, however, is different from \eqref{eq:rkhs_learner} in that, as we discussed in the previous section, we need to predict a response $z_{ij}$ (i.e., the attention logit) for every pair $({\bm{t}}_i, {\bm{s}}_j)$. This motivates a generalization of the classic class of kernel learning problems that operates on pairs of input spaces. We discuss this generalization now. \begin{definition}[Binary kernel learning problem - regularized empirical risk minimization] \label{def:binary_kernel} Let ${\mathcal{X}}$ and ${\mathcal{Y}}$ be nonempty sets, and ${\mathcal{B}}_{\mathcal{X}}$ and ${\mathcal{B}}_{\mathcal{Y}}$ RKBS's on ${\mathcal{X}}$ and ${\mathcal{Y}}$, respectively. Let $\Bmap{\cdot}{\cdot}: {\mathcal{B}}_{\mathcal{X}} \times {\mathcal{B}}_{\mathcal{Y}} \to \mathbb{R}$ be a bilinear mapping on the two RKBS's. Let $\Phi_{\mathcal{X}}: {\mathcal{X}} \to {\mathcal{F}}_{\mathcal{X}}$ and $\Phi_{\mathcal{Y}}: {\mathcal{Y}} \to {\mathcal{F}}_{\mathcal{Y}}$ be fixed feature mappings with the property that $\Fmap{\Phi_{\mathcal{X}}(x_i)}{\Phi_{\mathcal{Y}}(y_i)} = \Bmap{f_{\Phi_{\mathcal{Y}}(y)}}{g_{\Phi_{\mathcal{X}}(x)}}$. Say $\{x_1, \dots, x_{n_x}\}, x_i \in {\mathcal{X}}$, $\{y_1, \dots, y_{n_y}\}, y_j \in {\mathcal{Y}}$, and $\{z_{ij}\}_{i=1,\dots,n_x; \; j=1,\dots,n_y}$, $z_{ij} \in \mathbb{R}$ is a finite dataset where a response $z_{ij}$ is defined for every $(i,j)$ pair of an $x_i$ and a $y_j$. Let $L: {\mathcal{X}} \times {\mathcal{Y}} \times \mathbb{R} \times \mathbb{R} \to \mathbb{R}$ be a loss function that is convex for fixed $(x_i, y_j, z_{i,j})$, and $R_{\mathcal{X}}: [0, \infty) \to \mathbb{R}$ and $R_{\mathcal{Y}}: [0, \infty) \to \mathbb{R}$ be convex, strictly increasing regularization functions. A \emph{binary empirical risk minimization kernel learning problem} for learning on a pair of RKBS's takes the form \begin{align} \begin{split} f^\ast, g^\ast = \argmin_{f \in {\mathcal{B}}_{\mathcal{X}}, g \in {\mathcal{B}}_{\mathcal{Y}}} \Bigg[ &\frac{1}{n_x n_y} \sum_{i,j} L \left(x_i, y_j, z_{ij}, \Bmap{f_{\Phi_{\mathcal{Y}}(y_j)}}{g_{\Phi_{\mathcal{X}}(x_i)}} \right) \\ &+ \lambda_{\mathcal{X}} R_{\mathcal{X}}(\| f \|_{{\mathcal{B}}_{\mathcal{X}}}) + \lambda_{\mathcal{Y}} R_{\mathcal{Y}}(\| g \|_{{\mathcal{B}}_{\mathcal{Y}}}) \Bigg] \label{eq:kernel_problem} \end{split} \end{align} where $\lambda_{\mathcal{X}}$ and $\lambda_{\mathcal{Y}}$ are again scaling constants. \end{definition} \begin{remark} The idea of a binary kernel problem that operates over pairs of two sets is not wholly new: there is prior work both in the collaborative filtering \citep{abernethy_new_2009} and tensor kernel method \citep{tao_supervised_2005,kotsia_support_2011,he_kernelized_2017} literatures. Our problem and results are new in the generalization to Banach rather than Hilbert spaces: as prior work in the RKBS literature \citep[etc.]{micchelli_function_2004,zhang_regularized_2012,xu_generalized_2019} notes, RKBS learning problems are distinct from RKHS ones in their additional nonlinearity and/or nonconvexity. An extension of binary learning problems to Banach spaces is thus motivated by the Transformer setting, where a kernel method is in a context of a nonlinear and nonconvex deep neural network, rather than as a shallow learner like an SVM or matrix completion. For more discussion, see Appendix \ref{app:why_banach}. \end{remark} Virtually all classic kernel learning methods find solutions whose forms are specified by so-called \emph{representer theorems}. Representer theorems state that the solution to a regularized empirical risk minimization problem over a reproducing kernel space can be expressed as a linear combination of evaluations of the reproducing kernel against the dataset. Classic solutions to kernel learning problems thus reduce to finding the coefficients of this linear combination. Representer theorems exist in the literature for RKHS's \citep{kimeldorf_results_1971,scholkopf_generalized_2001,argyriou_when_2009}, RKKS's \citep{ong_learning_2004,oglic_learning_2018}, and RKBS's \citep{zhang_reproducing_2009,zhang_regularized_2012,song_reproducing_2013,fasshauer_solving_2015,xu_generalized_2019,lin_reproducing_2019}. \citet[Theorem 3.2]{fasshauer_solving_2015}, \citet[Theorem 2.23]{xu_generalized_2019}, and \citet[Theorem 4.7]{lin_reproducing_2019} provide representer theorems for RKBS learning problems. However, their theorems only deal with learning problems where datapoints come from only one of the sets on which the reproducing kernel is defined (i.e., only ${\mathcal{X}}$ but not ${\mathcal{Y}}$), which means the solution sought is an element of only one of the Banach spaces (e.g., $f: {\mathcal{X}} \to \mathbb{R}, f \in {\mathcal{B}}_{\mathcal{X}}$). Here, we state and prove a theorem for the more-relevant-to-Transformers binary case presented in Definition \ref{def:binary_kernel}. \begin{theorem} \label{thm:representer} Suppose we have a kernel learning problem of the form in \eqref{eq:kernel_problem}. Let $\kappa: {\mathcal{X}} \times {\mathcal{Y}} \to \mathbb{R}$ be the reproducing kernel of the pair of RKBS's ${\mathcal{B}}_{\mathcal{X}}$ and ${\mathcal{B}}_{\mathcal{Y}}$ satisfying Definitions \ref{def:rkbs} and \ref{def:featuremaps}. Then, given some conditions on ${\mathcal{B}}_{\mathcal{X}}$ and ${\mathcal{B}}_{\mathcal{Y}}$ (see Appendix \ref{app:representer}), the regularized empirical risk minimization problem \eqref{eq:kernel_problem} has a unique solution pair $(f^*, g^*)$, with the property that \begin{align} \iota(f^\ast) = \sum_{i=1}^{n_x} \xi_i \kappa(x_i, \cdot); \qquad \iota(g^\ast) = \sum_{j=1}^{n_y} \zeta_j \kappa(\cdot, y_j). \label{eq:representer} \end{align} where $\iota(f)$ (resp. $\iota(g)$) denotes the G\^ateaux derivative of the norm of $f$ (resp. $g$) with the convention that $\iota(0) \triangleq 0$, and where $\xi_i,\zeta_j \in \mathbb{R}$. \end{theorem} \begin{proof} See Appendix \ref{app:representer}. \end{proof} \subsection{A new approximate kernel learning problem and universal approximation theorem} \label{sec:approx} The downside of finding solutions to kernel learning problems like \eqref{eq:rkhs_learner} or \eqref{eq:kernel_problem} of the form \eqref{eq:representer} as suggested by representer theorems is that they scale poorly to large datasets. It is well-known that for an RKHS learning problem, finding the scalar coefficients by which to multiply the kernel evaluations takes time cubic in the size of the dataset, and querying the model takes linear time. The most popular class of approximation techniques are based on the so-called Nystr\"{o}m method, which constructs a low-rank approximation of the kernel Gram matrix and solves the problem generated by this approximation \citep{williams_using_2001}. A recent line of work \citep{gisbrecht_metric_2015,schleif_indefinite_2017,oglic_scalable_2019} has extended the Nystr\"{o}m method to RKKS learning. In this section, we characterize the Transformer learning problem as a new class of approximate kernel methods -- a ``distillation'' approach, one might call it. We formally state this idea now. \begin{proposition}[Parametric approximate solutions of binary kernel learning problems] Consider the setup of a binary kernel learning problem from Definition \ref{def:binary_kernel}. We want to find approximations to the solution pair $(f^*, g^*)$. In particular, we will say we want an approximation $\hat \kappa: {\mathcal{X}} \times {\mathcal{Y}} \to \mathbb{R}$ such that \begin{equation} \hat \kappa (x, y) \approx \Bmap{f^*_{\Phi_{\mathcal{Y}}(y)}}{g^*_{\Phi_{\mathcal{X}}(x)}}. \label{eq:kernel_approx_prob} \end{equation} for all $x \in {\mathcal{X}}$ and $y \in {\mathcal{Y}}$. Comparing \eqref{eq:kernel_approx_prob} to \eqref{eq:kernel_identity} suggests a solution: to learn a function $\hat \kappa$ that approximates $\kappa$. In particular, \eqref{eq:kernel_identity} suggests learning explicit approximations of the feature maps, i.e., \begin{equation*} \hat \kappa (x, y) \approx \Fmap{\Phi_{\mathcal{X}}(x)}{\Phi_{\mathcal{Y}}(y)}. \end{equation*} In fact, it turns out that the Transformer query-key mapping \eqref{eq:scaleddotproduct_attn} does exactly this. That is, while the Transformer kernel calculation outlined in Propostion \ref{prop:rkbs} is finite-dimensional, it can in fact approximate the potentially infinite-dimensional optimal solution $(f^\ast, g^\ast)$ characterized in Theorem~\ref{thm:representer}. This fact is proved next. \end{proposition} \begin{theorem} \label{th:approx} Let ${\mathcal{X}} \subset \mathbb{R}^{d_t}$ and ${\mathcal{Y}} \subset \mathbb{R}^{d_s}$ be compact; ${\bm{t}} \in {\mathcal{X}}, {\bm{s}} \in {\mathcal{Y}}$; and let $q_\ell: {\mathcal{X}} \to \mathbb{R}$ and $k_\ell: {\mathcal{Y}}~\to~\mathbb{R}$ for $\ell=1, \dots, \dh$ be two-layer neural networks with $m$ hidden units. Then, for any continuous function $F: {\mathcal{X}} \times {\mathcal{Y}} \to \mathbb{R}$ and $\epsilon > 0$, there are integers $m, \dh > 0$ such that \begin{equation} \left| F({\bm{t}}, {\bm{s}}) - \sum_{\ell=1}^\dh q_\ell({\bm{t}}) k_\ell({\bm{s}}) \right| < \epsilon \quad \forall \; {\bm{t}} \in {\mathcal{X}}, {\bm{s}} \in {\mathcal{Y}}. \label{eq:kernel_approx} \end{equation} \end{theorem} \begin{proof} See Appendix \ref{app:approx}. \end{proof} We now outline how Theorem \ref{th:approx} relates to Transformers. If we concatenate the outputs of the two-layer neural networks $\{q_\ell\}_{\ell=1}^d$ and $\{k_\ell\}_{\ell=1}^d$ into $d$-dimensional vectors ${\bm{q}}: \mathbb{R}^{d_t} \to \mathbb{R}^d$ and ${\bm{k}}: \mathbb{R}^{d_s} \to \mathbb{R}^d$, then the dot product ${\bm{q}}({\bm{t}})^\mathsf{T} {\bm{k}}({\bm{s}})$ denoted by the sum in \eqref{eq:kernel_approx} can approximate any real-valued continuous function on ${\mathcal{X}} \times {\mathcal{Y}}$. Minus the usual caveats in applications of universal approximation theorems (i.e., in practice the output elements share hidden units rather than having independent ones), this dot product is exactly the computation of the attention logits $a_{ij}$, i.e., $F({\bm{t}}, {\bm{s}}) \approx \log \kappa({\bm{t}}, {\bm{s}})$ for the $F$ in \eqref{eq:kernel_approx} and the $\kappa$ in \eqref{eq:transformer_kernel} up to a scaling constant $\sqrt{d}$. Since the exponential mapping between the attention logits and the exponentiated query-key kernel used in Transformers is a one-to-one mapping, if we take $F({\bm{t}}, {\bm{s}}) = \log \Bmapbig{f^\ast_{\Phi_{\mathcal{Y}}({\bm{s}})}}{g^\ast_{\Phi_{\mathcal{X}}({\bm{t}})}}$, then we can use a Transformer's dot-product attention to approximate the optimal solution to any RKBS solution arbitrarily well. The core idea of an attention-based deep neural network is then to learn parametric representations of $q_\ell$ and $k_\ell$ via stochastic gradient descent. Unlike traditional representer-theorem-based learned functions, training time of attention-based kernel machines like deep Transformers (generally, but with no guarantees) scale sub-cubically with dataset size, and evaluation time stays constant regardless of dataset size. \section{Is the exponentiated dot product essential to Transformers?} \label{sec:more_kernels} \ctable[ caption = Test BLEU scores for Transformers with various kernels on machine translation (case-sensitive sacreBLEU). Values are mean $\pm$ std. dev over 5 training runs with different random seeds., label = tab:more_kernels, pos = htb, width = \textwidth, star ]{l X X X X X}{ \tnote[]{EDP = Exponentiated dot product; EI = Exponentiated intersection kernel} }{ \toprule & \multicolumn{1}{c}{EDP} & \multicolumn{1}{c}{RBF} & \multicolumn{1}{c}{L2 Distance} & \multicolumn{1}{c}{EI} & \multicolumn{1}{c}{Quadratic} \\ \midrule IWSLT14 DE-EN & $30.41 \pm 0.03$ & $30.32 \pm 0.22$ & $19.45 \pm 0.16$ & $30.84 \pm 0.27$ & $29.56 \pm 0.19$ \\ WMT14 EN-FR & $35.11 \pm 0.08$ & $35.57 \pm 0.20$ & $28.41 \pm 0.26$ & $34.51 \pm 0.17$ & $34.54 \pm 0.30$ \\ \bottomrule } We study modifications of the Transformer with several kernels used in classic kernel machines. We train on two standard machine translation datasets and two standard sentiment classification tasks. For machine translation, IWSLT14 DE-EN is a relatively small dataset, while WMT14 EN-FR is a considerably larger one. For sentiment classification, we consider SST-2 and SST-5. We retain the standard asymmetric query and key feature mappings, i.e., ${\bm{q}} = {\bm{W}}^Q {\bm{t}}$ and ${\bm{k}} = {\bm{W}}^K {\bm{s}}$, and only modify the kernel $\kappa : \mathbb{R}^d \times \mathbb{R}^d \to \mathbb{R}_{\geq 0}$. In the below, $\tau > 0$ and $\gamma \in \mathbb{R}$ are per-head learned scalars. Our kernels of interest are: \begin{enumerate} \item the (scaled) exponentiated dot product (EDP), $\kappa({\bm{q}}, {\bm{t}}) = \exp( {\bm{q}}^T {\bm{k}} / \sqrt{d})$, i.e., the standard Transformer kernel; \item the radial basis function (RBF) kernel, $\kappa({\bm{q}}, {\bm{t}}) = \exp(\|-\nicefrac{\tau}{\sqrt{d}} ({\bm{q}} - {\bm{k}})\|^2_2)$, where $\| \cdot \|_2$ is the standard 2-norm. It is well-known that the RBF kernel is a normalized version of the exponentiated dot-product, with the normalization making it translation-invariant; \item the vanilla L2 distance, $\kappa({\bm{q}}, {\bm{t}}) = \nicefrac{\tau}{\sqrt{d}} \| {\bm{q}} - {\bm{k}} \|_2$; \item an exponentiated version of the intersection kernel, $\kappa({\bm{q}}, {\bm{t}}) = \exp( \sum_{\ell=1}^d \min( {q}_\ell, {k}_\ell ))$. The symmetric version of the intersection kernel was popular in kernel machines for computer vision applications \citep[etc.]{barla_histogram_2003,grauman_pyramid_2005,maji_classification_2008}, and is usually characterized as having an associated RKHS that is a subspace of the function space $L^2$ (i.e., it is infinite-dimensional in the sense of having a feature space of continuous functions, as opposed to the infinite-dimensional infinite series of the EDP and RBF kernels); \item a quadratic polynomial kernel, $\kappa({\bm{q}}, {\bm{k}}) = ( \nicefrac{1}{\sqrt{d}} {\bm{q}}^\mathsf{T} {\bm{k}} + \gamma)^2$. \end{enumerate} Full implementation details are provided in Appendix \ref{sec:implementation}. Results for machine translation are presented in Table \ref{tab:more_kernels}. Several results stand out. First, the exponentiated dot product, RBF, and exponentiated intersection kernels, which are said to have infinite-dimensional feature spaces, indeed do perform better than kernels with lower-dimensional feature maps such as the quadratic kernel. In fact, the RBF and EDP kernels perform about the same, suggesting that a deep Transformer may not need the translation-invariance that makes the RBF kernel preferred to the EDP in classic kernel machines. Intriguingly, the (unorthodox) exponentiated intersection kernel performs about the same as the two than the EDP and RBF kernels on IWSLT14 DE-EN, but slightly worse on WMT14 EN-FR. As mentioned, the EDP and RBF kernels have feature spaces of infinite series, while the intersection kernel corresponds to a feature space of continuous functions. On both datasets, the quadratic kernel performs slightly worse than the best infinite-dimensional kernel, while the L2 distance performs significantly worse. \ctable[ caption = Test accuracies for Transformers with various kernels on sentiment classification. Values are mean $\pm$ std. dev over 5 training runs with different random seeds., label = tab:more_kernels_2, pos = tb, width = \textwidth, star, ]{l X X X X X}{ \tnote[]{EDP = Exponentiated dot product; EI = Exponentiated intersection kernel} }{ \toprule & \multicolumn{1}{c}{EDP} & \multicolumn{1}{c}{RBF} & \multicolumn{1}{c}{L2 Distance} & \multicolumn{1}{c}{EI} & \multicolumn{1}{c}{Quadratic} \\ \midrule SST-2 ($\%$) & $76.70 \pm 0.36$ & $74.24 \pm 0.39$ & $76.78 \pm 0.67$ & $74.90 \pm 1.32$ & $76.24 \pm 0.65$ \\ SST-5 ($\%$) & $39.44 \pm 0.47$ & $39.04 \pm 0.62$ & $39.44 \pm 1.33$ & $37.74 \pm 0.48$ & $39.34 \pm 0.80$ \\ \bottomrule } Results for sentiment classification appear in Table \ref{tab:more_kernels_2}. Unlike the machine translation experiments, the infinite-dimensional kernels do not appear strictly superior to the finite-dimensional ones on this task. In fact, the apparent loser here is the exponentiated intersection kernel, while the L2 distance, which performed the worst on machine translation, is within a standard deviation of the top-performing kernel. Notably, however, the variance of test accuracies on sentiment classification means that it is impossible to select a statistically significant ``best'' on this task. It is possible that the small inter-kernel variation relates to the relative simplicity of this problem (and relative smallness of the dataset) vs. machine translation: perhaps an infinite-dimensional feature space is not needed to obtain Transformer-level performance on the simpler problem. It is worth noting that the exponentiated dot product kernel (again, the standard Transformer kernel) is a consistent high performer. This may be experimental evidence for the practical usefulness of the universal approximation property they enjoy (c.f. Theorem \ref{th:approx}). The relatively small yet statistically significant performance differences between kernels is reminiscent of the same phenomenon with activation functions (ReLU, ELU, etc.) for neural nets. Moreover, the wide inter-kernel differences in performance for machine translation, compared against the much smaller performance differences on the SST sentiment analysis tasks, suggests differing representational needs for problems of differing complexity. As a whole, these results suggest that kernel choice may be an additional design parameter for Transformer networks. \section{Conclusion} \label{sec:conclusion} In this paper, we drew connections between classic kernel methods and the state-of-the-art Transformer networks. Beyond the theoretical interest in developing new RKBS representer theorems and other kernel theory, we gained new insight into what may make Transformers work. Our experimental results suggest that the infinite dimensionality of the Transformer kernel makes it a good choice in application, similar to how the RBF kernel is the standard choice for e.g. SVMs. Our work also reveals new avenues for Transformer research. For example, our experimental results suggest that choice of Transformer kernel acts as a similar design choice as activation functions in neural net design. Among the new open research questions are (1) whether the exponentiated dot-product should be always preferred, or if different kernels are better for different tasks (c.f. how GELUs have recently become very popular as replacements for ReLUs in Transformers), (2) any relation between vector-valued kernels used for structured prediction \citep{alvarez_kernels_2012} and, e.g., multiple attention heads, and (3) the extension of Transformer-type deep kernel learners to non-Euclidean data (using, e.g., graph kernels or kernels on manifolds). \bibliographystyle{abbrvnat} \newcommand{\noopsort}[1]{}
{'timestamp': '2021-06-04T02:06:40', 'yymm': '2106', 'arxiv_id': '2106.01506', 'language': 'en', 'url': 'https://arxiv.org/abs/2106.01506'}
arxiv
\section{Introduction} \label{sec:introduction} \subsection{The Case for FCFS} While advanced scheduling algorithms are a popular topic in theory papers, it is unequivocal that the most popular scheduling policy used in practice is still First-Come First-Served (FCFS). There are many reasons for the popularity of FCFS. From a practical perspective, FCFS is easy to implement. Additionally, FCFS has a feeling of being fair. However, there are also theoretical arguments for why one should use FCFS. For one thing, FCFS minimizes the {\em maximum} response time across jobs for {\em any} finite arrival sequence of jobs. By {\em response time} we mean the time from when a job arrives until it completes service. For another thing, in an M/G/1 with a light-tailed job size distribution, FCFS is known to have a {\em weakly optimal} asymptotic tail of response time \citep{stolyar_largest_2001,boxma_tails_2007}. Specifically, using $T$ to denote response time, the asymptotic tail under FCFS is of the form: \begin{equation} \label{eq:FCFS_asymptotic} \P{T^\mathsf{FCFS} > t} \sim C_\mathsf{FCFS} e^{-\theta^* t}, \end{equation} where ``$\sim$'' indicates that the ratio of the two quantities converges to $1$ in the $t \to \infty$ limit. The exponent $\theta^*$ in \eqref{eq:FCFS_asymptotic} is known to be optimal, while the optimality of $C_\mathsf{FCFS}$ is an open problem \citep{boxma_tails_2007}. The asymptotic tail growth under FCFS has been compared with more sophisticated policies \citep{boxma_tails_2007}. It has been shown that, for light-tailed job size distributions, the tail of response time under Processor-Sharing (PS), Preemptive Last-Come-First-Served (PLCFS), and Shortest-Remaining-Processing-Time (SRPT) each take the asymptotic form of $$\P{T > t} \sim C' e^{-\theta' t},$$ where $\theta'$ is the \emph{worst possible} exponential decay rate \citep{nair_tail_2010} over all work-conserving scheduling policies. Roughly, FCFS's tail exponent $\theta^*$ arises from the tail of the workload distribution, while the other policies' tail exponent $\theta'$ arises from the tail of the busy period distribution, which is much larger under light-tailed job size distributions. \subsection{The Case For Light-Tailed Job Size Distributions} In this paper, we choose to focus on the case of light-tailed job size distributions. Light-tailed job size distributions show up naturally in workloads where all the transactions are of the same type (say shopping); while there is some variability in the time it takes to purchase an item, even high-variability distributions that arise in such settings are often light-tailed. Also, many natural distributions, like the Normal distribution, Exponential distribution, and all Phase-type distributions, are light-tailed. Finally, while heavy-tailed job size distributions are certainly prevalent in empirical workloads (see for example \cite{Eurosys20,h-t,CrovellaTaqquBestavros98}), in practice, these heavy-tailed workloads are often {\em truncated}, which immediately makes them light-tailed. Such truncation can happen because there is a limit imposed on how long jobs are allowed to run. Alternatively, truncation can occur when a heavy-tailed job size distribution is divided into a few size classes as in \cite{JACM02,JPDC99} where the smaller size classes end up being truncated distributions. \subsection{The Case for Non-Asymptotic Tails} Within the world of light-tailed job size distributions, FCFS is viewed as the best policy. However, while FCFS has a weakly optimal {\em asymptotic} tail, it is not best at minimizing $\P{T > t}$ for {\em all} $t$. In practice, one cares less about the asymptotic case than about particular $t$ \cite{QUESTA21}. For example, one might want to minimize the fraction of response times that exceed $t = 0.5$ seconds, because such response times are noticeable by users. One might also want to meet several additional Service Level Objectives (SLOs) where one is charged for exceeding particular response time values, such as $t = 1$ minute, or $t = 1$ hour. SLOs are very common in the computing literature \citep{MogulWilkes19,chen_sla_2007,QUESTA21}, in service industries \cite{davis_how_1991,so_price_1998,urban_establishing_2009}, and in healthcare \citep{blake_analysis_1996,horwitz_us_2010}. Unfortunately, different applications have different SLOs. This leads us to ask: \begin{quote} {\em When considering $\P{T > t}$, is it possible to strictly improve upon FCFS for \underline{all} values of $t$?} \end{quote} We are motivated by the fact that, for lower values of $t$, Shortest-Remaining-Processing-Time (SRPT) is better than FCFS, although FCFS clearly beats SRPT for higher values of $t$, as FCFS is weakly asymptotically optimal while SRPT is asymptotically pessimal \citep{nair_tail_2010,nuyens_preventing_2008}. SRPT also minimizes mean response time \cite{Schr68}, which is closely related to lower values of $t$. This motivates us to consider whether prioritizing small jobs might have some benefit, even in the world of light-tailed job size distributions. We ask more specifically: \begin{quote} {\em Can partial prioritization of small jobs lead to a strict improvement over FCFS? Specifically, is there a scheduling policy which strictly improves upon FCFS with respect to $\P{T > t}$, for {\em every} possible $t$ including large $t$?} \end{quote} \subsection{Our Answer: Nudge} \begin{figure}[t] \includegraphics[height=0.8in]{nudge.pdf} \caption{The Nudge algorithm.} \label{fig:nudge} \end{figure} \begin{figure}[t] \centering \includegraphics[width=\linewidth]{improvement_08.pdf} \caption[Text]{Empirical tail improvement of Nudge over FCFS in an M/G/1. The tail improvement ratio (TIR) is defined as $1 - \P{T^\mathsf{Nudge} > t}/\P{T^\mathsf{FCFS} > t}$. Specific job size distributions, each with mean $1$: Uniform($0$,$2$); Exponential with mean $1$; Hyperexponential with branches drawn from Exp($2$) and Exp($1/3$), where the first branch has probability $0.8$ and where $C^2 = 3$; BoundedLomax($\lambda=2$, max$=4$, $\alpha = 2$). Distributions in legend ordered by asymptotic improvement. Simulations run with $10$ billion arrivals. Load $\rho = 0.8$. Nudge parameters: $x_1 = 1, x_2 = 1, x_3 = \infty$. Note that $x_1 = x_2$, so there are no medium-sized jobs. Empirically, Nudge often achieves its best performance with $x_1 = x_2$, though our proofs involve setting $x_1 < x_2$. See \cref{sec:empirical}. } \label{fig:improvement_plot} \end{figure} This paper answers the above question in the affirmative. We will define a policy, which we call {\em Nudge}, whose response time tail is {\em provably} better than that of FCFS for {\em every} value of $t$, assuming a light-tailed job size distribution\footnote{% Technically, a Class I job size distribution. See \cref{def:class_I}.} (see \cref{thm:existence_of_improvement}). We say that Nudge's response time {\em stochastically improves upon} that of FCFS, in the sense of stochastic dominance. Moreover, we prove that the asymptotic tail of response time of Nudge is of the form \begin{align*} P\{T^\mathsf{Nudge} > t\} \sim C_\mathsf{Nudge} e^{-\theta^* t}, \end{align*} with optimal decay rate $\theta^*$ and a superior leading constant $C_\mathsf{Nudge} < C_\mathsf{FCFS}$ (see \cref{cor:existence_of_asymptotic_improvement}). Thus, we demonstrate that FCFS is \emph{not} strongly optimal, answering an open problem posed by Boxma and Zwart \citep{boxma_tails_2007}. In particular, this is contrary to a conjecture of \citet{wierman_is_2012} (see \cref{sub:prior_asymptotic}). The intuition behind the Nudge algorithm is that we'd like to basically stick to FCFS, which we know is great for handling the extreme tail (high $t$), while at the same time incorporating a little bit of prioritization of small jobs, which we know can be helpful for the mean and lower $t$. We need to be careful, however, not to make too much use of size, because Nudge still needs to beat FCFS for high $t$; hence we want just a little ``nudge'' towards prioritizing small jobs. We now describe the Nudge algorithm. Imagine that the job size distribution is divided into size regions, as shown in \cref{fig:nudge}, consisting of small, medium, large, and extra large jobs. Most of the time, Nudge defaults to FCFS. However, when a ``small'' job arrives and finds a ``large'' job immediately ahead of it in the queue, we swap the positions of the small and large job in the queue. The one caveat is that a job which has already swapped is ineligible for further swaps. The size cutoffs defining small and large jobs will be defined later in the paper. The degree of the tail improvement of Nudge over FCFS is non-trivial. In \cref{fig:improvement_plot}, we see that for many common light-tailed job size distributions, Nudge results in a multiplicative improvement of 4-7\% throughout the tail. In \cref{sec:empirical_low_load}, we show that with low load and a high-variability job size distribution, Nudge's improvement can be as much as 10-15\% throughout the tail. The magnitude of these improvements highlights the importance of scheduling, even in the light-tailed setting. We additionally present an exact analysis of the performance of Nudge. Nudge does not fit into any existing framework for M/G/1 transform analysis, including the recently developed SOAP framework \citep{scully_soap_2018} (see \cref{sub:prior_transform}). Nonetheless, we derive a tagged-job analysis of Nudge in \cref{thm:transform}, deriving the Laplace-Stieltjes transform of response time of Nudge. \subsection{Contributions and Roadmap} This paper makes the following contributions. \begin{itemize} \item In \cref{sec:nudge_definition}, we introduce the Nudge policy. \item In \cref{sec:main_results,sec:proof_improvement_regime,sec:proof_of_existence_of_improvement} we prove that with appropriately chosen parameters, Nudge stochastically improves upon FCFS for light-tailed% \footnote{% Technically, any Class I job size distribution. See \cref{def:class_I}.} job size distributions; we also give a simple expression for such parameters. Moreover, in \cref{sec:proof_of_asymptotic_constant}, we prove that Nudge achieves a multiplicative asymptotic improvement over FCFS. \item In \cref{sec:transform}, we derive the Laplace-Stieltjes transform of response time under Nudge. \item In \cref{sec:empirical}, we empirically demonstrate the magnitude of Nudge's stochastic improvement over FCFS. We also discuss how to tune Nudge's parameters for best performance. \item In \cref{sec:nudge_in_practice}, we discuss practical considerations for using Nudge. \item In \cref{sec:nudge_variants}, we discuss several notable variants of Nudge. \end{itemize} \section{Prior Work} Most prior work on scheduling to optimize the tail of response time focuses on the \emph{asymptotic} case, characterizing $\P{T > t}$ in the $t \to \infty$ limit. We review these results in \cref{sub:prior_asymptotic}. Our main result, \cref{thm:existence_of_improvement}, is a \emph{non-asymptotic} statement, characterizing the behavior of $\P{T > t}$ for \emph{all}~$t$, not just the $t \to \infty$ limit. There is much less prior work on the tail of response time outside of the asymptotic regime. We review the few results in this area in \cref{sub:prior_non-asymptotic}. In addition to characterizing Nudge's tail of response time, we also give an exact transform analysis of Nudge's response time. Our analysis requires a novel approach that significantly differs from traditional analyses, as we discuss in \cref{sub:prior_transform}. Our paper's focus is the M/G/1 queue. All of the results cited in this section apply to the M/G/1, with some also applying to more general models, such as the GI/GI/1. \subsection{Asymptotic Tails: Extensive Theory, but Open Problems Remain} \label{sub:prior_asymptotic} When optimizing the asymptotic tail, the goal is to find a policy $\pi^*$ such that for all scheduling policies $\pi$, \begin{equation*} \limsup_{t \to \infty} \frac{\P{T^{\pi^*} > t}}{\P{T^\pi > t}} \le c \end{equation*} for some constant~$c \in [1,\infty)$. Such a policy $\pi^*$ is called \emph{weakly optimal}; if $c = 1$, then $\pi^*$ is called \emph{strongly optimal} \citep{boxma_tails_2007}. While weak optimality has been well studied, proving or disproving strong optimality is much harder. One major theme of the prior work is that optimizing the asymptotic tail looks very different depending on the job size distribution. \begin{itemize} \item For light-tailed job sizes, FCFS is weakly optimal \citep{boxma_tails_2007}. Specifically, the tail of response time has a form given in \eqref{eq:FCFS_asymptotic}. Moreover, many popular preemptive policies such as PS, SRPT, and Foreground-Background (FB)% \footnote{% FB at all times serves the jobs that have received the least service so far. } are ``weakly pessimal'': they have the \emph{maximum} possible asymptotic tail, up to a constant factor, of any work-conserving scheduling policy \citep{nair_tail_2010,nuyens_preventing_2008}. \item For heavy-tailed job sizes, the reverse is true: PS, SRPT, FB, and similar policies are all weakly optimal \citep{nuyens_preventing_2008,scully_characterizing_2020,boxma_tails_2007}, while FCFS is weakly pessimal. \end{itemize} This state of affairs prompts a question: is any policy weakly optimal in both the light-tailed and heavy-tailed cases? \Citet{nair_tail_2010} show that a variant of PS achieves this, but their variant requires knowledge of the system's load. \Citet{wierman_is_2012} show that {\em any} policy that is weakly optimal in both the light- and heavy-tailed cases requires knowing some information about the system parameters, such as the load. The above results mostly characterize weakly optimal scheduling policies, but the problem of strongly optimizing the tail remains open. \Citet{boxma_tails_2007} pose the strong optimality of FCFS as an open problem. \Citet{wierman_is_2012} go further and conjecture that FCFS is in fact strongly optimal for light-tailed job size distributions. Despite a large of body of work analyzing the tail asymptotics of FCFS \citep{abate1994waiting,sakurai2004approximating,abate1997asymptotics,abate1995exponential}, the problem has remained open. We solve the problem by showing that FCFS is \emph{not} strongly optimal. Specifically, our \cref{cor:existence_of_asymptotic_improvement} implies \begin{align*} \lim_{t \to \infty} \frac{\P{T^\mathsf{Nudge} > t}}{\P{T^\mathsf{FCFS} > t}} = \frac{C_\mathsf{Nudge}}{C_\mathsf{FCFS}} < 1. \end{align*} \subsection{Non-asymptotic Tails: Few Optimality Results} \label{sub:prior_non-asymptotic} Characterizing $\P{T > t}$ outside the asymptotic regime is a much harder problem than characterizing the asymptotic tail. As such, the strongest results in this area are for relatively simple scheduling policies. For FCFS under light-tailed job size distributions, it is known that $\P{T > t} < e^{-\theta^* t}$ for the same constant $\theta^*$ as appears in FCFS's asymptotic tail formula \citep{kingman_martingale_1964,kingman_inequalities_1970}. As a result, this bound is tight up to a constant factor \citep{kingman_inequalities_1970}, subject to subtleties discussed in \cref{sec:model_class_I}. Beyond FCFS, one of the few known results gives an improved characterization of response time under preemptive-priority scheduling policies \citep[Section~2]{abate1997asymptotics}. Very little is known about more complicated scheduling policies. While the Laplace-Steiltjes transform of~$T$ is known for a wide variety of scheduling policies \citep{scully_soap_2018,stanford2014waiting}, these transforms do not readily yield useful bounds on $\P{T > t}$ for general job size distributions. Given that characterizing $\P{T > t}$ is difficult, it comes as no surprise that optimizing $\P{T > t}$ is harder still. As such, rather than trying to crown a single optimal policy, we focus on a \emph{relative} measure. Specifically, as we define in \cref{def:stochastic_improvement}, we say that policy~$\pi_1$ \emph{stochastically improves upon} another policy~$\pi_2$ if $\P{T^{\pi_1} > t} \leq \P{T^{\pi_2} > t}$ for all~$t$. There are two stochastic improvement results in the literature, but both are much simpler than our Nudge result. Both results start with a well-known policy that does not use job sizes and show that a variation that does use job sizes stochastically improves response time. \begin{itemize} \item \Citet{nuyens_preventing_2008} show that SRPT and similar policies stochastically improve upon FB. \item \Citet{friedman_fairness_2003} and \citet{friedman2003protective} show that one can stochastically improve upon PS by using job sizes. Their policy, Fair Sojourn Protocol (FSP), guarantees in a sample-path sense that no job departs later than it would if the server were using PS. \end{itemize} The results above fit a common theme. Both FB and PS often share the server between multiple jobs. Sharing the server is fundamentally suboptimal. For example, when sharing the server between jobs~1 and~2, if we knew that we would finish job~1 first, then it would be better to devote the entire server to job~1 at first. Doing so improves the response time of job~1 without harming the response time of job~2. Roughly speaking, when FB and PS would share the server between jobs, SRPT and FSP serve the jobs one at a time, using job size information to choose the ordering. FCFS is more difficult to stochastically improve upon than FB and PS. For one thing, FCFS never shares the server, removing this easy opportunity for stochastic improvement. Moreover, there is a sense in which FCFS is unimprovable: on any specific finite arrival sequence, FCFS minimizes the sorted vector of response times, where we order vectors lexicographically. For example, FCFS minimizes the maximum response time. As a result, the sample path arguments that work for improving FB and PS do not apply to improving FCFS. In spite of these obstacles, we show in \cref{thm:existence_of_improvement} that Nudge stochastically improves upon FCFS. Rather than reasoning in terms of sample paths, we take a fundamentally stochastic approach from the beginning. See our proofs in \cref{sec:proof_improvement_regime}. \subsection{Transform of Response Time: Nudge Needs a Novel Approach} \label{sub:prior_transform} In \cref{thm:transform}, we give a closed-form expression for the Laplace-Stieltjes transform of Nudge's response time. There has been much prior work on analyzing the transform of response time of the M/G/1 under various scheduling policies. Some analysis techniques cover a wide variety of scenarios \citep{scully_soap_2018,fuhrmann_stochastic_1985}. However, as we explain below, none of these prior techniques can analyze Nudge. \emph{\textsf{SOAP Policies.}} Policies in the SOAP class, introduced by \citet{scully_soap_2018}, schedule jobs based on an index calculated from each job's size and attained service\footnote{% The index can also depend on certain other characteristics of the job, e.g. its class if there are multiple classes of jobs. Size and attained service are the attributes relevant to Nudge.}, and their response time can be analyzed via the SOAP framework \citep{scully_soap_2018}. These include SRPT \citep{schrage_queue_1966}, FB \citep{schrage_queue_1967}, some multi-level processor sharing policies \citep{kleinrock_queueing_1976}, and certain cases of the Gittins policy \citep{osipova_optimal_2009}. Unfortunately, Nudge is not a SOAP policy, so we cannot leverage this analysis method. This is because whether Nudge will swap a small job~$s$ with a large job~$\ell$ depends in part on whether any other jobs arrive between $\ell$ and~$s$. In contrast, a SOAP policy would make such a decision based on properties of $\ell$ and~$s$ alone. \emph{\textsf{Variations on FCFS.}} Nudge serves jobs in FCFS order by default and only ever swaps adjacent arrivals. One might therefore hope that Nudge could be analyzed as a variation on FCFS. There are many papers analyzing a variety of M/G/1 variants under FCFS scheduling. These include systems with generalized vacations \citep{fuhrmann_stochastic_1985} and exceptional first service \citep{welch_generalized_1964}. Unfortunately, to the best of our knowledge, no prior analysis of a variation of FCFS applies to Nudge. \emph{\textsf{Other Analysis Techniques.}} There are a number of scheduling policies whose transform analyses do not fit into either of the previous categories, such as random order of service \citep{kingman_queues_1962} and systems with accumulating priority \citep{stanford2014waiting}. However, these policies do not resemble Nudge, and the techniques used in their analyses do not readily apply to Nudge. \section{Model} \subsection{Notation} We consider the M/G/1 queue in which job sizes are known. Let $\lambda$ be the arrival rate, $S$ be the job size distribution, and $s_{\min}$ be the minimum possible job size. Specifically, let $s_{\min}$ be the infimum of the support of $S$. We denote the load by $\rho=\lambda \E{S}$ and assume $0 < \rho < 1$. The queueing time, $T_Q$, is the time from when a job arrives until it first receives service. The response time, $T$, is the time from when a job arrives until it completes. We write $T_Q^{\mathsf{Alg}}$ and $T^{\mathsf{Alg}}$ for the queueing time and response time under scheduling algorithm $\mathsf{Alg}$, respectively. For any continuous random variable $V$, we will use $f_V(\cdot)$ to denote the probability density function (p.d.f.) of $V$. We write the $\widetilde{V}(s)$ for the Laplace-Stieltjes transform of $V$. \subsection{Stochastic Improvement} In this paper, our goal is to prove that the $\mathsf{Nudge}$ policy stochastically improves upon the $\mathsf{FCFS}$ policy. We now define stochastic improvement, along with the related notion of tail improvement ratio. \begin{definition}[Stochastic Improvement] \label{def:stochastic_improvement} For two scheduling algorithms $\mathsf{Alg}_1$ and $\mathsf{Alg}_2$, we say that $\mathsf{Alg}_1$ (strictly) \emph{stochastically improves} upon $\mathsf{Alg}_2$ if, for any response time cutoff $t>s_{\min}$, the probability that response time of $\mathsf{Alg}_1$ exceeds $t$ is smaller than the probability that $\mathsf{Alg}_2$'s response time exceeds $t$, i.e., \begin{equation*} \forall t > s_{\min}, \quad \P{T^{\mathsf{Alg}_1} > t } < \P{T^{\mathsf{Alg}_2} > t }. \end{equation*} \end{definition} \begin{definition}[Tail improvement ratio] For any response time cutoff $t$, the \emph{tail improvement ratio} of $\mathsf{Alg}_1$ versus $\mathsf{Alg}_2$ at $t$, denoted $\mathsf{TIR}(t)$, is defined as \begin{equation*} \mathsf{TIR}(t)\triangleq 1-\frac{\P{T^{\mathsf{Alg}_1}>t}}{\P{T^{\mathsf{Alg}_2}>t}}. \end{equation*} The \emph{asymptotic tail improvement ratio}, denoted $\mathsf{AsymTIR}$, is defined as \begin{equation*} \mathsf{AsymTIR} \triangleq \liminf_{t\to\infty} \mathsf{TIR}(t) =1 - \limsup_{t\to\infty} \frac{\P{T^{\mathsf{Alg}_1}>t}}{\P{T^{\mathsf{Alg}_2}>t}}. \end{equation*} \end{definition} \subsection{Class I ``Light-Tailed'' Distributions} \label{sec:model_class_I} In this paper, we focus on job size distributions for which the FCFS policy has an asymptotically exponential waiting time distribution. This property of FCFS will be crucial for our analysis. Prior work has exactly characterized the job size distributions for which FCFS has this property. These distributions are known as ``class I'' distributions \citep{abate1994waiting,sakurai2004approximating,abate1997asymptotics}. \begin{definition}[Class I Distribution] \label{def:class_I} For a distribution $S$, let $-s^*$ be the rightmost singularity of $\widetilde{S}(s)$, with $-s^*=-\infty$ if $\widetilde{S}(s)$ is analytic everywhere. $S$ is a \emph{class I distribution} if and only if $s^*>0$ and $\widetilde{S}(-s^*)=\infty$. \end{definition} Class I distributions can roughly be thought of as ``well-behaved'' light-tailed distributions. In contrast, class II distributions, the other class of light-tailed distributions, are very unusual and ``paradoxical'', and rarely occur as job size distributions. For our paper, the key property of class I job size distributions is that they cause FCFS to have an asymptotically exponential waiting time distribution for all loads \citep{abate1994waiting,abate1995exponential}. However, as shown by \cite{abate1994waiting,abate1995exponential}, the waiting time also exhibits an exponential tail for light load if the job size is class II. For this reason, while we focus only on class I distributions, we believe that our results also hold for class II under light load. In \cref{sec:fcfs_waiting_time}, we characterize the exponential waiting time in more detail. \subsection{Characterizing the FCFS Waiting Time Distribution} \label{sec:fcfs_waiting_time} In this paper, we care about the exponential tail of the FCFS response time distribution. It turns out to be simpler to focus on the FCFS waiting time distribution, which is closely related. We will make use of two key concepts regarding the waiting time distribution. The first concept is the asymptotic exponential decay rate, as investigated in~\cite{abate1995exponential,boxma_tails_2007}. We refer to this quantity as $\theta^*$ and formally define it to be the negative of the rightmost singularity of $\widetilde{T_Q^\mathsf{FCFS}}$. Based on the Cramer-Lundberg theory, the waiting time distribution $T_Q^\mathsf{FCFS}$ takes an asymptotic exponential tail: \begin{equation} \label{eq:notation_asymptotic_cdf} \P{T_Q^{\mathsf{FCFS}}>t}\sim Ce^{-\theta^*t}. \end{equation} The quantity $\theta^*$ is the least positive real solution to the equation \begin{equation*} \widetilde{S}(-\theta^*)=\frac{\lambda + \theta^*}{\lambda}. \end{equation*} We also define the \emph{normalized p.d.f.} to be \begin{align} \label{eq:notation_pdf} g(t)\triangleq f_{T_Q^\mathsf{FCFS}}(t)\cdot e^{\theta^* t}. \end{align} Note that \eqref{eq:notation_asymptotic_cdf} relates to the c.d.f. of waiting time, while \eqref{eq:notation_pdf} relates to the p.d.f. of waiting time. We characterize three important properties of the normalized p.d.f., namely its maximum, minimum, and asymptotic limit. Let $g_{\max},\ g_{\min},\ g^*$ denote respectively the maximum, minimum and asymptotically limiting values of $g(\cdot)$ over $[0,\infty)$: \begin{equation*} g_{\max}\triangleq\sup\limits_{t\in[0,\infty)}g(t);\qquad g_{\min}\triangleq\inf\limits_{t\in[0,\infty)}g(t); \qquad g^* \triangleq \lim_{t \to \infty} g(t). \end{equation*} The following lemma, proven in \cref{app:normalized_converges}, implies these quantities are well defined. \begin{lemma} \label{lem:normalized_converges} Suppose $S$ is a continuous class I job size distribution. For any load~$\rho$, the normalized p.d.f. $g(t)$ is bounded above and below by positive constants, and $\lim_{t \to \infty} g(t)$ exists. \end{lemma} The ratio $g_{\max}/g_{\min}$ will be particularly important in our analysis. Intuitively, we can think of the ratio as measuring the deviation of the queueing time $T_Q^\mathsf{FCFS}$ from a perfect exponential distribution. The queueing time distribution is exactly an exponential distribution in an $M/M/1$, and diverges from an exponential to greater or lesser degree under any class I job size distribution. The degree of divergence will show up in our later results. \subsection{Scheduling Algorithm: Nudge} \label{sec:nudge_definition} We now formally define the Nudge algorithm. $\mathsf{Nudge}$($x_1, x_2, x_3$) first divides jobs into four regions based on their sizes: \begin{itemize} \item ``small'': $0=x_0 \le S < x_1$. \item ``medium'': $x_1 \le S < x_2$. \item ``large'': $x_2 \le S < x_3$. \item ``very large'': $x_3 \le S < x_4=\infty$. \end{itemize} Throughout the paper, we concentrate mostly on the ``small'' and the ``large'' jobs. For conciseness, we define $S_{\textnormal{\textsf{\tiny small}}},S_{\textnormal{\textsf{\tiny large}}},p_{\textnormal{\textsf{\tiny small}}},p_{\textnormal{\textsf{\tiny large}}}$ as follows. \begin{definition} \label{def:small_large} We define $S_{\textnormal{\textsf{\tiny small}}}$ and $S_{\textnormal{\textsf{\tiny large}}}$ to be the distribution of small and large jobs, respectively. We also define $p_{\textnormal{\textsf{\tiny small}}}$ and $p_{\textnormal{\textsf{\tiny large}}}$ to be the fraction of small and large jobs, respectively. \begin{align*} S_{\textnormal{\textsf{\tiny small}}} \sim [S|S<x_1],&\qquad S_{\textnormal{\textsf{\tiny large}}} \sim [S|x_2 \le S < x_3]\\ p_{\textnormal{\textsf{\tiny small}}} \triangleq \P{S < x_1},&\qquad p_{\textnormal{\textsf{\tiny large}}} \triangleq \P{x_2 \le S < x_3}. \end{align*} \end{definition} To determine which job to serve, $\mathsf{Nudge}$ maintains an ordering over jobs which have not yet entered service. We call this ordering the ``queue''. For each job, we also track whether or not it each has already been ``swapped''. Whenever a job completes, $\mathsf{Nudge}$ serves the job at the front of the queue (if any), and serves it to completion. By default, newly arriving jobs are placed at the back of the queue, resulting in $\mathsf{FCFS}$ scheduling by default. However, if {\em three conditions} are satisfied, then a ``swap'' is performed. If \begin{enumerate} \item the arriving job is a small job, $j_s$, \item the job at the back of queue is a large job, $j_\ell$, and \item the job $j_\ell$ at the back of queue has never been swapped, \end{enumerate} then $\mathsf{Nudge}$ places the small job $j_s$ just ahead of $j_\ell$, in the second-to-last position in the queue. This is called a {\em swap}, and both $j_\ell$ and $j_s$ are now marked as having been ``swapped.'' Because Nudge never swaps the same job twice, a job is only in the last position in the queue and eligible to be swapped immediately after it arrives. As a result, Nudge only ever swaps a job with the job that arrives immediately before or after it. \section{Main Results} \label{sec:main_results} \subsection{Nudge Improves upon FCFS Non-Asymptotically} \label{sec:nudge_improves_non-asymptotic} Our main goal is to show that Nudge stochastically improves upon FCFS. Nudge's performance crucially depends on the choice of parameters $x_1$, $x_2$, and~$x_3$, i.e. which jobs are small and which jobs are large. We begin by asking: given job size distribution~$S$ and load~$\rho$, for what choices of parameters $x_1$, $x_2$, and~$x_3$ does Nudge stochastically improve upon FCFS? We answer this in \cref{thm:improvement_regime}, which gives sufficient conditions on the parameters for Nudge to stochastically improve upon FCFS. We prove \cref{thm:improvement_regime} in \cref{sec:proof_improvement_regime}. \begin{theorem}[Stochastic Improvement Regime] \label{thm:improvement_regime} Suppose $S$ is a continuous class I job size distribution. Then $\mathsf{Nudge}(x_1, x_2, x_3)$ stochastically improves upon $\mathsf{FCFS}$ for any $s_{\min} < x_1\le x_2\le x_3$ satisfying\footnote{% Recall from \cref{def:small_large} that $S_{\textnormal{\textsf{\tiny small}}}$ and $S_{\textnormal{\textsf{\tiny large}}}$ depend on $x_1$, $x_2$, and~$x_3$. This applies throughout the paper.} \begin{align} \bullet\ \ &\frac{g_{\max}}{g_{\min}} \frac{\lambda+\theta^*}{\lambda}< \frac{1-\widetilde{S_{\textnormal{\textsf{\tiny large}}}}(-\theta^*)^{-1}} {1-\widetilde{S_{\textnormal{\textsf{\tiny small}}}}(-\theta^*)^{-1}}, \label{eq:gmax/gmin_<_function(x_1,x_2)}\\ \bullet\ \ &x_1+x_3\le 2x_2. \label{eq:x1_x2_x3_to_remove_t} \end{align} \end{theorem} With \cref{thm:improvement_regime} in hand, our goal reduces to the following question: given $S$ and~$\rho$, do there exist parameters satisfying the sufficient condition from \cref{thm:improvement_regime}? We answer this in \cref{thm:existence_of_improvement}, showing that as long as the minimum job size $s_{\min} = 0$, such parameters always exist. Our proof of \cref{thm:existence_of_improvement} in \cref{sec:proof_of_existence_of_improvement} gives a simple construction of those parameters. \begin{theorem}[Existence of Stochastic Improvement] \label{thm:existence_of_improvement} For any continuous class I job size distribution $S$ with $s_{\min} = 0$ and any load $0<\rho<1$, there exist $x_1, x_2, x_3$ satisfying \eqref{eq:gmax/gmin_<_function(x_1,x_2)} and~\eqref{eq:x1_x2_x3_to_remove_t}, implying that $\mathsf{Nudge}(x_1,x_2,x_3)$ stochastically improves upon $\mathsf{FCFS}$. \end{theorem} \subsection{Nudge Improves upon FCFS Asymptotically} \label{sec:nudge_improves_asymptotic} Having shown that Nudge stochastically improves upon FCFS, we ask: is Nudge's improvement non-negligible in the asymptotic limit? We answer this in \cref{thm:asymptotic_constant}. Specifically, recall that in the $t \to \infty$ limit, $\P{T^\mathsf{FCFS} > t} \sim C_\mathsf{FCFS} e^{-\theta^* t}$. We show that $\P{T^\mathsf{Nudge} > t} \sim C_\mathsf{Nudge} e^{-\theta^* t}$ and that, with appropriately set parameters, $C_\mathsf{Nudge} < C_\mathsf{FCFS}$. This implies that FCFS is \emph{not} strongly optimal for asymptotic tail behavior (see \cref{sub:prior_asymptotic}), resolving a long-standing open problem \citep{boxma_tails_2007,wierman_is_2012}. We also exactly derive the difference $C_\mathsf{FCFS} - C_\mathsf{Nudge}$. We prove \cref{thm:asymptotic_constant} in \cref{sec:proof_of_asymptotic_constant}, making use of \cref{thm:transform}. \begin{theorem}[Asymptotic Improvement Regime] \label{thm:asymptotic_constant} Suppose $S$ is a continuous class I job size distribution. For any $s_{\min} < x_1 \leq x_2 \leq x_3$, the asymptotic tail improvement ratio of $\mathsf{Nudge}(x_1, x_2, x_3)$ compared to $\mathsf{FCFS}$ is \begin{equation*} \mathsf{AsymTIR} = p_{\textnormal{\textsf{\tiny small}}}p_{\textnormal{\textsf{\tiny large}}} \frac{\lambda}{\lambda+\theta^*}\left( \widetilde{S_{\textnormal{\textsf{\tiny large}}}}(-\theta^*) -\frac{\lambda}{\lambda+\theta^*} \widetilde{S_{\textnormal{\textsf{\tiny small}}}}(-\theta^*) -\frac{\theta^*}{\lambda+\theta^*} \widetilde{S_{\textnormal{\textsf{\tiny large}}}}(-\theta^*)\widetilde{S_{\textnormal{\textsf{\tiny small}}}}(-\theta^*) \right). \end{equation*} Furthermore, $\mathsf{AsymTIR}$ is positive, meaning $C_\mathsf{Nudge} < C_\mathsf{FCFS}$, if \begin{equation*} \frac{\lambda+\theta^*}{\lambda}< \frac{1-\widetilde{S_{\textnormal{\textsf{\tiny large}}}}(-\theta^*)^{-1}} {1-\widetilde{S_{\textnormal{\textsf{\tiny small}}}}(-\theta^*)^{-1}}. \end{equation*} \end{theorem} Note that the asymptotic improvement regime in \cref{thm:asymptotic_constant} is a superset of the non-asymptotic improvement regime in \cref{thm:improvement_regime}, because $g_{\max}/g_{\min} \ge 1$. Thus, whenever \cref{thm:improvement_regime} guarantees a stochastic improvement, we also have $C_\mathsf{FCFS} > C_\mathsf{Nudge}$. Thus, by \cref{thm:existence_of_improvement}, there exists an asymptotic improvement whenever $s_{\min} = 0$. \begin{corollary}[Existence of Asymptotic Improvement] \label{cor:existence_of_asymptotic_improvement} For any continuous class I job size distribution $S$ with $s_{\min} = 0$ and any load $0<\rho<1$, there exist $x_1, x_2, x_3$ such that $C_\mathsf{Nudge} < C_\mathsf{FCFS}$. \end{corollary} While \cref{thm:asymptotic_constant} shows that there is a multiplicative improvement in the asymptotic tail, we find empirically that the same multiplicative improvement exists throughout nearly the entire tail. See \cref{fig:improvement_plot} and \cref{sec:empirical}. \subsection{Exact Analysis of Nudge} All of the above results compare Nudge's performance to that of FCFS. In particular, none of these results give an exact analysis of Nudge's response time. We give such an analysis in \cref{thm:transform}, in which we exactly derive $\widetilde{T^\mathsf{Nudge}}(s)$. This result is nontrivial, because Nudge does not fall into any class of policies with known analyses (see \cref{sub:prior_transform}). We prove \cref{thm:transform} in \cref{sec:transform}. \begin{theorem}[Transform of Response Time] \label{thm:transform} The response time of Nudge has Laplace-Stieltjes transform \begin{align*} \SwapAboveDisplaySkip \widetilde{T^\mathsf{Nudge}}(s) &= \widetilde{T^\mathsf{FCFS}}(s) + p_{\textnormal{\textsf{\tiny small}}} p_{\textnormal{\textsf{\tiny large}}} \left( \widetilde{S_{\textnormal{\textsf{\tiny large}}}}(s) (1 - \widetilde{S_{\textnormal{\textsf{\tiny small}}}}(s)) \left(\widetilde{T_Q^\mathsf{FCFS}}(\lambda + s) - \widetilde{T_Q^\mathsf{FCFS}}(s)\right) \rule{0pt}{2.2em} \right. \\[-0.8em] &\qquad \left. \rule{0pt}{2.2em} + \widetilde{S_{\textnormal{\textsf{\tiny small}}}}(s) (1 - \widetilde{S_{\textnormal{\textsf{\tiny large}}}}(s)) \left(\frac{\widetilde{T_Q^\mathsf{FCFS}}(s)}{\widetilde{S}(s)} - (1 - \rho)\frac{\lambda/\widetilde{S}(\lambda) - s/\widetilde{S}(s)}{\lambda - s}\right) \right). \end{align*} \end{theorem} \section{Proof of Theorem~\ref{thm:improvement_regime}: Stochastic Improvement Regime} \label{sec:proof_improvement_regime} Our goal in this section is to prove \cref{thm:improvement_regime}, which gives sufficient conditions on the parameters $x_1$, $x_2$, and~$x_3$ for Nudge to stochastically improve upon FCFS. To do so, we employ a tagged job approach. In particular, we follow an arbitrary tagged job~$i$ making its way through a pair of coupled systems, one employing the FCFS policy and one employing the Nudge policy, both with the same arrival process and job sizes. We focus on one particular response time threshold~$t$, and in particular on the events $D_{i, t}$ and $I_{i, t}$, where the tagged job~$i$ has response time greater than~$t$ in one system and below in the other system. In \eqref{eq:relationship_alg1_vs_fcfs}, we write the difference in the response time tails of Nudge and FCFS in terms of the events $D_{i, t}$ and $I_{i, t}$. In \cref{lem:calculation_of_PI_and_PD}, we derive formulas for the probabilities of these events. Using these formulas, in \cref{lem:single_threshold_improvement}, we derive a sufficient condition for Nudge to improve upon FCFS relative to a specific threshold~$t$. This sufficient condition is dependent on the threshold~$t$. In order to remove this dependence, we prove \cref{lem:A_B_c}, a technical lemma regarding arbitrary random variables. Finally, in \cref{sec:final_proof_improvement_regime}, we prove \cref{thm:improvement_regime}, by demonstrating that the conditions given in \cref{thm:improvement_regime} ensure that the sufficient condition in \cref{lem:single_threshold_improvement} holds relative to every response time threshold~$t$, making use of \cref{lem:A_B_c} to do so. \subsection{Intermediate Lemmas} \label{sub:proofs_of_lemmas} Consider a tagged job $i$ that arrives into the steady state of the pair of coupled systems. We write $T_i^{\mathsf{Nudge}}$ and $T_i^{\mathsf{FCFS}}$ for job~$i$'s response time in the Nudge and FCFS systems, respectively. For any $t \ge 0$, define the events \begin{equation*} I_{i,t} \triangleq \left\{T_i^{\mathsf{FCFS}} \le t < T_i^{\mathsf{Nudge}}\right\}, \qquad D_{i,t} \triangleq \left\{T_i^{\mathsf{Nudge}} \le t < T_i^{\mathsf{FCFS}}\right\}. \end{equation*} Intuitively, $D_{i,t}$ is the event in which Nudge \emph{decreases} job~$i$'s response time relative to FCFS, specifically from above~$t$ to below~$t$. Similarly, $I_{i,t}$ is the event in which Nudge \emph{increases} job~$i$'s response time relative to FCFS. We can write \begin{align} \label{eq:relationship_alg1_vs_fcfs} \P{T_i^{\mathsf{Nudge}} > t}=\P{T_i^{\mathsf{FCFS}} > t}+\P{I_{i,t}}-\P{D_{i,t}}. \end{align} The events $D_{i,t}$ and $I_{i,t}$ are defined using the Nudge and FCFS systems. Our next step is to express them in terms of only the FCFS system, which we understand well. We begin by defining the relevant quantities in the FCFS system. Let $i^-$ be the arrival immediately before job~$i$, and let $i^+$ be the arrival immediately after, and let \begin{align*} W_i &\triangleq \text{amount of work in the system (either Nudge or FCFS) when job~$i$ arrives,} \\ A_i &\triangleq \text{interarrival time between jobs~$i$ and~$i^+$,} \\ S_i &\triangleq \text{size of job~$i$.} \end{align*} We define analogous quantities for $i^-$ and~$i^+$. The work is the same in both systems because both Nudge and FCFS are work-conserving. Note that Nudge will only ever swap job~$i$ with one of the adjacent arrivals, $i^-$ or~$i^+$ (see \cref{sec:nudge_definition}). Under what condition do we swap job~$i$ with job~$i^+$? This happens if and only if the following events occur: \begin{enumerate} \item[(a)] Job~$i$ is large, which is when $x_2 \le S_i < x_3$. \item[(b)] Job~$i^+$ is small, which is when $S_{i^+} < x_1$. \item[(c)] Job~$i^+$ arrives before job~$i$ enters service in the Nudge system. \item[(d)] Job~$i$ has not swapped with any other job, namely job~$i^-$. \end{enumerate} Because job~$i$ cannot be both large and small, (a) implies~(d). But (d) implies that (c) happens when $A_i \leq W_i$. This is because in the absence of swaps, job~$i$ would enter service after $W_i$ time. Therefore, the event that job~$i$ swaps with job~$i^+$ is \begin{equation} \label{eq:swap_event} \mathsf{swap}_{i,i^+} \triangleq \{(x_2 \leq S_i < x_3) \ \wedge\ (S_{i^+} \leq x_1) \ \wedge\ (A_i \leq W_i)\}. \end{equation} Crucially, this definition of $\mathsf{swap}_{i,i^+}$ depends only on quantities in the FCFS system. We define $\mathsf{swap}_{i^-,i}$ analogously. \begin{lemma}[Evaluating $\P{I_{i,t}}$ and $\P{D_{i,t}}$] \label{lem:calculation_of_PI_and_PD} We have \begin{align} \P{I_{i,t}}&=\P{\mathsf{swap}_{i,i^+} \ \wedge\ (W_i+S_i \le t < W_i+S_i+S_{i^+})}, \label{eq:P I_i,t}\\ \P{D_{i,t}}&=\P{\mathsf{swap}_{i^-,i} \ \wedge\ (W_{i^-}-A_{i^-}+S_i \le t < W_{i^-}-A_{i^-}+S_i+S_{i^-})}. \label{eq:P D_i,t} \end{align} \end{lemma} \begin{proof} We begin by computing $\P{I_{i,t}}$. The event $I_{i,t}$ occurs only if $T_i^\mathsf{Nudge} > T_i^\mathsf{FCFS}$, which in turn occurs only if job~$i$ swaps with the next arrival, namely job~$i^+$. If this swap occurs, then $T_i^\mathsf{Nudge} = T_i^\mathsf{FCFS} + S_{i^+}$. We know that $T_i^\mathsf{FCFS} = W_i + S_i$, so \eqref{eq:P I_i,t} follows from \begin{align*} I_{i, t} &= \mathsf{swap}_{i,i^+} \ \wedge\ (T_i^\mathsf{FCFS} \leq t < T_i^\mathsf{Nudge}) \\ &= \mathsf{swap}_{i,i^+} \ \wedge\ (T_i^\mathsf{FCFS} \leq t < T_i^\mathsf{FCFS} + S_{i^+}) \\ &= \mathsf{swap}_{i,i^+} \ \wedge\ (W_i + S_i \leq t < W_i + S_i + S_{i^+}). \end{align*} We now compute $\P{D_{i,t}}$. By similar reasoning to the above, the event $D_{i,t}$ occurs only if job~$i$ swaps with job~$i^-$. If this swap occurs, then $T_i^\mathsf{Nudge} = T_i^\mathsf{FCFS} - S_{i^-}$. We again have $T_i^\mathsf{FCFS} = W_i + S_i$, so \begin{align*} D_{i, t} &= \mathsf{swap}_{i^-,i} \ \wedge\ (T_i^\mathsf{Nudge} \leq t < T_i^\mathsf{FCFS}) \\ &= \mathsf{swap}_{i^-,i} \ \wedge\ (T_i^\mathsf{FCFS} - S_{i^-} \leq t < T_i^\mathsf{FCFS}) \\ &= \mathsf{swap}_{i^-,i} \ \wedge\ (W_i + S_i - S_{i^-} \leq t < W_i + S_i). \end{align*} To obtain~\eqref{eq:P D_i,t}, observe that conditioned on $\mathsf{swap}_{i^-,i}$, we have $W_i = W_{i-} + S_{i^-} - A_{i^-}$. \end{proof} Now, we give sufficient conditions for Nudge to improve upon FCFS relative to a particular threshold~$t$. \begin{lemma}[Strict Improvement at a Given Threshold] \label{lem:single_threshold_improvement} Given any $t>s_{\min}$, where $s_{\min}$ is the smallest value of $S$, \begin{equation*} \P{T^{\mathsf{Nudge}} > t } < \P{T^{\mathsf{FCFS}} > t } \end{equation*} if the following inequality in terms of $t$ holds: \begin{align} \frac{g_{\max}}{g_{\min}}\frac{\lambda+\theta^*}{\lambda} < \frac{ \E{e^{\theta^*\min(t,S_{\textnormal{\textsf{\tiny small}}}+S_{\textnormal{\textsf{\tiny large}}})}- e^{\theta^*\min(t, S_{\textnormal{\textsf{\tiny small}}})}} }{ \E{e^{\theta^*\min(t,S_{\textnormal{\textsf{\tiny small}}}+S_{\textnormal{\textsf{\tiny large}}})}- e^{\theta^*\min(t, S_{\textnormal{\textsf{\tiny large}}})}} }. \label{ineq: improve for single t} \end{align} \end{lemma} \begin{proof} Because the tagged job~$i$ is a random sample arriving to the steady state of the system, by \cref{eq:relationship_alg1_vs_fcfs}, we have $\P{T^{\mathsf{Nudge}}> t} < \P{T^{\mathsf{FCFS}}> t}$ if and only if $\P{I_{i,t}} < \P{D_{i,t}}$. Our approach is to use \cref{lem:calculation_of_PI_and_PD} to bound each of $\P{I_{i,t}}$ and $\P{D_{i,t}}$, from which the desired sufficient condition follows. We begin by computing $\P{I_{i,t}}$: \begin{align*} \P{I_{i,t}} &= \P{\mathsf{swap}_{i,i^+} \ \wedge\ (W_i+S_i \le t < W_i+S_i+S_{i^+})} \tag*{\small [by \cref{lem:calculation_of_PI_and_PD}]}\\ &= \P{ \left(A_i\le W_i\right)\wedge \left(W_i+S_i\le t< W_i+S_i+S_{i^+}\right)\wedge \left(x_2\le S_i<x_3\right)\wedge \left(S_{i^+}<x_1\right)} \tag*{\small [by \eqref{eq:swap_event}]}\\ &\le \P{ \left(W_i+S_i\le t< W_i+S_i+S_{i^+}\right)\wedge \left(x_2\le S_i<x_3\right)\wedge \left(S_{i^+}<x_1\right)} \tag*{\small [discarding $A_i \leq W_i$]}\\ &= \P{\left((t-S_i-S_{i^+})^+\le W_i\le (t-S_{i})^+\right)\wedge \left(x_2\le S_i<x_3\right)\wedge \left(S_{i^+}<x_1\right)} \\ &= \plargep_{\textnormal{\textsf{\tiny small}}}\cdot \condE{S_i\sim S_{\textnormal{\textsf{\tiny large}}},S_{i^+}\sim S_{\textnormal{\textsf{\tiny small}}}}{\int_{w=(t-S_i-S_{i^+})^+}^{(t-S_{i})^+} f_{W_i}(w)\mathop{}\!\mathrm{d} w } \tag*{\small$\biggl[\parbox{13em}{change of measure for $S_i$ and $S_i^+$, independence of $S_i$, $S_{i^+}$, and~$W_i$}\biggr]$}\\ &\le \plargep_{\textnormal{\textsf{\tiny small}}}\cdot \condE{S_i\sim S_{\textnormal{\textsf{\tiny large}}},S_{i^+}\sim S_{\textnormal{\textsf{\tiny small}}}}{\int_{w=(t-S_i-S_{i^+})^+}^{(t-S_{i})^+} g_{\max}e^{-\theta^* w}\mathop{}\!\mathrm{d} w } \tag*{\small$\raisebox{0.15em}{$\biggl[$}\parbox{8.6em}{by \cref{lem:normalized_converges} and the fact that $W_i \sim T_Q^\mathsf{FCFS}$}\raisebox{0.15em}{$\biggr]$}$}\\ &= \plargep_{\textnormal{\textsf{\tiny small}}}\cdot \frac{e^{-\theta^* t}}{\theta^*}\cdot g_{\max} \E{e^{\theta^*\min(t,S_{\textnormal{\textsf{\tiny small}}}+S_{\textnormal{\textsf{\tiny large}}})}- e^{\theta^*\min(t, S_{\textnormal{\textsf{\tiny large}}})}}. \stepcounter{equation}\tag{\theequation} \label{eq:I_i_t_bound} \end{align*} % Similarly, we compute $\P{D_{i,t}}$: % \begin{align*} &\P{D_{i,t}} = \P{\mathsf{swap}_{i^-,i} \ \wedge\ (W_{i^-}-A_{i^-}+S_i \le t < W_{i^-}-A_{i^-}+S_i+S_{i^-})} \\ &=\P (A_{i^-}\le W_{i^-})\wedge (W_{i^-}-A_{i^-}+S_i\le t< W_{i^-}-A_{i^-}+S_i+S_{i^-}) \wedge (S_i<x_1)\wedge (x_2\le S_{i^-}<x_3) } \\ &=\P{\left(A_{i^-}+(t-S_i-S_{i^-})^+\le W_{i^-}\le A_{i^-}+(t-S_{i})^+\right)\ \wedge\ \left(S_i<x_1\right)\ \wedge\ \left(x_2\le S_{i^-}<x_3\right)} \\ &= p_{\textnormal{\textsf{\tiny small}}}p_{\textnormal{\textsf{\tiny large}}}\cdot \condE{S_i\sim S_{\textnormal{\textsf{\tiny small}}},S_{i^-}\sim S_{\textnormal{\textsf{\tiny large}}},A_{i^-}\sim \Exp(\lambda)} {\int_{w=A_{i^-}+(t-S_i-S_{i^-})^+}^{A_{i^-}+(t-S_{i})^+} f_{W_{i^-}}(w)\mathop{}\!\mathrm{d} w } \tag*{\small$\biggl[\parbox{8.6em}{mutual independence of $S_i$, $S_{i^+}$, $A_{i^-}$, and~$W_i$}\biggr]$}\\ &\ge p_{\textnormal{\textsf{\tiny small}}}p_{\textnormal{\textsf{\tiny large}}}\cdot \condE{S_i\sim S_{\textnormal{\textsf{\tiny small}}},S_{i^-}\sim S_{\textnormal{\textsf{\tiny large}}},A_{i^-}\sim \Exp(\lambda)} {\int_{w=A_{i^-}+(t-S_i-S_{i^-})^+}^{A_{i^-}+(t-S_{i})^+} g_{\min}e^{-\theta^*w}\mathop{}\!\mathrm{d} w } \tag*{\small$\raisebox{0.15em}{$\biggl[$}\parbox{8.6em}{by \cref{lem:normalized_converges} and the fact that $W_i \sim T_Q^\mathsf{FCFS}$}\raisebox{0.15em}{$\biggr]$}$}\\ &\ge p_{\textnormal{\textsf{\tiny small}}}p_{\textnormal{\textsf{\tiny large}}}\cdot \condE{S_i\sim S_{\textnormal{\textsf{\tiny small}}},S_{i^-}\sim S_{\textnormal{\textsf{\tiny large}}}} {\int_{a=0}^\infty \int_{w=a+(t-S_i-S_{i^-})^+}^{a+(t-S_{i})^+} g_{\min}e^{-\theta^*w} \cdot \lambda e^{-\lambda a} \mathop{}\!\mathrm{d} w \mathop{}\!\mathrm{d} a } \tag*{\small [$A_{i^-} \sim \Exp(\lambda)$]}\\ &= p_{\textnormal{\textsf{\tiny small}}}p_{\textnormal{\textsf{\tiny large}}}\cdot \frac{e^{-\theta^* t}}{\theta^*}\cdot g_{\min}\frac{\lambda}{\lambda+\theta^*} \E{e^{\theta^*\min(t,S_{\textnormal{\textsf{\tiny small}}}+S_{\textnormal{\textsf{\tiny large}}})}- e^{\theta^*\min(t, S_{\textnormal{\textsf{\tiny small}}})}}. \stepcounter{equation}\tag{\theequation} \label{eq:D_i_t_bound} \end{align*} Combining the bounds \eqref{eq:I_i_t_bound} and~\eqref{eq:D_i_t_bound}, we find that $\P{I_{i,t}} < \P{D_{i,t}}$ holds if \begin{equation} \label{ineq: improve last step} \mkern-22mu g_{\max} \E{e^{\theta^*\!\min(t,S_{\textnormal{\textsf{\tiny small}}}+S_{\textnormal{\textsf{\tiny large}}})}\!-\! e^{\theta^*\!\min(t, S_{\textnormal{\textsf{\tiny large}}})}}< g_{\min}\frac{\lambda}{\lambda\!+\!\theta^*} \E{e^{\theta^*\!\min(t,S_{\textnormal{\textsf{\tiny small}}}+S_{\textnormal{\textsf{\tiny large}}})}\!-\! e^{\theta^*\!\min(t, S_{\textnormal{\textsf{\tiny small}}})}}. \qedhere \end{equation} \end{proof} Having proven \cref{lem:single_threshold_improvement}, we have a sufficient condition, namely~\eqref{ineq: improve for single t}, for Nudge to improve upon FCFS at a specific value of~$t$. But our goal is to improve upon FCFS for \emph{all} values of~$t$. We therefore seek a condition which implies that \eqref{ineq: improve for single t} holds for all~$t$. We start by simplifying \eqref{ineq: improve for single t}. Let $A = e^{\theta^* S_{\textnormal{\textsf{\tiny small}}}}$, $B = e^{\theta^* S_{\textnormal{\textsf{\tiny large}}}}$, and $c=e^{\theta^* t}$. Then \eqref{ineq: improve for single t} becomes \begin{equation} \label{eq:A_B_c_motivation} \frac{g_{\max}}{g_{\min}}\frac{\lambda+\theta^*}{\lambda} < \frac{\E{\min(AB,c)-\min(A,c)}}{\E{\min(AB,c) - \min(B, c)}}. \end{equation} Here the only appearance of the specific value of~$t$ is via~$c$. Our strategy is to lower-bound the right-hand side of \eqref{eq:A_B_c_motivation} by a quantity that does not include~$c$. The following lemma, which we prove in \cref{app:normalized_converges}, helps accomplish this under an additional assumption. \begin{lemma} \label{lem:A_B_c} Let $A,B$ be two independent real-valued random variables and $c$ be a fixed constant. Suppose $1\le A\le c$ and $A<B$. Under these assumptions, if $\P{B>c}>0$ and $c\E{B}\ge \E{A}\E{B|B>c}$, then \begin{equation*} \frac{\E{\min(AB, c)- \min(A, c)}}{\E{\min(AB, c)-\min(B, c)}} = \frac{\E{\min(AB, c)-A}}{\E{\min(AB, c)-\min(B, c)}} \ge\frac{\E{AB-A}}{\E{AB-B}}. \end{equation*} \end{lemma} \subsection{Main Proof} \label{sec:final_proof_improvement_regime} \begin{reptheorem}{thm:improvement_regime} Suppose $S$ is a continuous class I job size distribution. Then $\mathsf{Nudge}(x_1, x_2, x_3)$ stochastically improves upon $\mathsf{FCFS}$ for any $s_{\min} < x_1\le x_2\le x_3$ satisfying \begin{align} \bullet\ \ &\frac{g_{\max}}{g_{\min}} \frac{\lambda+\theta^*}{\lambda}< \frac{1-\widetilde{S_{\textnormal{\textsf{\tiny large}}}}(-\theta^*)^{-1}} {1-\widetilde{S_{\textnormal{\textsf{\tiny small}}}}(-\theta^*)^{-1}}, \label{eq:repeat_gmax/gmin_<_function(x_1,x_2)}\\ \bullet\ \ &x_1+x_3\le 2x_2. \label{eq:repeat_x1_x2_x3_to_remove_t} \end{align} \end{reptheorem} \begin{proof} We prove \cref{thm:improvement_regime} by verifying the condition in \cref{lem:single_threshold_improvement}. For every $t>s_{\min}$, we will show that Inequalities~\eqref{eq:repeat_gmax/gmin_<_function(x_1,x_2)} and \eqref{eq:repeat_x1_x2_x3_to_remove_t} together imply \eqref{ineq: improve for single t}. \begin{enumerate}[(i)] \item When $s_{\min}< t\le x_2$, the denominator of the right hand side of \eqref{ineq: improve for single t} becomes \begin{equation*} \E{e^{\theta^*\min(t,S_{\textnormal{\textsf{\tiny small}}}+S_{\textnormal{\textsf{\tiny large}}})}- e^{\theta^*\min(t, S_{\textnormal{\textsf{\tiny large}}})}}=\E{e^t-e^t}=0. \end{equation*} Thus \eqref{ineq: improve for single t} is not well defined, but \eqref{ineq: improve last step} holds trivially, which is sufficient. \item When $x_2< t< x_3$, we let $A=e^{\theta^* S_{\textnormal{\textsf{\tiny small}}}},\ B=e^{\theta^* S_{\textnormal{\textsf{\tiny large}}}}$ and $c=e^{\theta^* t}$. Then clearly $1\le A\le c$ and $A<B$. By \eqref{eq:repeat_x1_x2_x3_to_remove_t}, we know that \begin{align*} c\E{B}&=e^{\theta^* t}\E{e^{\theta^*S_{\textnormal{\textsf{\tiny large}}}}}\ge e^{\theta^*(2x_2)} \ge e^{\theta^*(x_1+x_3)}\\ &\ge \E{e^{\theta^* (S_{\textnormal{\textsf{\tiny small}}}+S_{\textnormal{\textsf{\tiny large}}})}} \ge \E{e^{\theta^* \min(S_{\textnormal{\textsf{\tiny small}}}+S_{\textnormal{\textsf{\tiny large}}}, t)}} \ge \E{A}\E{B|B>c}. \end{align*} We can therefore apply \cref{lem:A_B_c} to obtain \begin{align} \frac{\E{e^{\theta^*\min(S_{\textnormal{\textsf{\tiny small}}}+S_{\textnormal{\textsf{\tiny large}}}, t)}-e^{\theta^* S_{\textnormal{\textsf{\tiny small}}}}}} {\E{e^{\theta^*\min(S_{\textnormal{\textsf{\tiny small}}}+S_{\textnormal{\textsf{\tiny large}}}, t)}-e^{\theta^* \min(S_{\textnormal{\textsf{\tiny large}}}, t)}}} \ge\frac{\E{e^{\theta^*(S_{\textnormal{\textsf{\tiny small}}}+S_{\textnormal{\textsf{\tiny large}}})}-e^{\theta^* S_{\textnormal{\textsf{\tiny small}}}}}} {\E{e^{\theta^* (S_{\textnormal{\textsf{\tiny small}}}+S_{\textnormal{\textsf{\tiny large}}})}-e^{\theta^* S_{\textnormal{\textsf{\tiny large}}}}}}. \label{eq:final_1} \end{align} Moreover, condition \eqref{eq:repeat_gmax/gmin_<_function(x_1,x_2)} implies that \begin{align} \frac{g_{\max}}{g_{\min}} \frac{\lambda+\theta^*}{\lambda} < \frac{1-\widetilde{S_{\textnormal{\textsf{\tiny large}}}}(-\theta^*)^{-1}} {1-\widetilde{S_{\textnormal{\textsf{\tiny small}}}}(-\theta^*)^{-1}} =\frac{\E{e^{\theta^*(S_{\textnormal{\textsf{\tiny small}}}+S_{\textnormal{\textsf{\tiny large}}})}-e^{\theta^* S_{\textnormal{\textsf{\tiny small}}}}}} {\E{e^{\theta^* (S_{\textnormal{\textsf{\tiny small}}}+S_{\textnormal{\textsf{\tiny large}}})}-e^{\theta^* S_{\textnormal{\textsf{\tiny large}}}}}} \label{eq:final_2} \end{align} Combining \eqref{eq:final_1} with \eqref{eq:final_2} establishes \eqref{ineq: improve for single t}. \item When $t\ge x_3$, we have $\min(t, S_{\textnormal{\textsf{\tiny small}}})=S_{\textnormal{\textsf{\tiny small}}}$ and $\min(t, S_{\textnormal{\textsf{\tiny large}}})=S_{\textnormal{\textsf{\tiny large}}}$. Therefore, condition~\eqref{eq:repeat_gmax/gmin_<_function(x_1,x_2)} is equivalent to \eqref{ineq: improve for single t}. \end{enumerate} Therefore, for every $t>s_{\min}$, we have proven that $\P{T^{\mathsf{Nudge}}> t}<\P{T^{\mathsf{FCFS}}> t}$. \end{proof} \section{Proof of Theorem~\ref{thm:existence_of_improvement}: Existence of Stochastic Improvement} \label{sec:proof_of_existence_of_improvement} \begin{reptheorem}{thm:existence_of_improvement} For any continuous class I job size distribution $S$ with $s_{\min} = 0$ and any load $0<\rho<1$, there exist $x_1, x_2, x_3$ satisfying \eqref{eq:repeat_gmax/gmin_<_function(x_1,x_2)} and~\eqref{eq:repeat_x1_x2_x3_to_remove_t}, implying that $\mathsf{Nudge}(x_1,x_2,x_3)$ stochastically improves upon $\mathsf{FCFS}$. \end{reptheorem} \begin{proof} We start by constructing $x_1,x_2,x_3$ that satisfy both Inequality \eqref{eq:repeat_gmax/gmin_<_function(x_1,x_2)} and \eqref{eq:repeat_x1_x2_x3_to_remove_t}. For notational convenience, let $M=\frac{g_{\max}}{g_{\min}} \frac{\lambda+\theta^*}{\lambda}$. First fix an arbitrary $x_3>0$ and let $x_2=\frac{3}{4} x_3$, then compute $\widetilde{S_{\textnormal{\textsf{\tiny large}}}}(-\theta^*)$ and choose a small enough $x_1$ such that \begin{align} x_1<\min\left\{ -\frac{1}{\theta^*}\ln\!\left( 1- \frac{1-\widetilde{S_{\textnormal{\textsf{\tiny large}}}}(-\theta^*)^{-1}}{M} \right),\frac{1}{2}x_3 \right\}. \label{eq:how_to_choose_x1} \end{align} Clearly, such $x_1 > s_{\min} = 0$ in \eqref{eq:how_to_choose_x1} exists because $M>1$, so we have \begin{align} \bullet\ \ &x_1+x_3< \frac{3}{2}x_3=2x_2, \label{ineq: satisfy condition 1}\\ \bullet\ \ & \frac{1-\widetilde{S_{\textnormal{\textsf{\tiny large}}}}(-\theta^*)^{-1}} {1-\widetilde{S_{\textnormal{\textsf{\tiny small}}}}(-\theta^*)^{-1}}=\frac{1-\widetilde{S_{\textnormal{\textsf{\tiny large}}}}(-\theta^*)^{-1}} {1-\E{e^{\theta^*S_{\textnormal{\textsf{\tiny small}}}}}^{-1}}\ge \frac{1-\widetilde{S_{\textnormal{\textsf{\tiny large}}}}(-\theta^*)^{-1}}{1-e^{-\theta^* x_1}}> M=\frac{g_{\max}}{g_{\min}} \frac{\lambda+\theta^*}{\lambda}. \label{ineq: satisfy condition 2} \end{align} By \cref{thm:improvement_regime}, \eqref{ineq: satisfy condition 1} and \eqref{ineq: satisfy condition 2} together imply that $\P{T^{\mathsf{Nudge}} \ge t } < \P{T^{\mathsf{FCFS}} \ge t }$ for every $t > s_{\min}=0$. Therefore, \begin{equation*} \forall t > 0,\quad\P{T^{\mathsf{Nudge}} > t } < \P{T^{\mathsf{FCFS}} > t }. \qedhere \end{equation*} \end{proof} \section{Proof of Theorem~\ref{thm:transform}: Transform of Response Time} \label{sec:transform} In this section we compute an exact formula for $\widetilde{T^\mathsf{Nudge}}(s)$. The formula holds for arbitrary job size distributions, not just those of class~I. At a high level, our analysis works by considering two systems experiencing identical arrivals: one using Nudge, and one using FCFS. We consider a tagged job arriving to this pair of systems in equilibrium and determine how its Nudge queueing time relates to its FCFS queueing time. \begin{itemize} \item \emph{Small jobs:} Nudge queueing time is FCFS queueing time, possibly minus a large job's size. \item \emph{Large jobs:} Nudge queueing time is FCFS queueing time, possibly plus a small job's size. \item \emph{Other jobs:} Nudge queueing time is identical to FCFS queueing time. \end{itemize} We will determine $\widetilde{T_{Q,\mathsf{small}}^\mathsf{Nudge}}(s)$ and $\widetilde{T_{Q,\mathsf{large}}^\mathsf{Nudge}}(s)$, from which $\widetilde{T^\mathsf{Nudge}}(s)$ easily follows. \subsection{Probabilistic Interpretation of the Laplace-Stieltjes Transform} Before jumping into the Nudge queueing time analysis, we recall a probabilistic interpretation of the Laplace-Stieltjes transform. Let $V$ be a nonnegative random variable. Consider a time interval of length~$V$ and a Poisson process of rate~$s$ that is independent of~$V$. We call the increments of the Poisson process ``interruptions''. Let $\nop{V}{s}$ be the event that there are no interruptions during the time interval. Then \citep[Exercise~25.7]{harchol-balter_performance_2013} \begin{equation} \label{eq:lst_nop} \widetilde{V}(s) = \P{\nop{V}{s}}. \end{equation} The interpretation in \eqref{eq:lst_nop} necessarily requires $s \geq 0$. Fortunately, formulas we derive using \eqref{eq:lst_nop} are still valid for $s < 0$ because Laplace transforms are uniquely defined by their value on any bounded interval on the real line \citep{chareka_finite-interval_2007}. \subsection{Transform for Large Jobs} \label{sec:transform_large} \begin{lemma} \label{lem:lst_large} The queueing time of large jobs under Nudge has Laplace-Stieltjes transform \begin{equation*} \widetilde{T_{Q,\mathsf{large}}^\mathsf{Nudge}}(s) = \bigl(1 - p_{\textnormal{\textsf{\tiny small}}}(1 - \widetilde{S_{\textnormal{\textsf{\tiny small}}}}(s))\bigr) \widetilde{T_Q^\mathsf{FCFS}}(s) + p_{\textnormal{\textsf{\tiny small}}}(1 - \widetilde{S_{\textnormal{\textsf{\tiny small}}}}(s)) \widetilde{T_Q^\mathsf{FCFS}}(\lambda + s). \end{equation*} \end{lemma} \begin{proof} Consider a large tagged job arriving to the pair of systems, one using Nudge and the other using FCFS, in equilibrium. We can think of the job's Nudge queueing time as the time it takes to do the following two steps: \begin{enumerate} \item[(a)] We first wait for its FCFS queueing time, namely~$T_Q^\mathsf{FCFS}$. \item[(b)] If during that $T_Q^\mathsf{FCFS}$ time there has been at least one arrival, and if the first such arrival is a small job, we then wait for that small job's service, which takes $S_{\textnormal{\textsf{\tiny small}}}$ time. Note that the small job's size is independent of the FCFS queueing time. \end{enumerate} We will use \eqref{eq:lst_nop} to compute $\widetilde{T_{Q,\mathsf{large}}^\mathsf{Nudge}}(s)$. To that end, we associate each of the Nudge and FCFS systems with a Poisson ``interruption'' process of rate~$s$. The interruption processes are independent of the arrival times and job sizes of each system, but they are coupled to each other in the following way. At any moment in time when the systems are busy, some job~$j$ has been in service for some amount of time~$t$. We couple the interruption processes such that interruptions occur at the same $(j, t)$ pairs in both systems. By \eqref{eq:lst_nop}, $\widetilde{T_{Q,\mathsf{large}}^\mathsf{Nudge}}(s)$ is the probability that no interruptions occur during steps~(a) and~(b). We compute this probability by conditioning on the following event: \begin{equation*} E = \left\{\text{\parbox{18em}{the next arrival after the tagged job is small, and an interruption occurs during its service}}\right\} \end{equation*} Note that $E$ does not consider whether the next arrival occurs before the tagged job exits the queue. Therefore, it is independent of the length $T_Q^\mathsf{FCFS}$ of step~(a). If $E$ does not occur, then there are no interruptions during step~(b). Therefore, there are no interruptions if and only if there are no interruptions during step~(a). By~\eqref{eq:lst_nop}, this happens with probability $\widetilde{T_Q^\mathsf{FCFS}}(s)$. If $E$ does occur, then an interruption will occur during step~(b) if and only if a new job arrives during step~(a). That is, by conditioning on~$E$, we have predetermined that the next arrival will be small and, if it swaps with the tagged job, will cause an interruption. Therefore, to avoid interruptions, we need to avoid interruptions \emph{and arrivals} during step~(a). Merging the arrival and interruption processes yields a Poisson process of rate $\lambda + s$, so avoiding interruptions corresponds to the event $\nop{T_Q^\mathsf{FCFS}}{\lambda + s}$. By~\eqref{eq:lst_nop}, this happens with probability $\widetilde{T_Q^\mathsf{FCFS}}(\lambda + s)$. Conditioning on whether $E$ occurs and using \eqref{eq:lst_nop} to compute $\P{E} = p_{\textnormal{\textsf{\tiny small}}}(1 - \widetilde{S_{\textnormal{\textsf{\tiny small}}}}(s))$, we obtain the desired expression. \end{proof} \subsection{Transform for Small Jobs} \label{sec:transform_small} \begin{lemma} \label{lem:lst_small} The queueing time of small jobs under Nudge has Laplace-Stieltjes transform \begin{equation*} \widetilde{T_{Q, \mathsf{small}}^\mathsf{Nudge}}(s) = \widetilde{T_Q^\mathsf{FCFS}}(s) \left(1 + \frac{p_{\textnormal{\textsf{\tiny large}}}(1 - \widetilde{S_{\textnormal{\textsf{\tiny large}}}}(s))}{\widetilde{S}(s)}\right) - p_{\textnormal{\textsf{\tiny large}}}(1 - \widetilde{S_{\textnormal{\textsf{\tiny large}}}}(s))(1 - \rho) \cdot \frac{\lambda/\widetilde{S}(\lambda) - s/\widetilde{S}(s)}{\lambda - s}. \end{equation*} \end{lemma} The analysis of small jobs is more involved than the analysis of large jobs. We therefore state and prove several more intermediate results before proving \cref{lem:lst_small}. Consider a small tagged job arriving to the pair of systems, one using Nudge and the other using FCFS, in equilibrium. The main question we need to answer is whether the tagged job will swap with a large job in the Nudge system. Our main insight is that we can tell whether the swap will occur by examining just the FCFS system. Because we understand FCFS well, this makes it relatively simple to tell whether a swap will occur. \begin{lemma} \label{lem:swap_fcfs} The small tagged job swaps with a large job in the Nudge system if and only if, when it arrives, the FCFS system has a nonempty queue whose last job is large. \end{lemma} The proof of \cref{lem:swap_fcfs} follows very similar reasoning to our analysis at the start of \cref{sub:proofs_of_lemmas}. For completeness, we provide a proof in \cref{app:transform_proofs}. Thanks to \cref{lem:swap_fcfs}, we can determine the queueing time of the small tagged job by looking at the state of the FCFS system when it arrives. We describe the equilibrium state of the FCFS system with the following quantities: \begin{itemize} \item $W$: the amount of work in the system. \item $N_Q$: the number of jobs in the queue. \item $W_{\mathsf{most}}$: the amount of work in the system, excluding the last job in the queue if $N_Q \geq 1$. \item $S_{\mathsf{last}}$: the size of the last job in the queue, or $0$ if $N_Q = 0$. \end{itemize} Note that these quantities are not independent. In particular, $W = W_{\mathsf{most}} + S_{\mathsf{last}}$. However, $W_{\mathsf{most}}$ and $S_{\mathsf{last}}$ are \emph{conditionally} independent given $N_Q \geq 1$. Armed with \cref{lem:swap_fcfs} and the system state notation, we are ready to compute $T_{Q, \mathsf{small}}^\mathsf{Nudge}(s)$, thus proving \cref{lem:lst_small}. Our computation will make use of an additional lemma which we state after the proof and prove in \cref{app:transform_proofs}. \begin{proof}[Proof of \cref{lem:lst_small}] Consider the small tagged job arriving to the pair of systems in equilibrium. By \cref{lem:swap_fcfs}, its Nudge queueing time is \begin{equation*} T_{Q, \mathsf{small}}^\mathsf{Nudge} = \begin{cases} W_{\mathsf{most}} & \text{if } N_Q = 0 \\ W_{\mathsf{most}} + S_{\mathsf{last}} \mathbf{1}(\lnot(x_2 \leq S_{\mathsf{last}} < x_3)) & \text{if } N_Q \geq 1. \end{cases} \end{equation*} Applying \eqref{eq:lst_nop} and the conditional independence of $W_{\mathsf{most}}$ and $S_{\mathsf{last}}$ yields \begin{align*} \widetilde{T_{Q, \mathsf{small}}^\mathsf{Nudge}}(s) &= \P{\nop{W_{\mathsf{most}}}{s} \ \land\ N_Q = 0} \\ &\quad + \P{\nop{W_{\mathsf{most}}}{s} \ \land\ N_Q \geq 1 \ \land\ (\nop{S_{\mathsf{last}}}{s} \ \lor\ x_2 \leq S_{\mathsf{last}} < x_3)} \\ &= \P{\nop{W_{\mathsf{most}}}{s} \ \land\ N_Q = 0} \\ \stepcounter{equation}\tag{\theequation} \label{eq:lst_small_progress} &\quad + \P{\nop{W_{\mathsf{most}}}{s} \ \land\ N_Q \geq 1} \cdot \bigl(\widetilde{S}(s) + p_{\textnormal{\textsf{\tiny large}}}(1 - \widetilde{S_{\textnormal{\textsf{\tiny large}}}}(s))\bigr). \end{align*} It remains only to compute the two probabilities in \eqref{eq:lst_small_progress}. Let \begin{equation} \label{eq:lst_small_q_0} q \triangleq \P{\nop{W}{s} \ \land\ N_Q = 0} = \P{\nop{W_{\mathsf{most}}}{s} \ \land\ N_Q = 0}, \end{equation} making $q$ the first probability in \eqref{eq:lst_small_progress}. We now compute the second probability in \eqref{eq:lst_small_progress} in terms of~$q$. First, note that $T_Q^\mathsf{FCFS}$ and $W$ are identically distributed. Recalling the conditional independence of $W_{\mathsf{most}}$ and $S_{\mathsf{last}}$, we have, using \eqref{eq:lst_nop} throughout, \begin{align*} \MoveEqLeft \widetilde{T_Q^\mathsf{FCFS}}(s) - q = \widetilde{W}(s) - q = \P{\nop{W}{s} \ \land\ N_Q \geq 1} \\ &= \P{\nop{W_{\mathsf{most}}}{s} \ \land\ N_Q \geq 1 \ \land\ \nop{S_{\mathsf{last}}}{s}} \\ \stepcounter{equation}\tag{\theequation} \label{eq:lst_small_q_1} &= \P{\nop{W_{\mathsf{most}}}{s} \ \land\ N_Q \geq 1} \cdot \widetilde{S}(s). \end{align*} Plugging \eqref{eq:lst_small_q_0} and \eqref{eq:lst_small_q_1} into \eqref{eq:lst_small_progress} yields \begin{equation*} \widetilde{T_{Q, \mathsf{small}}^\mathsf{Nudge}}(s) = q + \bigl(\widetilde{T_Q^\mathsf{FCFS}}(s) - q\bigr)\left(1 + \frac{p_{\textnormal{\textsf{\tiny large}}}(1 - \widetilde{S_{\textnormal{\textsf{\tiny large}}}}(s))}{\widetilde{S}(s)}\right). \end{equation*} \Cref{lem:lst_small_q} below, proven in \cref{app:transform_proofs}, computes the value of~$q$, yielding the desired result. \end{proof} \begin{lemma} \label{lem:lst_small_q} Let $q \triangleq \P{\nop{W}{s} \ \land\ N_Q = 0}$. We have \begin{equation*} q = \widetilde{T_Q^\mathsf{FCFS}}(\lambda) \cdot \frac{\lambda \widetilde{S}(s) - s \widetilde{S}(\lambda)}{\lambda - s} = \frac{1 - \rho}{\widetilde{S}(\lambda)} \cdot \frac{\lambda \widetilde{S}(s) - s \widetilde{S}(\lambda)}{\lambda - s}. \end{equation*} \end{lemma} \subsection{Overall Response Time Transform} \begin{reptheorem}{thm:transform} The response time of Nudge has Laplace-Stieltjes transform \begin{align*} \SwapAboveDisplaySkip \widetilde{T^\mathsf{Nudge}}(s) &= \widetilde{T^\mathsf{FCFS}}(s) + p_{\textnormal{\textsf{\tiny small}}} p_{\textnormal{\textsf{\tiny large}}} \left( \widetilde{S_{\textnormal{\textsf{\tiny large}}}}(s) (1 - \widetilde{S_{\textnormal{\textsf{\tiny small}}}}(s)) \left(\widetilde{T_Q^\mathsf{FCFS}}(\lambda + s) - \widetilde{T_Q^\mathsf{FCFS}}(s)\right) \rule{0pt}{2.5em} \right. \\[-0.75em] &\qquad \left. \rule{0pt}{2.5em} + \widetilde{S_{\textnormal{\textsf{\tiny small}}}}(s) (1 - \widetilde{S_{\textnormal{\textsf{\tiny large}}}}(s)) \left(\frac{\widetilde{T_Q^\mathsf{FCFS}}(s)}{\widetilde{S}(s)} - (1 - \rho)\frac{\lambda/\widetilde{S}(\lambda) - s/\widetilde{S}(s)}{\lambda - s}\right) \right). \end{align*} \end{reptheorem} \begin{proof} The expression follows by plugging the results of \cref{lem:lst_small,lem:lst_large} into \begin{align*} \widetilde{T^\mathsf{Nudge}}(s) &= p_{\textnormal{\textsf{\tiny small}}} \cdot \widetilde{T_{Q,\mathsf{small}}^\mathsf{Nudge}}(s) \cdot \widetilde{S_{\textnormal{\textsf{\tiny small}}}}(s) + p_{\textnormal{\textsf{\tiny large}}} \cdot \widetilde{T_{Q,\mathsf{large}}^\mathsf{Nudge}}(s) \cdot \widetilde{S_{\textnormal{\textsf{\tiny large}}}}(s)\\ &\quad + (1 - p_{\textnormal{\textsf{\tiny small}}} - p_{\textnormal{\textsf{\tiny large}}}) \cdot \widetilde{T_Q^\mathsf{FCFS}}(s) \cdot \frac{\widetilde{S}(s) - p_{\textnormal{\textsf{\tiny small}}} \widetilde{S_{\textnormal{\textsf{\tiny small}}}}(s) - p_{\textnormal{\textsf{\tiny large}}} \widetilde{S_{\textnormal{\textsf{\tiny large}}}}(s)}{1 - p_{\textnormal{\textsf{\tiny small}}} - p_{\textnormal{\textsf{\tiny large}}}} \end{align*} and simplifying the resulting expression. One key step is recognizing $\widetilde{T^\mathsf{FCFS}}(s) = \widetilde{T_Q^\mathsf{FCFS}}(s) \cdot \widetilde{S}(s)$. \end{proof} \section{Proof of Theorem~\ref{thm:asymptotic_constant}: Asymptotic Improvement} \label{sec:proof_of_asymptotic_constant} \begin{reptheorem}{thm:asymptotic_constant} Suppose $S$ is a continuous class I job size distribution. For any $s_{\min} < x_1 \leq x_2 \leq x_3$, the asymptotic tail improvement ratio of $\mathsf{Nudge}(x_1, x_2, x_3)$ compared to $\mathsf{FCFS}$ is \begin{equation*} \mathsf{AsymTIR} = p_{\textnormal{\textsf{\tiny small}}}p_{\textnormal{\textsf{\tiny large}}} \frac{\lambda}{\lambda+\theta^*}\left( \widetilde{S_{\textnormal{\textsf{\tiny large}}}}(-\theta^*) -\frac{\lambda}{\lambda+\theta^*} \widetilde{S_{\textnormal{\textsf{\tiny small}}}}(-\theta^*) -\frac{\theta^*}{\lambda+\theta^*} \widetilde{S_{\textnormal{\textsf{\tiny large}}}}(-\theta^*)\widetilde{S_{\textnormal{\textsf{\tiny small}}}}(-\theta^*) \right). \end{equation*} Furthermore, $\mathsf{AsymTIR}$ is positive, meaning $C_\mathsf{Nudge} < C_\mathsf{FCFS}$, if \begin{equation*} \frac{\lambda+\theta^*}{\lambda}< \frac{1-\widetilde{S_{\textnormal{\textsf{\tiny large}}}}(-\theta^*)^{-1}} {1-\widetilde{S_{\textnormal{\textsf{\tiny small}}}}(-\theta^*)^{-1}}. \end{equation*} \end{reptheorem} Below we give a high-level overview of the proof. We provide full computations in \cref{app:transform_proofs}. \begin{proof}[Proof sketch] Using the Final Value Theorem, one can show that for $\mathsf{Alg} \in \{\mathsf{Nudge}, \mathsf{FCFS}\}$, \begin{equation*} C_\mathsf{Alg} = \frac{1}{\theta^*}\lim_{s \to 0} s\widetilde{T^\mathsf{Alg}}(s - \theta^*). \end{equation*} Combining this with \cref{thm:transform}, which relates $\widetilde{T^\mathsf{Nudge}}(s)$ to $\widetilde{T^\mathsf{FCFS}}(s)$, will relate $C_\mathsf{Nudge}$ to $C_\mathsf{FCFS}$. To obtain $\mathsf{AsymTIR} = 1 - C_\mathsf{Nudge}/C_\mathsf{FCFS}$, we compute $\lim_{s \to 0} (s\widetilde{T^\mathsf{FCFS}}(s - \theta^*) - s\widetilde{T^\mathsf{Nudge}}(s - \theta^*))$ via \cref{thm:transform}. Each non-vanishing term has an $sT^\mathsf{FCFS}_Q(s - \theta^*)$ factor. Because $\widetilde{T^\mathsf{FCFS}_Q}(s) = \widetilde{T^\mathsf{FCFS}}(s)/\widetilde{S}(s)$, we can express $C_\mathsf{FCFS} - C_\mathsf{Nudge}$ as a constant times $C_\mathsf{FCFS}$; this constant is $\mathsf{AsymTIR}$. \end{proof} \section{Empirical Lessons} \label{sec:empirical} This paper proves that Nudge stochastically improves upon FCFS under the correct choice of parameters, and achieves multiplicative improvement in the asymptotic tail. However, there are a few practical questions remaining. These questions center around finding Nudge parameters in practice. In this section, we demonstrate several practical lessons on choosing Nudge parameters. \begin{enumerate} \item (\cref{sec:how_set_nudge_parameters}) We find that Nudge typically achieves its greatest improvement over FCFS when the Nudge parameters specify that all jobs are either large or small (i.e. $x_1 = x_2$, $x_3 = \infty$). \item (\cref{sec:empirical_low_load}) We find that when load is low, Nudge can dramatically improve upon FCFS (10-20\%) in the common case where job size variability is relatively high (i.e. $C^2 > 1$). When job size variability is lower and load is low, improvement is smaller \item (\cref{sec:stochastic_asymptotic_connection}) We find that the space of parameters that lead Nudge to {\em asymptotically} improve upon FCFS typically also cause Nudge to {\em stochastically} improve upon FCFS. This is serendipitous, because \cref{thm:asymptotic_constant} provides a simple, exact method to check whether given Nudge parameters will achieve asymptotic improvement over FCFS. \end{enumerate} \subsection{All Jobs Should Be Either Large or Small} \label{sec:how_set_nudge_parameters} When evaluating Nudge on common job size distributions, we have found that the greatest improvement over FCFS is achieved by setting the Nudge parameters such that all jobs are either large or small (i.e. $x_1 = x_2$, $x_3 = \infty$), with no medium or very large jobs. This is a pattern we have seen with great consistency across a variety of job size distributions. \begin{figure}[t] \centering \includegraphics[width=\linewidth]{improvement_hyperexp.pdf} \caption{Empirical tail improvement of Nudge over FCFS under a variety of Nudge parameter choices. Highest improvement occurs when $x_1 = x_2$, $x_3 = \infty$. Job size distribution is hyperexponential with branches drawn from $\Exp(2)$ and $\Exp(1/3)$, where the first branch has probability $0.8$. $\E{S} = 1$, $C^2 = 3$. Simulations run with 10 billion arrivals. Load $\rho = 0.8$. Parameter choices are listed in order of asymptotic improvement.} \label{fig:how_set_nudge_parameters} \end{figure} In \cref{fig:how_set_nudge_parameters}, we show one instance of this pattern, for the case of a particular hyperexponential distribution. We see that the two choices of Nudge parameters that display the {\em least} improvement over FCFS are those where both medium and very large jobs exist, i.e. $x_1 \neq x_2$ and $x_3 \neq \infty$. To explain this phenomenon, note that when we remove medium and very large jobs, we end up with more swaps. Empirically, we have found that the \emph{quantity} of swaps is more important than the \emph{quality} of those swaps, and thus maximizing the number of swaps leads to the largest improvement. While empirically removing medium and very large jobs improves performance, our analytical result in \cref{thm:existence_of_improvement} requires medium and very large jobs. Setting the Nudge parameters so that all jobs are either large or small dramatically simplifies the problem of choosing Nudge parameters, in addition to achieving consistently strong performance. Now, only {\em one free parameter} remains: the cutoff between small and large jobs. \subsection{Low Load: Dramatic Improvement when Variability is High} \label{sec:empirical_low_load} At low load, Nudge has the potential for dramatic improvement over FCFS (>10\% throughout the tail), in the common case where the job size distribution is more variable than an exponential distribution, i.e. $C^2 > 1$. On the other hand, under low-variability job size distributions ($C^2 < 1$), we find that Nudge's improvement shrinks at lower loads; here it helps to set the $x_1$ cutoff close to $0$. \begin{figure}[t] \centering \includegraphics[width=\linewidth]{improvement_load_by_variance.pdf} {\small (a) High variance: $C^2 > 1$; $x_1 = x_2 = 1$, $x_3 = \infty$ \hspace{10pt} (b) Low variance: $C^2 < 1$; $x_1 = x_2 = 0.2$, $x_3 = \infty$\vspace{-5pt}} \caption{ Empirical tail improvement of Nudge over FCFS at low load ($\rho = 0.4$) under a variety of job size distributions with $\E{S} = 1$. (a) Higher variance distributions show dramatic improvement. (b) Lower variance distributions show modest improvement. Specific distributions: In (a), Mixed Uniform: Uniform($0,1$) w/prob. $0.9$, else Uniform($0,11$), $C^2 = 3.33$; Hyperexponential: $\Exp(2)$ w/ prob. $0.8$, else $\Exp(1/3)$, $C^2 = 3$; ChiSquared(1), $C^2 = 2$; InverseGaussian($\mu=1, \lambda=1/2$), $C^2 = 2$. In (b), Triangle w/ $\min=0$, mode~$=0$, $\max=3$, $C^2 = 1/2$; Uniform($0, 2$), $C^2 = 1/3$; Erlang($k=3$, $\lambda=1/3$, $C^2 = 1/3$; Beta($\alpha = 2, \beta = 2$) scaled by a factor of 2, $C^2 = 1/5$. Distributions listed in order of asymptotic improvement. Simulations run with 10 billion arrivals.} \label{fig:empirical_low_load} \end{figure} In \cref{fig:empirical_low_load} we show these patterns for a wide variety of distributions at relatively low load $\rho = 0.4$. In \cref{fig:empirical_low_load}(a), we have four high-variance job size distributions, each with $C^2 \in [2, 3.33]$. In every case, Nudge dramatically improves upon FCFS, with TIR in the range of 10-15\%. In \cref{fig:empirical_low_load}(b), we have four low-variance job size distributions, each with $C^2 \in [1/5, 1/2]$. In these cases, we reduce the cutoff $x_1$ to $0.2$ for best performance, and Nudge's improvement over FCFS is under 3\%. Intuitively, when load is low, each job waits behind fewer other jobs on average, so Nudge's one swap per job has a greater relative impact. When those swaps are broadly beneficial for the tail, as occurs when job size variance is high, Nudge achieves the most dramatic improvement over FCFS. When job size variance is low, swaps involving small jobs that are near the mean job size cause the response time of the large jobs to suffer too much. To alleviate this, we reduce the small job cutoff $x_1$ to maintain stochastic improvement over FCFS. \subsection{Asymptotic Improvement Means Stochastic Improvement} \label{sec:stochastic_asymptotic_connection} After extensively simulating Nudge under different loads and job size distributions, we have found that the space of parameters under which Nudge asymptotically improves upon FCFS typically matches the space under which Nudge stochastically improves upon FCFS. \begin{table}[t] \centering \setlength\tabcolsep{0.9pt} \begin{tabular}{|c|ccc|ccc|ccc|ccc|ccc|} \hline Job size dist. & $x_1$ & Asym. & Stoc. & $x_1$ & Asym. & Stoc. & $x_1$ & Asym. & Stoc. & $x_1$ & Asym. & Stoc. & $x_1$ & Asym. & Stoc.\\ \hline Exponential & $0.5$ & \checkmark & \checkmark & $1$ & \checkmark & \checkmark & $2$ & $\times$ & $\times$ & $4$ & $\times$ & $\times$ & $8$ & $\times$ & $\times$ \\ \hline Hyperexponential & $0.5$ & \checkmark & \checkmark & $1$ & \checkmark & \checkmark & $2$ & \checkmark & \checkmark & $4$ & \checkmark & \checkmark & $8$ & \checkmark & \checkmark \\ \hline Bounded Lomax & $0.5$ & \checkmark & \checkmark & $1$ & \checkmark & \checkmark & $1.5$ & $\times$ & $\times$ & $2$ & $\times$ & $\times$ & $3$ & $\times$ & $\times$ \\ \hline Uniform & $0.1$ & \checkmark & \checkmark & $0.2$ & \checkmark & \checkmark & $0.5$ & $\times$ & $\times$ & $0.75$ & $\times$ & $\times$ & $1$ & $\times$ & $\times$ \\ \hline Beta & $0.1$ & \checkmark & \checkmark & $0.2$ & \checkmark & \checkmark & $0.3$ & $\times$ & $\times$ & $0.4$ & $\times$ & $\times$ & $0.5$ & $\times$ & $\times$ \\ \hline \end{tabular} \caption{Presence or absence of asymptotic and stochastic improvement of Nudge over FCFS under a variety of job size distributions and Nudge parameter choices. Stochastic improvement occurs whenever asymptotic improvement occurs. Each row gives a distinct job size distribution, and each cell gives a distinct Nudge parameter setting. In every case, $x_2 = x_1$ and $x_3 = \infty$, so only $x_1$ is specified. Load $\rho = 0.4$. Specific job size distributions, each with mean 1: Exponential with mean 1, Uniform(0, 2), Hyperexponential drawn from $\Exp(2)$ w/ prob. $0.8$ and $\Exp(1/3)$ with prob. $0.2$, BoundedLomax($\lambda = 2, \max=4, \alpha=2$), Beta($\alpha=2, \beta=2$) scaled by a factor of 2.} \label{tab:asymptotic_implies_stochastic} \end{table} In \cref{tab:asymptotic_implies_stochastic}, we show the consistency of this relationship across a wide variety of job size distributions and choices of Nudge parameters. The distributions range from a low-variance Beta distribution with $C^2 = 1/5$ to a hyperexponential distribution with $C^2 = 3$. Across the spectrum, Nudge stochastically improves over FCFS whenever it asymptotically improves over FCFS. This connection between asymptotic and stochastic improvement is surprising given that the conditions that we need to prove stochastic improvement (\cref{thm:improvement_regime}) are much more stringent than what we need to prove asymptotic improvement (\cref{thm:asymptotic_constant}). Nonetheless, the connection is highly useful because we have provided a simple analytical formula for determining when Nudge asymptotically improves upon FCFS (\cref{thm:asymptotic_constant}). \section{Nudge in practice} \label{sec:nudge_in_practice} Nudge can be used in practice even if some of the assumptions made in this paper are not perfectly satisfied. In this paper, we assume that exact job size information is known to the scheduler. However, such information is only used to determine which size class (small, large, etc.) a job should be placed in. In practice, only estimates of job size may be known. In such a setting, the scheduler could assign jobs that are clearly above or below a size threshold to the large and small classes, while placing ambiguous jobs in the medium class. If the estimates are reasonably accurate, we would expect such a Nudge policy to stochastically improve upon FCFS. We also assume that the exact job size distribution is known to the scheduler. This assumption is needed to choose the Nudge parameters for our proofs in \cref{sec:main_results}. However, our empirical results in \cref{sec:empirical} show that much less information is needed in practice to choose good Nudge parameters. For instance, as we saw in \cref{sec:empirical_low_load}, the following choice of parameters works well empirically: By default, set $x_1 = x_2 = E[S], x_3 = \infty$. However, if load is low and job size variability ($C^2$) is low, set $x_1 = x_2 = E[S]/5, x_3 = \infty$. \section{Variants on Nudge} \label{sec:nudge_variants} As Nudge is such a simple policy, there are many interesting variants of Nudge that one could investigate. We now discuss the advisability of several such variants. Recall that Nudge only ever swaps a job at most once. One might consider allowing a job to swap a second or third time with new arrivals, or even an unlimited number of times. Unfortunately, this change could ruin Nudge's stochastic improvement over FCFS, if implemented poorly. In particular, under a Nudge variant where large jobs can be swapped with an unlimited number of small arrivals, such highly-swapped large jobs will typically dominate the response time tail, dramatically worsening the variant's tail performance. A wiser variant might be to allow large jobs to be swapped with a bounded number of small jobs, or to allow only the small jobs to be swapped an unlimited number of times. Another interesting variant of Nudge would only swap in a probabilistic fashion, such as with an i.i.d. coin flip. We believe such a policy could achieve stochastic improvement over FCFS. However, proving such a result would be no simpler than for Nudge, because probabilistic swapping does not change the shape of the distribution of swaps. Moreover, the variant's tail improvement ratios would likely be smaller than those of Nudge, because a smaller fraction of jobs are involved in swaps. Finally, one could design a more complicated variant of Nudge which would consider a job's exact size when deciding whether to swap, rather than simply comparing the job's size to a threshold. For instance, one might decide to swap all pairs of jobs whose sizes differ by a factor of 2, as long as neither job has yet been swapped. These more complicated Nudge variants might achieve even larger stochastic improvements over FCFS than Nudge. Beyond FCFS, such Nudge variants might be able to stochastically improve upon some or even all Nudge policies. We leave this possibility as an open question. \section{Conclusion} We introduce Nudge, the first scheduling policy whose response time distribution stochastically improves upon that of FCFS. Specifically, we prove that with appropriately chosen parameters, Nudge stochastically improves upon FCFS for light-tailed job size distributions% \footnote{% More specifically, continuous class I job size distributions with positive density at 0.% }. From an asymptotic viewpoint, we prove that Nudge achieves a multiplicative improvement over FCFS, disproving the strong asymptotic optimality conjecture for FCFS. Finally, we derive the Laplace-Stieltjes transform of response time under Nudge, using a novel technique. Nudge is simple to implement and is a practical drop-in replacement for FCFS when job sizes are known. One of the major insights of this paper is that improving the tail does not follow the same intuitions that we use in improving the mean. While improving mean response time is often a matter of helping small jobs jump ahead of large ones, when it comes to the tail, this has to be done in a very measured way. Too much help to the small jobs causes the tail to get a lot worse. Nudge finds the exactly appropriate way to do this. One direction for future work is further exploring the stochastic improvement frontier. Can we stochastically improve upon other commonly used scheduling policies? Can we improve upon Nudge itself, such as with a more complicated variant of Nudge (see \cref{sec:nudge_variants})? One policy which cannot be stochastically improved upon is SRPT, due to its optimal mean response time. Can we prove that other policies are unimprovable? Another direction is simplifying the definition of Nudge. Our empirical results in \cref{sec:empirical} indicate that in practice, Nudge can always stochastically improve upon FCFS with only two classes of jobs: small and large. It would be of practical importance to figure out how to extend the theorems in this paper to hold for this simplified definition of Nudge. \section*{Acknowledgements} We thank Sem Borst and the anonymous referees for their helpful comments. This research was supported by NSF-CMMI-1938909, NSF-CSR-1763701, and a Google 2020 Faculty Research Award. \bibliographystyle{ACM-Reference-Format}
{'timestamp': '2021-06-04T02:06:14', 'yymm': '2106', 'arxiv_id': '2106.01492', 'language': 'en', 'url': 'https://arxiv.org/abs/2106.01492'}
arxiv
\section{Experimental Details} \label{appendix:details} \subsection{Long-Context Sequence Modelling} \label{appendix:lra} \input{tables/lra_hyperparam} For all tasks except Retrieval, we closely follow the model configurations in \citet{tay2021long} such as data preprocessing, data split, model architecture, batch size etc. To guarantee convergence, we train models for the Retrieval task with 20k steps instead of the 5k steps prescribed in\citet{tay2021long}. The hyperparameters of models in these tasks are listed in Table~\ref{tab:lra_hyperpara}. We mainly tune three hyperparameters: learning rate, dropout and attention dropout. For the other main hyperparametrs such as batch size, number of layers and number of warmup steps, we follow the guidance of \citet{tay2021long}. \subsection{Neural Machine Translation} \label{appendix:nmt} Our experiments on WMT 2014 English-German are based on the Transformer-base model \citep{vaswani2017attention}, with implementation from the FairSeq package~\citep{ott2019fairseq}. This dataset contains 4.5M parallel sentence pairs for training. We following the standard setting~\citep{vaswani2017attention}, using Newstest2013 as the validation set and Newstest2014 as the test set. The dataset is pre-processed following \citep{ma2020apollo}, using the scripts from FairSeq package\footnote{\url{https://github.com/pytorch/fairseq}}. Specifically, we use word embedding with 512 dimension and 6-layer encoder/decoder with 8 multi-head attention and 2048 feed-forward dimensions. We apply 0.1 label smoothing~\citep{szegedy2016rethinking}, and perform totally $500,000$ updates to train each model. For Adam, we use start learning rate $0.0005$, set $\beta=(0.9, 0.98)$, and apply the decoupled weight decay technique (AdamW)~\citep{loshchilov2019decoupled}. For all the models trained with \textsc{Apollo}, we set the learning rate is $0.1$, $\beta=0.9$ and $\epsilon=1e^{-4}$. For learning rate scheduling, we applied linear warm up the learning rate for both Adam, and \textsc{Apollo} --- $4000$ updates for Adam and $1000$ updates and \textsc{Apollo}. After learning rate warming up, we applied the inverse square root decay~\citep{vaswani2017attention} to Adam. For \textsc{Apollo}, following \citet{ma2020apollo}, we decayed the learning rate at the $300,000$ and $450,000$ updates by decay rate 0.1. Gradient clips with 1.0 are applied to all the optimization methods, and the dropout ratio are set to $0.1$. Weight decay rates are $1e^{-4}$ for Adam methods and $1e^{-8}$ for \textsc{Apollo}. The decoding beam size is set to 5, and the checkpoints of the last 10 epochs are averaged before evaluation. For each experiment, we conducted distributed training across eight NVIDIA Tesla V100 GPUs with maximum batch size as 8192 tokens per GPU (totally $8192\times 8$ tokens per batch). \subsection{Masked Language Modeling for Large-Scale Pretraining and Finetuing} \label{appendix:mlm} \input{tables/pretrain_hyperparam} We pre-trained all the models on 64 Tesla V100 GPUs with the standard masked-language-modeling (MLM) objective and two pre-training corpus: (i)BERT version with BookCorpus~\citep{zhu2015aligning} and English Wikipedia (totally 16GB); (ii) RoBERTa version with BookCorpus, English Wikipedia, CC-News~\citep{nagel2016cc}, OpenWebText~\citep{gokaslan2019openwebtext} and Stories~\citep{trinh2018simple} (totally 160GB). We use the standard Adam optimizer with a linear decay learning rate scheduler. Table~\ref{tab:pretrain_hyper} describes the hyperparameters for pre-training of Luna-128 model. For finetuning stage, we closely follow the training configuration used in released Roberta finetuning script for different tasks and main hyperparameters are listed in Table~\ref{tab:hyp:finetune}. \section*{Checklist} \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? \answerNo{} \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? \answerNA{} \item Did you include complete proofs of all theoretical results? \answerNA{} \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)? \answerYes{} \item Did you specify all the training details (e.g., data splits, hyperparameters, how they were chosen)? \answerYes{} \item Did you report error bars (e.g., with respect to the random seed after running experiments multiple times)? \answerYes{} \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)? \answerYes{} \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? \answerYes{} \item Did you mention the license of the assets? \answerNo{} \item Did you include any new assets either in the supplemental material or as a URL? \answerYes{} \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} \label{sec:conclusion} We have introduced Luna, a simple, efficient and effective linear attention mechanism used as a drop-in substitute for regular softmax attention. By introducing an extra input with the fixed length, Luna is capable of capturing adequate contextual information while performing attention operations linearly. On three sequence modeling tasks, i.e., long-context sequence modeling, neural machine translation, and large-scale pretraining and finetuning, Luna achieves comparable or even better performance than a variety of strong baselines, while acquiring prominent gains of efficiency in both speed and memory. In future work, we are interested in combining Luna with recurrence methods where $P$ can be used as a running memory across segments of inputs. Another interesting direction would be to apply Luna to other tasks with long input sequences, such as document-level summarization and translation. \section{Experiments} \label{sec:experiment} \subsection{Long-Context Sequence Modeling} We evaluate the effectiveness and efficiency of Luna on the Long Range Arena (LRA) benchmark recently introduced by~\citet{tay2021long}, which is designed for the purpose of evaluating efficient Transformer models under the long-context scenario. They collect five tasks in this benchmark which are ListOps~\citep{nangia2018listops}, byte-level text classification (Text;~\citealp{maas2011learning}), byte-level document retrieval (Retrieval; ~\citealp{radev2013acl}), image classification on sequences of pixels (Image;~\citealp{krizhevsky2009learning}) and Pathfinder~\citep{NEURIPS2018_ec895663}. These tasks consist of input sequences ranging from 1K to 8K tokens and span across a variety of data types and modalities. To ensure fair comparisons, for all tasks except for the task Retrieval, we closely follow the model configurations in \citet{tay2021long} such as data preprocessing, data split, model architecture, etc. For the task of Retrieval, we find that models are not fully converged when being trained for 5K steps as stated in~\citet{tay2021long}. Therefore, we train models for 20K steps for this task and obtain much better results. For a direct comparison, besides the average performance of models across all tasks, we also report the average accuracy on tasks excluding Retrieval. We run each experiment for five times with different random seeds and report the average accuracy. The hyper-parameters for each task are shown in Appendix~\ref{appendix:lra}. \vspace{-2mm} \paragraph{Results.} The results of various models on the LRA benchmark are presented in Table~\ref{tab:lra_rst}. For our proposed method, we report results from models of three different projected dimensions (16, 128 and 256). First, we note that Luna achieves good results on all tasks consistently compared to the Transformer model and significantly outperforms all the other baseline methods in terms of the average accuracy. By taking a closer look at the accuracy for each individual task, Luna wins over baseline models on three out of five tasks and performs comparably with the best performed model on the other two tasks, i.e. ListOps and byte-level text classification. Notably, Luna improves over the Transformer model on image classification and pathfinder by a large margin. Second, we observe that although Luna achieves the best average performance with a projection dimension of 256, it also performs considerably well with smaller projection dimensions (16 and 128). This demonstrates the effectiveness of Luna even with small projected dimensions. \input{tables/lra_efficiency} \vspace{-2mm} \paragraph{Memory and Speed Efficiency.} Luna employs two nested linear attention functions to reduce the time and memory complexity compared to the vanilla softmax attention. Here, we examine the speed and memory footprint of various models with varying input lengths (1K, 2K, 3K and 4K). Following~\citet{tay2021long}, all models are evaluated on the byte-level classification task with the same batch size. The result is shown in Table~\ref{tab:lra_efficiency}. Considering the memory efficiency, Luna with a projected dimension of 16 is highly memory-efficient, which is only 10\% of the vanilla Transformer at 4K input sequence length. With larger projected dimensions, i.e.~128 and 256, Luna requires more memory but is still competitive compared to other efficient Transformer models. In terms of time efficiency, Luna-16 speeds up over the standard Transformer by 1.2-5.5 times, varying by the sequence length. Compared to other efficient Transformers, Luna-16 performs comparably with the fastest models, i.e.~Performer and Linformer. Overall, our models achieve competitive advantage both in time- and memory-efficiency over other models, while attaining the best performance on the LRA benchmark (see Figure~\ref{fig:lra}). In addition, we plot the trade-off among memory, time and averaged LRA score without task Retrieval in Figure~\ref{fig:lra}. Models such as Linformer and Performer have faster speed and small memory requirement with the sacrifice of performance. However, besides competitive time- and memory-efficiency, Luna models retain superior performance even with a small projected dimension ($l$=16). \input{tables/lra_usep} \vspace{-2mm} \paragraph{Contextual information in $P$ of Luna.} Recently, a popular method to model the classification task using Transformer-based models is to prepend a special symbol, [CLS], to every input example. The last hidden state of this symbol is regarded as the aggregate sequence representation. In Luna, we introduce an extra model input $P$ which not only allows us to efficiently compute the attention mechanism but learn contextual information as well. Theoretically, the $P$ from the last layer is capable of learning the representation of the input sequence. To validate this, we extract $P$ at the last layer and employ the mean pooling strategy over positions to obtain the final feature for classification. We test its performance on three long-text modeling tasks in LRA~\citep{tay2021long}, i.e., ListOps, Text and Retrieval and report results in Table~\ref{tab:lra_usep_rst}. We find that $P$-based methods obtain better scores across all tasks against the [CLS]-based one, validating the powerful ability of $P$ to encode contextual information of the input sequence. \input{tables/luna_mt} \subsection{Machine translation} \label{subsec:nmt} To evaluate Luna on sequence-to-sequence modeling, we conduct experiments on a standard machine translation benchmark, i.e.~WMT'14 English-German (EN$\rightarrow$DE) dataset (4.5M sentence pairs). The data split and preprocessing steps follow those of~\citet{vaswani2017attention}, using the scripts from FairSeq~\citep{ott2019fairseq}. We share the source and target vocabularies within the language pair, with 37K byte pair encoding (BPE) types~\citep{sennrich2016neural}. The Luna models closely follow the architecture of Transformer-base: 6 encoder and decoder layers with 8 attention heads and $d_{\textrm{model}}/d_{\textrm{hidden}}=512/2048$. We train the Transformer-base model with two optimization methods: Adam~\citep{kingma2015adam} and Apollo~\citep{ma2020apollo}, and find Apollo achieves better performance. Therefore, we use Apollo as the optimizer for all Luna models. For each experiment, we conduct distributed training across eight NVIDIA Tesla V100 GPUs with maximum batch size of 8192 tokens per GPU. Further details are provided in Appendix~\ref{appendix:nmt}. \vspace{-2mm} \paragraph{Results.} Table~\ref{tab:nmt} presents the results of Luna on the test set BLEU scores of WMT'14 EN$\rightarrow$DE, along with Transformer-base and Random Feature Attention (RFA) as baselines. Different from~\citet{peng2021random} where the random feature attention is applied only to decoders, the RFA model in Table~\ref{tab:nmt} applies random feature attention in both the encoder and decoder for a fair comparison. $k=256$ is the number of feature maps in RFA. For Luna, we report performance of models with different projected lengths: $l=16$ and $l=32$, different activation functions in \eqref{eq:causal}: $\mathrm{elu}(\cdot) + 1$ and $\mathrm{softplus}(\cdot)$, and w./w.o parameter sharing. From Table~\ref{tab:nmt}, the first observation is that $\mathrm{softplus}(\cdot)$ consistently outperforms $\mathrm{elu}(\cdot) + 1$. Thus, we use $\mathrm{softplus}(\cdot)$ as the default activation function in the implementation. Another interesting observation is that Luna with a small projected length ($l=16$) obtains similar performance to RFA with $k=256$ feature maps. Luna with $l=32$ achieves competitive performance, but still falls behind the Transformer-base model. Further improving the machine translation performance of Luna is left to future work. We also report the number of parameters of different models. At last, we evaluate Luna w./w.o parameter sharing. Although there are two sets of parameters in a single Luna attention function ($W_Q, \,\, W_K, \,\, W_V$), as mentioned in \S\ref{subsec:nested_attention}, we tie $W_{k}$ with $W_{v}$ to reduce the number of parameters, and the performance decline is marginal. As a result, Luna with shared parameters has 7\% and 5\% more parameters compared to the vanilla Transformer and RFA models. \input{tables/luna_mt_context} \paragraph{Effect of Encoding Contextual Information into $P$.} As discussed in \S\ref{subsec:discussion}, one advantage of Luna against Linformer is to incorporate contextual $P$ by formulating it as an extra input. To investigate the importance of this design, we conduct experiments on WMT'14 to compare Luna with the baseline model where $P$ is formulated as a non-contextual learnable parameter of each layer. For both the contextual and non-contextual models, we train Luna with $l=16$, parameter sharing and $\mathrm{softplus}$. Table~\ref{tab:nmt:context} lists the BLEU scores on the development and test sets. Luna with contextual $P$ significantly outperforms the baseline with non-contextual $P$, demonstrating the effectiveness of this design in Luna. \subsection{Masked Language Modeling for Large-Scale Pretraining} One popular application of Transformer is to pretrain a large-scale language model on a large amount of data which can then be fine-tuned on a wide range of downstream tasks, such as BERT~\citep{devlin2019bert}, RoBERTa~\citep{liu2019roberta}, etc. Therefore, we pretrain a Luna-based language model with RoBERTa-base model configuration on two versions of data as our pretraining set: 1) BERT version with BookCorpus~\citep{zhu2015aligning} and English Wikipedia (totally 16GB), 2) RoBERTa version with BookCorpus, English Wikipedia, CC-News~\citep{nagel2016cc}, OpenWebText~\citep{gokaslan2019openwebtext} and Stories~\citep{trinh2018simple} (totally 160GB). For Luna models, we set $l=128$. On the larger training corpus (160GB), we train models w./w.o parameter sharing, respectively. We compare our models with RoBERTa-base, BERT-base and Linformer which are trained on the same training data. Experimental details are provided in Appendix~\ref{appendix:mlm}. \vspace{-2mm} \paragraph{Finetuning Luna} After obtaining the pretrained Luna-based language model, we finetune it on various natural language processing tasks, including sentiment classification (SST-2;~\citealp{socher2013recursive}), natural language inference (QNLI;~\citealp{rajpurkar2016squad}), textual similarity (QQP;~\citealp{chen2018quora}, question answering (RACE~\citep{lai2017race} and CommonsenseQA (CSQA;~\citealp{talmor2019commonsenseqa}). For GLUE tasks, following \citet{liu2019roberta}, we consider a limited hyperparameter sweep for each task, with batch sizes $\in \{16, 32\}$ and learning rate $\in \{5e^{-6}, 1e^{-5}, 2e^{-5}\}$, with a linear warmup for the first 6\% of steps followed by a linear decay to $0$. Finetuning is performed for 20 epochs with early stopping based on each task’s evaluation metric on the dev set\footnote{We observed that Luna finetuning requires more epochs than vanilla Transformer (20 vs. 10). We also finetuned RoBERTa with 20 epochs but did not obtain better results.}. For QA tasks, we concatenate each candidate answer with the corresponding question and passage. We then encode every candidate and pass the [CLS] output at the last layer through a fully-connected layer, which is used to predict the correct answer. We truncate question-answer pairs that are longer than 128 tokens and, if needed, the passage so that the total length is at most 512 tokens. Following \citet{liu2019roberta}, we try a small range of possible values for hyperparameters, i.e., batch size $\in \{16, 32\}$, learning rate $\in \{1e^{-5}, 2e^{-5}, 3e^{-5}\}$ and dropout $\in \{0.0, 0.1, 0.2\}$. For other configurations such as warm-up steps, optimizer, we follow thoses in \citet{liu2019roberta}. The result is reported in Table~\ref{tab:bert_rst}. We observe that on the smaller dataset (16GB) our Luna model has similar or slightly better downstream results compared to other pretrained language models. On QNLI and SST-2, Luna models obtain the best performance among all models, reaffirming the effectiveness of Luna in pre-training. This demonstrates the strong ability of Luna for language representations. On the larger dataset (160GB), however, the performance of Luna is slightly worse than RoBERTa with vanilla Transformer architecture. One possible reason is that the capacity of Luna is not as sufficient as vanilla Transformer, due to the efficient attention mechanism. This is supported by the evidence that Luna with full sets of parameters achieves better performance than that with parameter-sharing, because Luna with full sets of parameters has better capacity. \input{tables/luna_bert} \section{Linear Unified Nested Attention (Luna)} \label{sec:luna} Our goal is to design an efficient attention mechanism to solve the quadratic complexity problem of full attention. We first introduce the proposed \emph{linear unified nested attention} mechanism, named \emph{Luna attention} (\S\ref{subsec:nested_attention}), and the architecture of each Luna layer (\S\ref{subsec:luna_layer}). Then, we present the variant of Luna for causal attention, named \emph{Luna causal attention} (\S\ref{subsec:luna_causal}). Finally, we discuss the differences between Luna and three closely related models: Linformer~\citep{wang2019learning}, Set Transformer~\citep{lee2019set} (\S\ref{subsec:discussion}) and Shared Workspace~\citep{goyal2021coordination}. \vspace{-1mm} \subsection{Pack and Unpack Attention} \label{subsec:nested_attention} \vspace{-1mm} The key idea behind Luna is to decouple the regular attention function in \eqref{eq:attention} into two nested attention operations, both of which have linear efficiency. To achieve this, besides the original query and context input sequences, Luna introduces an extra input that is a sequence with fixed (constant) length. With this extra input as the query sequence, Luna uses its first attention, named \emph{pack attention}, to pack the context sequence into a fixed-length sequence. Formally, let $P \in \mathbb{R}^{l\times d}$ denote the extra input sequence with fixed length $l$. The pack attention first packs $C$ to $Y_P$ with $P$ as the query sequence: \begin{equation}\label{eq:pack_attention} Y_P = \mathrm{Attn}(P, C) \end{equation} where $\mathrm{Attn}(\cdot, \cdot)$ is the regular attention function in \eqref{eq:attention}, $C \in \mathbb{R}^{m\times d}$ is the context sequence, and $Y_P \in \mathbb{R}^{l\times d}$ is the output of the pack attention, which is named the \textit{packed context}. Since the length of $P$ is a constant $l$, the complexity of pack attention is $O(lm)$, which is linear with respect to $m$. To unpack the sequence back to the length of the original query sequence $X$, Luna leverages its second attention, named \emph{unpack attention}: \begin{equation}\label{eq:unpack_attention} Y_X = \mathrm{Attn}(X, Y_P) \end{equation} where $X \in \mathbb{R}^{n\times d}$ is the original query sequence. Similar to pack attention, the complexity of unpack attention is $O(ln)$, which is also linear with repect to $n$. \vspace{-2mm} \paragraph{Encoding Contextual Information in $P$.} The next question is where the extra input sequence $P$ comes from. One straightforward choice is to format $P$ as a learnable parameter of each Luna layer. One obvious drawback of this method, however, is that $P$ would not capture any contextual information. To enhance the capacity of the Luna model, we propose to formulate $Y_P$ as an additional output of each Luna layer, corresponding to $P$. Formally, the Luna attention function $\mathrm{LunaAttn}(\cdot, \cdot, \cdot)$ takes three sequences as input and generates two sequence as output: \begin{equation}\label{eq:luna_attention} Y_X, Y_P = \mathrm{LunaAttn}(X, P, C) \end{equation} where the computation of $Y_P$ and $Y_X$ is in \eqref{eq:pack_attention} and \eqref{eq:unpack_attention}. By stacking multiple layers of Luna attention, the output $Y_P$ from the previous layer, which captures contextual information of $C$, is employed as the input $P$ of the next layer. For the first layer of Luna, we formulate $P$ as learnable positional embeddings\footnote{We also experimented with sinusoidal positional embeddings, and obtained similar results.}~\citep{vaswani2017attention}. \vspace{-2mm} \paragraph{Reducing the Number of Parameters.} Due to the two nested attention operations, there are two sets of parameters ($W_Q, \,\, W_K, \,\, W_V$) in a single Luna attention function. There are several techniques to reduce the number of parameters, such as parameter sharing~\citep{xia2019tied}. In this work, we follow \citet{wang2020linformer} to share $W_K$ and $W_Q$ in each layer, and conduct experiments to analyze performance decline against Luna with full sets of parameters (\S\ref{subsec:nmt}). \subsection{Luna Layers} \label{subsec:luna_layer} The Luna attention is used as a drop-in-replacement for the regular attention. We incorporate the position-wise feed-forward network and layer normalization into Luna layers. Concretely, layer normalization is applied to both $Y_X$ and $Y_P$, while FFN only to $Y_X$: \begin{equation}\label{eq:luna} \begin{array}{rcl} Y_X, Y_P & = & \mathrm{LunaAttn}(X, P, C) \\ X_{A}, P_{A} & = & \mathrm{LayerNorm}(Y_X + X), \,\, \mathrm{LayerNorm}(Y_P + P) \\ X', P' & = & \mathrm{LayerNorm}(\mathrm{FFN}(X_A) + X_A), \,\, P_A \end{array} \end{equation} where $X'$ and $P'$ are the two outputs of the Luna layer. The graphical specification of one Luna layer is illustrated in Figure~\ref{fig:luna}. \subsection{Luna Causal Attention} \label{subsec:luna_causal} As discussed in \citet{tay2020efficient}, the ability to support causal autoregressive decoding, i.e. attending solely to the past and current tokens, is required when designing efficient self-attention mechanisms. However, due to the pack attention that packs the long sequence $X$ into a fixed (shorter) length, it is not straight-forward to support causal attention in Luna. To design causal attention in Luna, we need to assume that the input $P$ contains no information of $X$, i.e. $P$ will not leak any future information of $X$ to the history. Before we describe the Luna causal attention mechanism, we first define a causal function $f: \mathbb{R}^{n\times d_1} \times \mathbb{R}^{n\times d_1} \times \mathbb{R}^{n\times d_2} \rightarrow \mathbb{R}^{n\times d_2}$: \begin{equation}\label{eq:causal} F \triangleq f(X, Y, Z), \,\, \textrm{where} \,\, F_t = \frac{1}{t} X_t \sum\limits_{j=1}^{t} Y_j^T Z_j \end{equation} where $F \in \mathbb{R}^{n\times d_2}$ and $F_t$ denotes the $t$-th row of $F$. From the definition of $f$ in \eqref{eq:causal}, we see that $F_t$ can only access the information of the past and present row of $X$, $Y$ and $Z$. To perform Luna causal attention, we first compute the attention matrix of the pack attention: $A_{pack} = \omega(PX^T/\sqrt{d})$. For simplicity, we omit the learnable parameters, e.g. $W_Q, \,\, W_K, \,\, W_V$ in \eqref{eq:attention}. Note that for $A_{pack}$, we cannot use the softmax function for $\omega$, as the normalization term in softmax leaks future information of $X$ to the history. Inspired by the causal attention mechanism in Linear Transformer~\citep{katharopoulos2020transformers}, we use two activation functions: 1) $\omega(\cdot)=\mathrm{elu}(\cdot) + 1$ based on the exponential linear unit~\citep{clevert2016elu}; 2) $\omega(\cdot)=\mathrm{softplus}(\cdot)$ based on the \emph{softplus} function~\citep{glorot2011deep}. With the causal function $f$ in \eqref{eq:causal}, we compute the attention matrix of the unpack attention: $A_{unpack} = \omega(f(X, X, A_{pack}^T))$. Unlike $A_{pack}$, we can use $\omega(\cdot) = \mathrm{softmax}(\cdot)$ for $A_{unpack}$, because the normalization is along the $l$-dimension rather than the $n$-dimension of $X$. Finally, the output Y is computed by $Y = f(A_{unpack}, A_{pack}^T, X)$. The complexity of the causal attention in Luna is still linear: $O(ln)$. One drawback of Luna causal attention, similar to the causal attention in Random Feature Attention (RFA)~\citep{peng2021random} and Linear Transformer~\citep{katharopoulos2020transformers}, is its sequential computation for each timestep $t$. \vspace{-2mm} \paragraph{The sources of $P$.} In the formulation of causal attention, $P$ is expected to contain no information about $X$. Thus, we need to formulate $P$ based on the usage mode of the causal attention. For the \emph{encoder-decoder} mode in sequence-to-sequence modeling (e.g. for machine translation), we can use packed output from the Luna encoder as $P$. For the \emph{decoder-only} mode (e.g. for language modeling), $P$ might be formulated as a learnable parameter of each layer. \subsection{Discussion} \label{subsec:discussion} \paragraph{Relation to Linformer and Shared Workspace.} One previous work closely related to Luna is Linformer~\citep{wang2019learning}. Linformer linearly projects the context sequence $C \in \mathbb{R}^{m\times d}$ into a sequence with fixed length $l$: $C'=EC$, where $C' \in \mathbb{R}^{l\times d}$ is the projected context sequence and $E \in \mathbb{R}^{l\times m}$ is the learnable projection matrix of each layer. Then, the attention operation is applied on the query $X$ and the projected context $C'$. The pack attention in Luna is a generalization of the linear projection in Linformer. There are two main advantages to Luna over Linformer: i) with pack attention as the projection method, Luna is able to model sequences with various lengths. In contrast, Linformer requires the length of all input sequences to be the same $m$, due to the projection matrix $E$, whose shape depends on $m$. ii) Luna achieves better expressiveness than Linear, not only due to the general projection method but also by encoding adequate contextual information into the projection via $P$ (see~\S\ref{subsec:nested_attention}). Experimental improvements over non-contextual projection demonstrate the effectiveness of Luna (see \S\ref{subsec:nmt}). In contemporaneous and individual work, \citet{goyal2021coordination} formulate contextual $p$ as a shared global workspace, which shares similar instantiation with Luna. \vspace{-2mm} \paragraph{Relation to Set Transformer.} The additional input $P$ in Luna can be regarded as a side memory module that can access the entire sequence to gather contextual information. From this view of point, Luna is also closely related to Set Transformer~\citep{lee2019set}, an early model to integrate side memory module in Transformers. Similar to the projection matrix in Linformer, the \emph{inducing points} in Set Transformer are learnable parameters. Thus, these inducing points might be formulated as the non-contextual version of $P$ in Luna. Moreover, Set Transformer is designed for \emph{set-input} problems, which are problems wherein the input is a set of features and the model is thereby invariant to permutation or ordering of the input features~\citep{tay2020efficient}, while Luna attention is used as a drop-in replacement for regular softmax attention. \section{Related Work} \label{sec:related} There has been signficiant prior work on improving the efficiency of Transformers, besides the three closely related works discussed in \S\ref{subsec:discussion}. The common techniques include, but are not limited to, weight sharing~\citep{dehghani2018universal}, quantization~\citep{shen2020q,fan2020training}, sparse attention~\citep{parmar2018image,kitaev2020reformer}, side memory module~\citep{lee2019set,gupta2020gmat,goyal2021coordination}, and low-rank or compressed context~\citep{wang2019learning,ainslie2020etc}. In this section, we briefly review some recently proposed methods. For a detailed overview we refer the readers to \citet{tay2020efficient}. \paragraph{Sparse Attention} The general idea of these methods is that, instead of attending to the whole sequence, each token only access to a fixed, predefined range such as local neighborhoods and strided or “dilated” windows. Popular methods include local attention~\citep{parmar2018image}, blockwise attention~\citep{qiu2019blockwise}, strided attention patterns~\citep{child2019generating,beltagy2020longformer}, and compressed attention~\citep{liu2018generating}. To make this range more flexible, Reformer~\citep{kitaev2020reformer} employs a hash-based similarity measure to efficiently cluster tokens into chunks and Routing Transformer\citep{roy2021efficient} employ online k-means clustering on the tokens. The Sinkhorn sorting Network~\citep{tay2020sparse} exposes the sparsity in attention weights by learning to sort blocks of the input sequence. \paragraph{Kernel Methods. } A recently popular method to improve the efficiency of Transformers is to avoid explicitly computing the $m\times n$ attention matrix $A$ in \eqref{eq:attention} by re-writing it with kernels. Typical models leveraging kernelization are Linear Transformer~\citep{katharopoulos2020transformers}, Performer~\citep{choromanski2020rethinking} and Random Feature Attention~\citep{peng2021random}. Since kernels are a form of approximation of the attention matrix, they can be also viewed as a form of low-rank method~\citep{choromanski2020rethinking} that compresses the context to a shorter length, such as Linformer~\citep{wang2019learning} and the proposed Luna model. \paragraph{Recurrence.} The simplest technique to reduce the complexity of Transformer is to chunk input sequences into fixed blocks, with the obvious disadvantage of losing contextual information from past chunks. As discussed in \citet{tay2020efficient}, these models can be regarded as \emph{fixed pattern} models. Transformer-XL~\citep{dai2019transformer} proposed a natural extension to the blockwise method to connect these blocks via a recurrence mechanism. Compressive Transformer~\citep{rae2020compressive} further extends Transformer-XL by maintaining a fine-grained memory of past chunk activations, which are discarded in Transformer-XL. Technically, Luna can be adapted to a recurrence method, by simply using $P$ as an inherent memory module to maintain the recurrence across segments. \section{Introduction} \vspace{-1mm} Transformers~\citep{vaswani2017attention} are surprisingly versatile models that preform well on a wide range of language and vision tasks, including machine translation~\citep{vaswani2017attention,ott2018scaling}, language understanding~\citep{devlin2019bert}, image recognition~\citep{dosovitskiy2020image} and bioinformatics~\citep{madani2020progen}. Attention~\citep{bahdanau2015neural} provides the key mechanism that captures contextual information from the entire sequence by modeling pairwise interactions between the inputs at every timestep. However, a common weakness of Transformers is their quadratic time and memory complexity within the attention mechanism w.r.t the length of the input sequence, which prohibitively restricts their potential application to tasks requiring longer input sequences. A number of techniques have been recently introduced to improve the time and memory efficiency of Transformer models (\emph{`xformers'})~\citep{tay2020efficient,tay2021long}. One popular technique is using sparsity to restrict the attention field range, such as local attention~\citep{parmar2018image}, blockwise attention~\citep{qiu2019blockwise}, strided attention patterns~\citep{child2019generating,beltagy2020longformer}, compressed attention~\citep{liu2018generating}, and attention with learnable patterns~\citep{kitaev2020reformer,tay2020sparse,roy2021efficient}. Another emerging approach is to improve efficiency by leveraging low-rank approximations of the attention matrix. Linformer~\citep{wang2020linformer}, for example, projects the length dimension of key and value matrices to a fixed-dimensional representation by assuming low-rank structure in the full-rank attention matrix. Recently, some kernel-based methods, such as Linear Transformer~\citep{katharopoulos2020transformers}, Performer~\citep{choromanski2020rethinking} and Random Feature Attention~\citep{peng2021random}, attempt to efficiently approximate regular (softmax) full-rank attention through kernelization. Although these models demonstrate better \emph{asymptotic} complexity for long sequences, their efficiency gains are less prominent for moderate length sequences and their performance remains behind Transformers with regular attention. In this work, we propose \emph{a linear unified nested attention mechanism} (\textbf{Luna}), which uses two nested attention functions to approximate the regular softmax attention in Transformer (\S\ref{sec:background}). Specifically, with the first attention function, Luna packs the input sequence into a sequence of fixed length. Then, the packed sequence is unpacked using the second attention function (\S\ref{subsec:nested_attention}). As compared to a more traditional attention mechanism, Luna introduces an additional sequence with a fixed length as input and an additional corresponding output. Importantly, the extra input allows Luna to perform attention operation linearly as efficiently as Linformer~\citep{wang2020linformer}, while also storing adequate contextual information. Unlike Linformer, Luna is capable of modeling variable-length sequences and autoregressive (causal) attention (\S\ref{subsec:discussion}). We perform extensive experiments on three sequence modeling tasks, including long-context sequence modeling, neural machine translation, and masked language modeling for large-scale pretraining and downstream task finetuning. Compared to a variety of strong baseline models, Luna achieves competitive or even better performance, while acquiring prominent gains of efficiency in both speed and memory (see Figure~\ref{fig:lra}). More importantly, Luna manages to obtain superior performance with small projection lengths such as 16 (\S\ref{sec:experiment}). \vspace{-2mm} \section{Background} \label{sec:background} \vspace{-1mm} \vspace{-1mm} \subsection{Attention} \vspace{-1mm} The traditional attention mechanism is a function: \begin{equation}\label{eq:attention} Y = \mathrm{Attn}(X, C) = \omega\left( \frac{XW_Q (CW_K)^T}{\sqrt{d}} \right) CW_V \vspace{-1mm} \end{equation} where the attention function $\mathrm{Attn}: \mathbb{R}^{n\times d} \times \mathbb{R}^{m\times d} \rightarrow \mathbb{R}^{n\times d}$ takes as inputs two sequences: the query sequence $X \in \mathbb{R}^{n\times d}$ with length $n$ and the context sequence $C \in \mathbb{R}^{m\times d}$ with length $m$, and output one sequence $Y \in \mathbb{R}^{n\times d}$ with the same length $n$ as the query $X$. $d$ is the embedding dimension, and $W_Q, \,\, W_K, \,\, W_V \in \mathbb{R}^{d\times d}$ are three learnable parameters that project the input sequences into the space of query, key and value matrices: $Q=XW_Q, \,\, K = CW_K, \,\, V = CW_V$. $\omega$ is an activation function, e.g. the \emph{softmax} function in regular attention. Note that the formulation in~\eqref{eq:attention} is applicable to both \emph{cross-attention} where $C$ and $X$ are the representations from Transformer encoder and decoder, respectively, and \emph{self-attention} where $X$ and $C$ are the same sequence ($X=C$). In practice, the multi-head variant of attention~\citep{vaswani2017attention}, which performs the attention function $h$ times in parallel, is commonly used. Throughout this paper, we omit $h$ for simplicity. In particular, the matrix $A=\omega(\frac{Q{K}^{T}}{\sqrt{d_{k}}})\in \mathbb{R}^{n\times m}$ in~\eqref{eq:attention} is called the attention matrix which specifies the alignment scores between every pair of tokens in sequences of queries $X$ and contexts $C$. Calculating $A$ takes $O(nm)$ time and space, which is quadratic with respect to the sequence length and becomes a significant bottleneck when processing long sequences. \vspace{-2mm} \subsection{Transformer Layers} \vspace{-1mm} The other two key components of Transformer, besides attention, are position-wise feed-forward networks (FFN) and layer normalization~\citep{ba2016layer}. Technically, the position-wise feed-forward layer operates on each position independently and layer normalization plays a crucial role in controlling the gradient scales~\citep{xiong2020layer}. Each Transformer layer can be expressed as: \begin{equation}\label{eq:transformer} \begin{array}{rcl} X_A & = & \mathrm{LayerNorm}(\mathrm{Attn}(X, C) + X) \\ X' & = & \mathrm{LayerNorm}(\mathrm{FFN}(X_A) + X_A) \end{array} \vspace{-1mm} \end{equation} where $X$ and $C$ are the two input sequences and $X'$ is the output of the Transformer layer. The Transformer layer in \eqref{eq:transformer} adopts the original post-layer normalization architecture~\citep{vaswani2017attention,devlin2019bert} that places layer normalization after residual connection, rather than pre-layer normalization~\citep{vaswani2018tensor2tensor,wang2019learning}. \input{chapters/luna} \input{chapters/exp} \input{chapters/related_work} \input{chapters/conclusion} \begin{ack} This material is based on research sponsored by Air Force Research Laboratory (AFRL) under agreement number FA8750-19-1-1000. The U.S. Government is authorized to reproduce and distribute reprints for Government purposes notwithstanding any copyright notation therein. Xiang Kong was supported by U.S. DARPA AIDA Program No. FA8750-18-2-0014. The views and conclusions contained herein are those of the authors and should not be interpreted as necessarily representing the official policies or endorsements, either expressed or implied, of Air Force Laboratory, DARPA or the U.S. Government. \end{ack}
{'timestamp': '2021-11-04T01:03:58', 'yymm': '2106', 'arxiv_id': '2106.01540', 'language': 'en', 'url': 'https://arxiv.org/abs/2106.01540'}
arxiv
\section{Introduction}\label{sec:introduction} Since its identification in December 2019, COVID-19 has posed critical challenges for the public health and economies of essentially every country in the world~\cite{dong2020interactive,fauci2020covid,liu2020covid}. Government officials have taken a wide range of measures in an effort to contain this pandemic, including closing schools and workplaces, setting restrictions on air travel, and establishing stay at home requirements~\cite{hale2021global}. Accurately forecasting the number of new infected people in the short and medium term is critical for the timely decisions about policies and for the proper allocation of medical resources~\cite{arik2020interpretable,liao2020tw}. For the general population ({\em e.g.},\ business owners, parents with children in school age), additionally forecasting when the government will take action might help them to plan accordingly. There are three basic approaches for predicting the dynamics of an epidemic: compartmental models, statistical methods, and ML-based methods~\cite{arik2020interpretable,watson2021pandemic}. {\bf Compartmental models}\ subdivide a population into mutually exclusive categories (compartments), with a set of dynamical equations that explain the transitions among categories~\cite{blackwood2018introduction}. The \emph{Susceptible-Infected-Removed} (SIR) model~\cite{kermack1927contribution} is a common choice for the modelling of infectious diseases. {\bf Statistical methods}, as the name implies, extract general statistics from the data to fit mathematical models that explain the evolution of the epidemic~\cite{liao2020tw}. Finally, {\bf ML-based methods}\ use machine learning algorithms to analyze historical data and find patterns that lead to accurate predictions of the number of new infected people~\cite{murphy2012machine,watson2021pandemic}. Arguably, when any approach is used to make high-stake decisions, it is important that it be not just accurate, but also interpretable: It should give the decision-maker enough information to justify the recommendation~\cite{rudin2019stop}. Here, we propose {\sc si}ML{\sc r}, which is an interpretable probabilistic graphical model (PGM) that combines compartmental models and ML-based methods. As its name suggests, it incorporates machine learning (ML) within an SIR model. {\sc si}ML{\sc r}\ uses a \emph{mixture of experts}\ approach~\cite{jacobs1991adaptive}, where the contribution of each \emph{expert} to the final forecast depends on the changes in the government policies implemented at various earlier time points. When there is no recent change in policies (2 to 4 weeks before the week to be predicted), {\sc si}ML{\sc r}\ relies on an SIR model with time-varying parameters that are fitted using machine learning methods. When a change in policy occurs, {\sc si}ML{\sc r}\ instead relies on a simpler model that predicts that the new number of infections will remain constant. Note that forecasting the number of new infections 1 and 2 weeks in advance ($\nI{1}$\ and $\nI{2}$) is relatively easy as {\sc si}ML{\sc r}\ knows, at the time of the prediction, whether the policy has changed recently. However, for 3- or 4-week forecasts ($\nI{3}$\ and $\nI{4}$), our model needs to estimate the likelihood of a future change of policy. {\sc si}ML{\sc r}\ incorporates prior domain knowledge to estimate such policy-change probabilities. This work makes three important contributions. (1)~It empirically shows that an SIR model with time-varying parameters can describe the complex dynamics of COVID-19. (2)~It describes an interpretable model that predicts the new number of infections 1 to 4 weeks in advance, achieving state-of-the-art results, in terms of mean average percentage error (MAPE), on data from regions from Canada and the United States. (3)~It effectively estimates the probability of observing a change in the government policies, 1 to 4 weeks in advance. The rest of Section~\ref{sec:introduction} describes the related work and basics of the SIR compartmental model. Section~\ref{sec:SIMLR} then describes in detail our proposed {\sc si}ML{\sc r}\ approach. Finally, Section~\ref{sec:Experiments} shows the results of the predicting the number of new infections in the United States and provinces of Canada. \subsection{Basic SIR model}\label{sec:fixed_SIR} The \emph{Susceptible-Infected-Removed} (SIR) compartmental model~\cite{kermack1927contribution} is a mathematical model of infectious disease dynamics that divide the population into 3 disjoint groups~\cite{blackwood2018introduction}: \emph{Susceptible (S)} refers to the set of people who have never been infected, but can acquire the disease if they interact with someone with the infection. \emph{Infected (I)} refers to the set of people who have and can transmit the infection at a given point in time. \emph{Removed (R)} refers to the people who have either recovered or died from the infection, and so cannot transmit the disease anymore. The transitions between the groups is given by the following differential equations: \begin{equation}\label{eq:SIR} \frac{dS}{dt}\ =\ - \beta\ \frac{ S(t) I(t) }{N} \qquad\quad \frac{dI}{dt}\ =\ \beta \ \frac{S(t) I(t) }{N} - \gamma I(t) \qquad\quad \frac{dR}{dt}\ =\ \gamma\ I(t) \end{equation} This simple model, which assumes homogeneous and constant population, is fully defined by the parameters $\beta$ (transmission rate) and $\gamma$ (recovery rate). The intuition behind this model is that every infected patient gets in contact with $\beta$ people. Since only the susceptible people can become infected, the chance of interacting with a susceptible person is simply the proportion of susceptible people in the entire population, $N=S+I+R$. Likewise, at every time point, $\gamma$ proportion of the infected people is removed from the system. Figure~\ref{fig:SIR}(a) depicts the general behaviour of an SIR model. \begin{figure} \centering \includegraphics[width=\columnwidth]{Figures/SIR_Comparison.png} \caption{\label{fig:SIR} \textbf{(a)} General behaviour of the SIR model. \textbf{(b)} The number of infections predicted by the SIR model with fixed parameters, fitted to the US data for 1 week prediction. \textbf{(c)} Similar to (b), but with time-varying parameters. } \end{figure} \subsection{Related work} \label{sec:RelatedW} The main idea behind combining compartmental models with machine learning is to replace the fixed parameters of the former with time-varying parameters that can be learned from data~\cite{anastassopoulou2020data,arik2020interpretable,chen2020time,liao2020tw,liu2012infectious,watson2021pandemic}. However, it is still not clear if these approaches are able to explain (and forecast) the different waves of COVID-19 infections. Particularly relevant to our approach is the work by \citet{arik2020interpretable}, who used latent variables and autoencoders to model extra compartments in an extended \emph{Susceptible-Exposed-Infected-Removed}~(SEIR) model~\cite{blackwood2018introduction}. Those additional compartments bring further insight into how the disease impacts the population; however, we argue that they are not needed for an accurate prediction of the number of new infections; see results in Section~\ref{sec:Experiments}. One limitation of their model is a decrease in performance when the trend in the number of new infections changes~\cite{arik2020interpretable}. We hypothesize that those changes in trend are related to the government policies that are in place at a specific point in time. {\sc si}ML{\sc r}\ is able to capture those changes by tracking the policies implemented at the government level, allowing it to also predict when those policies are likely to change. A different line of work uses machine learning methods to directly predict the number of new infections, without incorporating epidemiological models~\cite{jin2021inter,kafieh2021covid,mojjada2020machine,omran2021applying}. Like our approach, \citeauthor{yeung2021machine} added the non-pharmaceutical interventions (policies) as features in their models; then they used traditional machine learning models to make their predictions under the assumption that the data is not a time-series, but a collection of points that are independent and identically distributed~\cite{yeung2021machine}. Their approach is limited to make predictions up to 2 weeks in advance, since information about the policies that will be implemented in the future is not available at inference time. Our \hbox{{\sc si}ML{\sc r}}{} approach differs by being interpretable and also forecasting policy changes, which allows it to extend the horizon of the $\nI{}$ predictions. \section{Our {\sc si}ML{\sc r}\ model}\label{sec:SIMLR} We view {\sc si}ML{\sc r}\ as a probabilistic graphical model that uses a mixture of experts approach to forecast the number of new COVID-19 infections, 1 to 4 weeks in advance; Figure~\ref{fig:SIMLR} depicts this graphical model as a plate model~\cite{koller2009probabilistic}. The {\color{blue}\bf blue} nodes are {\em estimated}\ at every time point, while the values of the {\color{OliveGreen}\bf green} nodes are either {\em known}\ as part of the historical data, or {\em inferred}\ in a previous time point. The random variables in Figure~\ref{fig:SIMLR} are assumed to have the following distributions: \begin{equation} \begin{array}{r@{\quad |\quad }c@{\quad \sim\quad }l} \mbox{CT}_{t+1} & \mbox{CP}_{t-3},\ \mbox{CP}_{t-2},\ \mbox{CP}_{t-1}& Categorical_{K \in \{-1,0,1\}} (\theta_{CT})\\ % \beta_{t+1} & \beta_{t-2},\ \beta_{t-1},\ \beta_{t},\ \mbox{CT}_{t+1} & \mathcal{N}(\mu_{\beta}, \Sigma_\beta)\\ \gamma_{t+1} &\gamma_{t-2},\ \gamma_{t-1},\ \gamma_{t},\ \mbox{CT}_{t+1} & \mathcal{N}(\mu_{\gamma}, \Sigma_\gamma)\\ % \mbox{SIR}_{t+1} &\beta_{t+1},\ \gamma_{t+1} & \mathcal{N}(\mu_{SIR}, \Sigma_{SIR})\\ % U_{t} &\mbox{SIR}_{t-2}, \mbox{SIR}_{t-1},\ \mbox{SIR}_{t}& Categorical_{K \in \{-1,0,1\}} (\theta_{U})\\ % O_{t}&W_t & Categorical_{K \in \{0,1\}} (\theta_{O})\\ % \mbox{CP}_{t+1}&O_{t},\ U_t & Categorical_{K \in \{-1,0,1\}} (\theta_{CP}) \end{array} \end{equation} \noindent where $t$ indexes the current week, $SIR_t = [S_t, I_t, R_t]$, $\mu_{SIR} \in \mathbb{R}^3$ is given below by Equation~\ref{eq:SIR_discrete}$, \mu_\beta = (\alpha_{0,CT_{t+1}}) + (\alpha_{1,CT_{t+1}})\beta_{t-1} + (\alpha_{2,CT_{t+1}})\beta_{t-2} + (\alpha_{3,CT_{t+1}})\beta_{t-3}$ and $\mu_\gamma = (\omega_{0,CT_{t+1}}) + (\omega_{1,CT_{t+1}})\gamma_{t-1} + (\omega_{2,CT_{t+1}})\gamma_{t-2} + (\omega_{3,CT_{t+1}})\gamma_{t-3}$ are linear combinations of the three previous values of $\beta$ and $\gamma$ (respectively). The coefficients of those linear combinations depend on the value of the random variable $\mbox{CT}_{t+1}$. We did not specify a distribution for the node $\mbox{\tt New infections}_{t+1}$ because its value is deterministically computed as $S_t - S_{t+1}$. Informally, the assignment $\mbox{CT}_t = -1$ means that we expect a change in trend from an increasing number of infections to a decreasing one. The opposite happens when $\mbox{CT}_t = 1$, while $\mbox{CT}_t = 0$ means that we expect the population to follow the current trend (either increasing or decreasing). These changes in trend are assumed to depend on changes in the government policies 2 to 4 weeks prior to the week of our forecast -- \hbox{{\em e.g.},\ }{} we use $\{\mbox{CT}_{t-3},\, \mbox{CT}_{t-2}, \,\mbox{CT}_{t-1}\}$ when predicting the number of new infections at $t+1$, $\nI{t+1}$; and we need $\{\mbox{CT}_{t},\, \mbox{CT}_{t+1}, \,\mbox{CT}_{t+2}\}$ when predicting $\nI{t+4}$, Note that, at time $t$, we will not know $\mbox{CT}_{t+1}$ nor $\mbox{CT}_{t+2}$. The status of $\mbox{CT}_{t+1}$ defines the coefficients that relate $\beta_{t+1}$ and $\gamma_{t+1}$ with their three previous values $\beta_{t}, \beta_{t-1}, \beta_{t-2}$ and $\gamma_{t}, \gamma_{t-1}, \gamma_{t-2}$, respectively. Since $\beta_{t+1}$ and $\gamma_{t+1}$ fully parameterize the SIR model in Equation~\ref{eq:SIR}, we can estimate the new number of infected people, $\nI{t+1}$, from these parameters (as well as the SIR values at time $t$). The random variables $U_t \in \{-1, 0, 1\}$ and $O_t \in \{0, 1\}$ are auxiliary variables designed to predict the probability of observing a change in policy at time $t+1$. Intuitively, $U_t$ represents the ``urgency'' of modifying a policy. As the number of cases per 100K inhabitants and the rate of change between the number of cases in two consecutive time points increases, the urgency to set {\em stricter}\ government policies increases. As the number (and rate of change) of cases decreases, the urgency to {\em relax}\ the policies increases. Finally, $O_t$ models the ``willingness'' to execute a change in government policies. As the number of time points without a change increases, so does this ``willingness''. \begin{figure}[tb] \centering \includegraphics[width=\columnwidth]{Figures/SIMLR.png} \caption{\label{fig:SIMLR} Modeling {\sc si}ML{\sc r}\ as a probabilistic graphical model for forecasting new cases of COVID-19. The {\color{blue}\bf blue} nodes are estimated at each time point, while the {\color{OliveGreen}\bf green} ones are either based on past information, or where estimated in a previous iteration.} \end{figure} \subsection{SIR with time-varying parameters}\label{sec:SIR_time_varying} We can approximate an SIR model by transforming the differential Equation~\ref{eq:SIR} into an equation of differences and then solving for $S_t, I_t$ and $R_t$: \begin{equation}\label{eq:SIR_discrete} S_t\ =\ - \beta \frac{S_{t-1} I_{t-1} }{N} + S_{t-1} \qquad I_t \ =\ \beta\frac{ S_{t-1} I_{t-1} }{N} - \gamma I_{t-1} + I_{t-1} \qquad R_t\ =\ \gamma I_{t-1} + R_{t-1} \end{equation} While the SIR model is non-linear with respect to the states (S, I, R), it is linear with respect to the parameters $\beta$ and $\gamma$. Therefore, under the assumption of constant and known population size ({\em i.e.},\ $N = S_t + I_t + R_t$) we can re-write the set of Equations~\ref{eq:SIR_discrete} as: \begin{equation}\label{eq:SIR_discrete_linear_algebra} \begin{aligned} \begin{bmatrix} S_t \\ I_t \end{bmatrix}\quad &= \quad \begin{bmatrix} -\frac{S_{t-1}I_{t-1}}{N} & 0 \\ \frac{S_{t-1}I_{t-1}}{N}& - I_{t-1}\\ \end{bmatrix} % \begin{bmatrix} \beta \\ \gamma \end{bmatrix}\quad +\quad \begin{bmatrix} S_{t-1} \\ I_{t-1} \end{bmatrix}\\ R_t \quad &= \quad N - S_t - I_t \end{aligned} \end{equation} Given a sequence of states $x_1, \dots, x_n$, where $x_t\ =\ [S_t\ I_t]^T$, it is possible to estimate the optimal parameters of the SIR model as: \begin{equation}\label{eq:beta_gamma} (\beta^*,\ \gamma^*)\quad =\quad \argmin_{\beta,\gamma} \sum_{i=1}^n||x_i - \hat{x}_i ||^2 + \lambda_1 (\beta - \beta_0)^2 + \lambda_2 (\gamma - \gamma_0)^2 \end{equation} \noindent where $\hat{x}_i$ is computed using Equation~\ref{eq:SIR_discrete_linear_algebra}, and $\lambda_1$ and $\lambda_2$ are optional regularization parameters that allow the incorporation of the priors $\beta_0$ and $\gamma_0$. For the case of Gaussian priors -- {\em i.e.},\ $\beta \sim \mathcal{N}(\beta_0, \sigma_{\beta}^2)$ and $\gamma \sim \mathcal{N}(\gamma_0, \sigma_{\gamma}^2)$ -- we use $\lambda_1 = \frac{1}{2\sigma_{\beta}^2}$ and $\lambda_2 = \frac{1}{2\sigma_{\gamma}^2}$~\cite{murphy2012machine}. In the traditional SIR model, we set $\lambda_1 = \lambda_2 = 0$ and fit a single $\beta$ and $\gamma$ to the entire time series. However, as shown in Figure~\ref{fig:SIR}(a), an SIR model with fixed parameters is unable to accurately model several waves of infections. As illustration, Figure~\ref{fig:SIR}(b) shows the predictions produced by fitting an SIR with fixed parameters (Equation~\ref{eq:beta_gamma}) to the US data from 29/March/2020 to 3/May/2021, and then using those parameters to make predictions one week in advance, {over this same interval}. That is, using this learned $(\beta, \gamma)$, and the number of people in the $S$, $I$, and $R$ compartments on 28/March/2020, we predicted the number of observed cases during the week of 29/March/2020 to 4/April/2020. Then, using the reported $[S, I, R]$ values on 4/April/2020, we predicted the number of new infections in the week of 5/April/2020 to 11/April/2020 and so on. Note that even though the parameters $\beta$ and $\gamma$ were found using {\em the entire time series} -- {\em i.e.},\ using information that was not available at the time of prediction -- the resulting model still does a poor job fitting the reported data. Figure~\ref{fig:SIR}(c), on the other hand, was created by allowing $\beta$ and $\gamma$ to change every week. Here, we first found the parameters that fit the data from 29/March/2020 to 4/April/2020 -- call them $\beta_1$ and $\gamma_1$ -- then used those parameters along with the SIR state on 28/March/2020 to predict the number of new infections one week ahead. By repeating this procedure during the entire time series we obtained an almost perfect fit to the data. Of course, these are also not ``legal'' predictions since they too use information that is not available at prediction time -- {\em i.e.},\ they used the number of reported infections during this first week to find the parameters, which were then used to estimate the number of cases over this time. However, this ``cheating'' example shows that an SIR model, with the best time varying parameters, can model the complex dynamics of COVID-19, including the different waves of infections. Recall from Figure~\ref{fig:SIR}(b) that this is not the case in the SIR model with fixed parameters: even in the best scenario (knowing the optimal parameters based on the true values over months of the same data you want to fit!), it still cannot properly fit the data. \subsection{Estimating $\beta_{t+1}$ and $\gamma_{t+1}$} \label{sec:parameterEstimation} Naturally, the challenge is ``legally'' computing the appropriate values of $\beta_{t+1}$ and $\gamma_{t+1}$, for each week, using only the data that is known at time $t$. Figure~\ref{fig:SIMLR} shows that computing $\beta_{t+1}$ and $\gamma_{t+1}$ depends on the status of the random variable $\mbox{CT}_{t+1}$. When $\mbox{CT}_{t+1} = 0$ -- {\em i.e.},\ there is no change in the current trend -- we assume that: \begin{equation}\label{eq:beta_gamma_distribution} \begin{gathered} \beta_{t+1}\quad \sim\quad \mathcal{N}(\alpha_0 + \alpha_1 \beta_{t} + \alpha_2 \beta_{t-1} + \alpha_3 \beta_{t-2},\quad \sigma_{\beta}^2)\\ \gamma_{t+1}\quad \sim \quad \mathcal{N}(\omega_0 + \omega_1 \gamma_{t} + \omega_2 \gamma_{t-1} + \omega_3 \gamma_{t-2}, \quad \sigma_{\gamma}^2) \end{gathered} \end{equation} At time \emph{t}, we can use the historical \emph{daily} data $x_1, x_2, \dots, x_{t}$ to find the \emph{weekly} parameters $\beta_1, \beta_2, \dots, \beta_{t/7}$ and $\gamma_1, \gamma_2, \dots, \gamma_{t/7}$. The first {\em weekly}\ pair $(\beta_1, \gamma_1)$ is found by fitting Equation~\ref{eq:beta_gamma} to $x_1, \dots, x_7$; $(\beta_2, \gamma_2)$ to $x_8, \dots, x_{14}$; and so on. Finally, we find the parameters $\boldsymbol{\alpha}$ and $\boldsymbol{\omega}$ in Equation~\ref{eq:beta_gamma_distribution} by maximizing the likelihood of the computed pairs. After finding those parameters, it is straightforward to infer $(\beta_{t+1}, \gamma_{t+1})$~\cite{koller2009probabilistic}. Note that we decided to estimate $\beta_{t+1}$ and $\gamma_{t+1}$ as a function of the 3 previous values of those parameters; this allows them to incorporate the velocity and acceleration at which the parameters change. That is, we can estimate the velocity at which $\beta$ change as $v_{\beta,t} = \beta_t - \beta_{t-1}$ and its acceleration as $a_{\beta,t} = v_{\beta,t} - v_{\beta,t-1}$. Then, estimating $\beta_t = \theta_0 + \theta_1\beta_{t-1} + \theta_2 v_{\beta,t-1} + \theta_3 a_{\beta,t-1}$ is equivalent to the model in Equation~\ref{eq:beta_gamma_distribution}. The same reasoning applies to the computation of $\gamma_t$. We call this approach the ``trend-following varying-time parameters SIR'', tf-v-SIR. For the case of $\mbox{CT}_t = -1$ and $\mbox{CT}_t = 1$ (which represents a change in trend from increasing number of infections to decreasing number of infections or vice-versa), we set $\beta_{t+1}$ and $\gamma_{t+1}$ to values such that the predicted number of new cases at week $t+1$ is identical to the one at week $t$. We call this the ``Same as the Last Observed Week'' (SLOW) model. \subsection{Estimating $\mbox{CT}_{t+1},\ \mbox{CP}_{t+1},\ \mbox{O}_t$ } \label{sec:Disc+Disc} The random variables $\mbox{CT}_{t+1} \in\{-1,0,1\}, \mbox{CP}_{t+1}\in\{-1,0,1\}$ and $\mbox{O}_t\in\{0,1\}$ in Figure~\ref{fig:SIMLR} are all discrete nodes with discrete parents, meaning their probability mass functions are fully defined by conditional probability tables~(CPTs). Learning the parameters of such CPTs from data is challenging due to the scarcity of historical information. The random variable $\mbox{CT}_{t+1}$ depends on the random variable changes in policy ($\mbox{CP}$) at times $t-1, t-2, t-3$; however, there are very few changes in policy in a given region, meaning it is difficult to accurately estimate those probabilities from data. For the random variable $\mbox{O}$, which represents the ``willingness'' of the government to implement a change in policy, there is no observable data at all. We therefore relied on prior expert knowledge to set the parameters of the conditional probability tables for these random variables. Figure~\ref{fig:CPT} shows the actual CPTs used in our experiments. \begin{figure}[h] \centering \includegraphics[width=\columnwidth]{Figures/CPTs.png} \caption{\label{fig:CPT} Conditional probability tables used by {\sc si}ML{\sc r}. The names of the variables refer to the nodes that appear on Figure~\ref{fig:SIMLR}} \end{figure} \subsection{Estimating $U_t$ } \label{sec:disc+cont For modelling the random variable $U_t$, which represents the ``Urgency to change the trend'', we use an NN-CPD (neural-network conditional probability distribution), which is a modified version of the multinomial logistic conditional probability distribution~\cite{koller2009probabilistic}. \begin{definition}[NN-CPD] Let $Y \in \{1, \dots, m\}$ be an ${m}$-valued random variable with \emph{k} parents $X_1, \dots, X_k$ that each take on numerical values. The conditional probability distribution $P(Y\ |\ X_1,\dots,X_k)$ is an NN-CPD if there is an function $z\ =\ f_{\theta}(X_1, \dots, X_k) \ \in \mathbb{R}^m$, represented as a neural network with parameters $\theta$, such that $p(Y = i \ |\ x_1, \dots, x_k) = \exp(z_i) / \sum_j \exp(z_j)$, where $z_i$ represents the \emph{i-th} entry of $z$. \end{definition} Similar to the case of discrete nodes with discrete parents, the main problem in estimating the parameters $\theta$ of the NN-CPD is the scarcity of data. To compensate for the lack of data, we again rely on domain knowledge and use the probabilistic labels approach proposed by~\citet{vega2021sample}. Using this approach, we can use a dataset with few training instances along with their probabilities to learn the parameters of a neural network more efficiently. To compute $P(U_{t} \ |\ \mbox{SIR}_{t-2}, \mbox{SIR}_{t-1},\ \mbox{SIR}_{t})$, we extract two features: $c_t = \mbox{10E5} (S_{t-1} - S_{t}) / N$, which represents the number of new infections per 100K inhabitants; and $v_t = c_t - c_{t-1}$, which estimates the rate of change of $c_t$, then define $P(U_{t} \ |\ \mbox{SIR}_{t-2}, \mbox{SIR}_{t-1},\ \mbox{SIR}_{t}) = P(U_{t} \ |\ c_t, v_t)$. To learn the parameters $\theta$, we created the dataset shown in Figure~\ref{fig:NN_CPD} and a neural network with a single hidden layer with 64 units with sigmoid activation functions, and 3 output units with softmax activation. As the number and rate of change of new infections increases, the ``urgency'' to impose stricter policies increases. The opposite effect (relaxing the policies) occurs with a decrease in the number and rate of change of new infections. When the new infections and its rate of change are relatively stable, then there is a preference to keep the current policies in place. \begin{figure} \centering \includegraphics[width=\columnwidth]{Figures/NN_CPD.png} \caption{Dataset used to create the NN-CPD for the variable $U_t$ and its visualization. Values closer to 1 (yellow) increase $p(U_t = 1\ |\ C_t,V_t)$. Values closer to 0 (green) increase $p(U_t = 0\ |\ C_t,V_t)$. Values closer to $-1$ (blue) increase $p(U_t = -1\ |\ C_t,V_t)$ }\label{fig:NN_CPD} \end{figure} \section{Experiments and results}\label{sec:Experiments} We evaluated the performance of {\sc si}ML{\sc r}, in terms of MAPE, for forecasting the number of new infections 1 to 4 weeks in advance, in data from United States (as a country) and the 6 biggest provinces of Canada: Alberta~(AB), British Columbia~(BC), Manitoba~(MN), Ontario~(ON), Quebec~(QB), and Saskatchewan~(SK). For each of the regions, the predictions are done on a weekly basis, over the 39 weeks from 26/Jul/2020 to 1/May/2021. This time span captures different waves of infections. At the end of every week, we fitted the {\sc si}ML{\sc r}\ parameters using the data that was available until that week. For example, on 25/Jul/2020 we used all the data available from 1/Jan/2020 to 25/Jul/2020 to fit the parameters of {\sc si}ML{\sc r}. Then, we made the predictions for the new number of new infections during the weeks: 26/Jul/2020 -- 1/Aug/2020 (1 week in advance), 2/Aug/2020 -- 8/Aug/2020 (2 weeks in advance), 9/Aug/2020 -- 15/Aug/2020 (3 weeks in advance), and 16/Aug/2020 -- 22/Aug/2020 (4 weeks in advance). After this, we then fitted the parameters with data up to 1/Aug/2020 and repeated the same process, for 38 more iterations, until we covered the entire range of predictions. We compared the performance of {\sc si}ML{\sc r}\ with the simple SIR compartmental model with time-varying parameters learned using Equation~\ref{eq:beta_gamma_distribution} but no other random variable (tf-v-SIR), and with the simple model that forecasts that the number of cases 1 to 4 weeks in advance is the ``Same as the Last Observed Week'' (SLOW). For the United States data, we also compared the performance of {\sc si}ML{\sc r}\ against the publicly available predictions at the COVID-19 Forecast Hub ({\tt https://github.com/reichlab/covid19-forecast-hub})~\cite{cramer2021evaluation}. For training, we used the publicly available (Creative Commons Attribution CC BY standard) dataset OxCGRT~\cite{hale2021global}, which contains the policies implemented by different countries, as well as the time period over which they were implemented. We limited our analysis to 3 policy decision: {\tt Workplace closing}, {\tt Stay at home requirements}, and {\tt Cancellation of public events}. For information about the new number of reported cases and deaths, we used the publicly available (Creative Commons Attribution 4.0 International) COVID-19 Data Repository by the Center for Systems Science and Engineering at Johns Hopkins University ({\tt https://github.com/CSSEGISandData/COVID-19})~\cite{dong2020interactive}. \subsection{Data preprocessing} Before inputting the time-series data to {\sc si}ML{\sc r}, we performed some basic preprocessing: (1)~The original data contains the cumulative number of reported infections/deaths on a daily basis. We trivially transformed this time-series into the number of new daily infections/deaths. (2)~We considered negative values from the new daily infections/deaths time-series as missing, assuming these negative values arose due to inconsistencies during the data reporting procedure. (3)~We ``filled-in'' the missing values. When the number of new infections/deaths was missing at day $d$, we assumed that the entry at $d+1$ contained the cases for both $d$ and $d+1$, and divided the number of new infections/deaths evenly between both days. (4)~We eliminated outliers. For each day $d$, with number of reported new infections, $\nI{d}$, we computed the mean $(\mu_d)$ and standard deviation $(\sigma_d$ of the set $\nI{d-10}, \dots, \nI{d-1}$; we then set $\nI{d} := \min\{ \nI{d}, \mu_d + 4\sigma_d\}$. (5)~We used the number of new infections and new deaths to produce the SIR vector $SIR_t = [S_t, I_t, R_t]$. Here, we assume everyone in that region was susceptible at the start time -- {\em i.e.},\ $S_{0} =$ total population. At each new time, we transfer the number of new infections from $S$ to $I$, and the number of new deaths and recovered from $I$ to $R$. If the number of new recovered people is not reported, we assume that each new infected person that did not die within the next 15 days, has recovered. \subsection{Results and discussion} \label{sec:Results} Figure~\ref{fig:MAPE_Regions} shows the MAPE of the 1- to 4-week forecasts for the United States (US) and the 6 biggest provinces of Canada. Note that {\sc si}ML{\sc r}\ has a consistently lower MAPE than tf-v-SIR and SLOW. Figure~\ref{fig:SIMLR_Results} illustrates the actual predictions of {\sc si}ML{\sc r}\ one week in advance (and tf-v-SIR and SLOW) for the province of Alberta, Canada; and two weeks in advance for the United States as a country. These two cases exemplify the behaviour of {\sc si}ML{\sc r}. As noted above, there is a 2- to 4-week lag after a policy changes, before we see the effects. This means the task of making 1-week forecasts is relatively simple, as the relevant policy (at times $t-3$ to $t-1$) is fully observable. This allows {\sc si}ML{\sc r}\ to directly compute $\mbox{CT}_{t+1}$, which can then choose whether to continue using the SIR with time-varying parameters if no policy changed at time $t-1$, $t-2$, or $t-3$, versus use the SLOW predictor if the policy changed. (See its CPT in Figure~\ref{fig:CPT}). Figure~\ref{fig:SIMLR_Results}(a) shows a change in the trend of reported new cases at week 22. However, just by looking at the evolution of number of new infections before week 22, there is no way to predict this change, which is why tf-v-SIR predicts that the number of new infections will continue growing. However, since {\sc si}ML{\sc r}\ observed a change in the government policies at week 20, it realized it could no longer rely on its estimation of parameters and so switched to the SLOW model, which is why it was more accurate here. A similar behaviour occurs in week 34, when the 3rd wave of cases in Alberta started. Due to a relaxation in the policies on week 31, {\sc si}ML{\sc r}\ (at week 31) correctly predicted a change of trend around weeks 33--35. Predictions at the country level are more complicated, since most of the time policies are implemented at the state (or province) level instead of nationally. For making predictions for an entire country, as well as predictions 3 or 4 weeks in advance, {\sc si}ML{\sc r}\ first predicts, then uses, the likelihood of observing a change in trend, at every week. In these cases, the random variable $CT_{t+1}$ no longer acts like a ``switch'', but instead it mixes the predictions of the tf-v-SIR and SLOW models, according to the probability of observing a change in the trend. Figure~\ref{fig:SIMLR_Results}(b) shows that whenever there is a stable trend in the number of new reported infections -- which suggests there has been no recent policy changes -- {\sc si}ML{\sc r}\ relies on the predictions of the tf-v-SIR model; however, as the number (and rate of change) of new infections increases, so does the probability of observing a change in the policy. Therefore, {\sc si}ML{\sc r}\ starts giving more weight to the predictions of the SLOW model. Note this behaviour in the same figure during weeks 13 -- 20. Figure~\ref{fig:SIMLR_Results}(c) shows how our proposed {\sc si}ML{\sc r}\ approach compares with the 18 models that submitted predictions to the CDC during the same span of time. Note that {\sc si}ML{\sc r}\ and the model \emph{LNQ-ens1} are the best performing models, with no statistically significant difference (p > 0.05 on a paired t-test) with respect to MAPE. A striking result is how hard it is to beat the simple SLOW model (presented as \emph{COVIDhub-baseline} in the CDC dataset). Out of the 19 models considered here, only 5 (including {\sc si}ML{\sc r}) do better than this simple baseline when predicting 3 to 4 weeks ahead! This brings some insight into the challenge of making accurate prediction in the medium term -- probably due to the need to predict, then use, policy change information. \section{Conclusions} \label{sec:concl} \begin{figure} \centering \includegraphics[width=0.9\columnwidth]{Figures/MAPE_Regions.png} \caption{\label{fig:MAPE_Regions} Comparison of {\sc si}ML{\sc r}, SIR model with time-varying parameters, and SLOW.} \end{figure} \begin{figure} \centering \includegraphics[width=0.9\columnwidth]{Figures/SIMLR_Results.png} \caption{\label{fig:SIMLR_Results} (a)~1-week forecasts {\sc si}ML{\sc r}, tf-v-SIR, and SLOW, for Alberta, Canada. (b)~2-week forecasts, of the same models, for US data. (c)~Comparison of {\sc si}ML{\sc r}\ versus models submitted to the CDC (on US data). } \end{figure} \subsection{Limitations and societal impact} \label{sec:limitations} We do not foresee any potential negative societal impacts of this work. There are, however, two main limitations to {\sc si}ML{\sc r}. {\sc si}ML{\sc r}'s underlying PGM makes it easy to interpret. However, this structure does not imply causality: Although changes in the observed policy influence changes in the trend of new reported cases, the opposite is also true in reality. Also, while {\sc si}ML{\sc r}\ is able to estimate the likelihood of a change in policy, it does not identify which policy might be implemented next. The second limitation is that {\sc si}ML{\sc r}\ relies on conditional probabilities tables that are hard to learn due to lack of data, which forced us to build them based on domain knowledge. If these estimations are disproportionately wrong, then the predictions might be also misleading. Also, different regions might have different ``thresholds'' for taking action. Although for our experiments we set those CPTs a priori for US and Canada, they might differ for other countries. Despite these two limitations, {\sc si}ML{\sc r}\ produced state-of-the-art results in both forecasting in the US as a country, and at the provincial level in Canada. \subsection{Contributions} This paper demonstrated that a model that explicitly models and incorporates government policy decisions can accurately produce 1- to 4-week forecasts of the number of COVID-19 infections. This involved showing (1)~that an SIR model with time-varying parameters is enough to describe the complex dynamics of this pandemic, including the different waves of infections. Modelling {\sc si}ML{\sc r}\ as a probabilistic graphical model not only makes it interpretable, but also makes it easy to incorporate domain knowledge that compensates for the relatively scarce data. {\sc si}ML{\sc r}'s excellent performance -- comparable to state-of-the-art systems in this competitive task -- show that it is possible to design interpretable machine learning models without sacrificing performance. We expect that this approach will be useful not only for modelling COVID-19, but other infectious diseases as well. We also hope that its interpretability will leads to its adoption by researchers, and users, in epidemiology and other non-ML fields.
{'timestamp': '2021-06-04T02:10:24', 'yymm': '2106', 'arxiv_id': '2106.01590', 'language': 'en', 'url': 'https://arxiv.org/abs/2106.01590'}
arxiv
\section{Notation Table} \begin{table}[bh] \caption{Notation Table} \label{ta:notations} \vskip 0.10in \begin{center} \begin{tabular}{c|l} \toprule Notation & Definition \\ \midrule $ K $ & The total number of episodes\\ \hline $ S$ & The number of states\\ \hline $ A$ & The number of actions\\ \hline $ H$ & The length of each episode\\ \hline $ [H]$ & Set $\{1,2,\dots,H\}$\\ \hline $Q_{k,h}(x,a)$ & The estimated reward Q-function at step $h$ in episode $k$ \\ \hline $Q_{h}^\pi (x,a)$ & The reward Q-function at step $h$ in episode $k$ under policy $\pi$\\ \hline $V_{k,h}(x)$ & The estimated reward value-function at step $h$ in episode $k$. \\ \hline $V_{h}^\pi (x)$ & The value-function at step $h$ in episode $k$ under policy $\pi$\\ \hline $C_{k,h}(x,a)$ & The estimated utility Q-function at step $h$ in episode $k$ \\ \hline $C_{h}^\pi (x,a)$ & The utility Q-function at step $h$ in episode $k$ under policy $\pi$\\ \hline $W_{k,h}(x)$ & The estimated utility value-function at step $h$ in episode $k$ \\ \hline $W_{h}^\pi (x)$ & The utility value-function at step $h$ in episode $k$ under policy $\pi$\\ \hline $F_{k,h}(x,a)$ & $F_{k,h} (x,a)= Q_{k,h}(x,a) + \frac{Z_k}{\eta} C_{k,h}(x,a)$ \\ \hline $U_{k,h}(x)$ & $U_{k,h} (x)=V_{k,h}(x) + \frac{Z_k}{\eta} W_{k,h}(x)$ \\ \hline $r_h(x,a)$ & The reward of (state, action) pair $(x,a)$ at step $h.$ \\ \hline $g_h(x,a)$ & The utility of (state, action) pair $(x,a)$ at step $h.$ \\ \hline $N_{k,h}(x,a)$ & The number of visits to $(x,a)$ when at step $h$ in episode $k$ (not including $k$) \\ \hline $Z_k$ & The dual estimation (virtual queue) in episode $k.$\\ \hline $q_h^*$ & The optimal solution to the LP of the CMDP \eqref{eq:lp}. \\ \hline ${q}_h^{\epsilon,*}$ & The optimal solution to the tightened LP \eqref{eq:lp-epsilon}. \\ \hline $\delta$ & Slater's constant.\\ \hline $b_t$ & the UCB bonus for given $t$\\ \hline $\mathbb{I}(\cdot)$ & The indicator function\\ \hline \bottomrule \end{tabular} \end{center} \end{table} \section{Useful Lemmas} The first lemma establishes some key properties of the learning rates used in Triple-Q. The proof closely follows the proof of Lemma 4.1 in \cite{JinAllZey_18}. \begin{lemma}\label{le:lr} Recall that the learning rate used in Triple-Q is $\alpha_t = \frac{\chi+1}{\chi+t},$ and \begin{equation} \alpha_t^0=\prod_{j=1}^t(1-\alpha_j)\quad \hbox{and}\quad \alpha_t^i=\alpha_i\prod_{j=i+1}^t(1-\alpha_j). \label{le:lr-def} \end{equation} The following properties hold for $\alpha_t^i:$ \begin{enumerate}[label=(\alph*)] \item $\alpha_t^0=0$ for $t \geq 1, \alpha_t^0=1$ for $t=0.$ \label{le:lr-a} \item $\sum_{i=1}^t\alpha_t^i=1$ for $t\geq 1,$ $\sum_{i=1}^{t}\alpha_t^i=0$ for $t=0.$\label{le:lr-b} \item $\frac{1}{\sqrt{\chi+t}}\leq \sum_{i=1}^t \frac{\alpha_t^i}{\sqrt{\chi + i}}\leq \frac{2}{\sqrt{\chi+t}}.$ \label{le:lr-c} \item $\sum_{t=i}^\infty\alpha_t^i=1+\frac{1}{\chi}$ for every $i\geq 1.$\label{le:lr-d} \item $ \sum_{i=1}^t (\alpha_t^i)^2\leq \frac{\chi+1}{\chi+t}$ for every $t\geq 1.$ \label{le:lr-e} \end{enumerate}\hfill{$\square$} \end{lemma} \begin{proof} The proof of \ref{le:lr-a} and \ref{le:lr-b} are straightforward by using the definition of $\alpha_t^i$. The proof of \ref{le:lr-d} is the same as that in \cite{JinAllZey_18}. \ref{le:lr-c}: We next prove \ref{le:lr-c} by induction. For $t=1,$ we have $\sum_{i=1}^t\frac{\alpha_t^i}{\sqrt{\chi+i}}=\frac{\alpha_1^1}{\sqrt{\chi+1}}=\frac{1}{\sqrt{\chi+1}},$ so \ref{le:lr-c} holds for $t=1$. Now suppose that \ref{le:lr-c} holds for $t-1$ for $t\geq 2,$ i.e. $$\frac{1}{\sqrt{\chi+t-1}}\leq \sum_{i=1}^{t-1} \frac{\alpha_t^i}{\sqrt{\chi + i-1}}\leq \frac{2}{\sqrt{\chi+t-1}}.$$ From the relationship $\alpha_t^i = (1-\alpha_t)\alpha_{t-1}^i$ for $i=1,2,\dots,t-1,$ we have $$\sum_{i=1}^t\frac{\alpha_t^i}{\chi + i} =\frac{\alpha_t}{\sqrt{\chi+t}}+(1-\alpha_t)\sum_{i=1}^{t-1}\frac{\alpha_{t-1}^i}{\sqrt{\chi+i}}.$$ Now we apply the induction assumption. To prove the lower bound in \ref{le:lr-c}, we have $$\frac{\alpha_t}{\sqrt{\chi+t}}+(1-\alpha_t)\sum_{i=1}^{t-1}\frac{\alpha_{t-1}^i}{\sqrt{\chi+i}}\geq \frac{\alpha_t}{\sqrt{\chi+t}} + \frac{1-\alpha_t}{ \sqrt{\chi +t- 1}}\geq \frac{\alpha_t}{\sqrt{\chi+t}} + \frac{1-\alpha_t}{ \sqrt{\chi+t}}\geq \frac{1}{\sqrt{\chi+t}}.$$ To prove the upper bound in \ref{le:lr-c}, we have \begin{align} \frac{\alpha_t}{\sqrt{\chi+t}}+(1-\alpha_t)\sum_{i=1}^{t-1}\frac{\alpha_{t-1}^i}{\sqrt{\chi+i}} \leq & \frac{\alpha_t}{\sqrt{\chi+t}} + \frac{2(1-\alpha_t)}{\sqrt{\chi+t-1}} = \frac{\chi+1}{(\chi+t)\sqrt{\chi+t}} + \frac{2(t-1)}{(\chi+t)\sqrt{\chi+t-1}},\nonumber\\ =& \frac{1-\chi-2t}{(\chi+t)\sqrt{\chi+t}}+ \frac{2(t-1)}{(\chi+t)\sqrt{\chi+t-1}} +\frac{2}{\sqrt{\chi+t}} \nonumber\\ \leq & \frac{-\chi-1}{(\chi+t)\sqrt{\chi+t-1}}+\frac{2}{\sqrt{\chi+t}} \leq \frac{2}{\sqrt{\chi+t}}. \end{align} \ref{le:lr-e} According to its definition, we have \begin{align} \alpha_t^i =& \frac{\chi+1}{i+\chi}\cdot \left(\frac{i}{i+1+\chi}\frac{i+1}{i+2+\chi}\cdots \frac{t-1}{t+\chi} \right)\nonumber\\ = & \frac{\chi+1}{t+\chi}\cdot \left(\frac{i}{i+\chi}\frac{i+1}{i+1+\chi}\cdots \frac{t-1}{t-1+\chi} \right) \leq \frac{\chi+1}{\chi+t}. \end{align} Therefore, we have $$\sum_{i=1}^t (\alpha_t^i)^2 \leq [\max_{i\in[t]}\alpha_t^i]\cdot \sum_{i=1}^t\alpha_t^i\leq \frac{\chi+1}{\chi+t},$$ because $\sum_{i=1}^t\alpha_t^i=1.$ \end{proof} The next lemma establishes upper bounds on $Q_{k,h}$ and $C_{k,h}$ under Triple-Q. \begin{lemma}\label{le:q1-bound} For any $(x,a,h,k)\in\mathcal{S}\times\mathcal{A}\times[H]\times[K],$ we have the following bounds on $Q_{k,h}(x,a)$ and $C_{k,h}(x,a):$ \begin{align*} 0\leq Q_{k,h}(x,a)\leq H^2\sqrt{\iota}\\ 0\leq C_{k,h}(x,a)\leq H^2\sqrt{\iota}. \end{align*} \end{lemma} \begin{proof} We first consider the last step of an episode, i.e. $h=H.$ Recall that $V_{k, H+1}(x)=0$ for any $k$ and $x$ by its definition and $Q_{0,H}=H\leq H\sqrt{\iota}.$ Suppose $Q_{k',H}(x,a)\leq H\sqrt{\iota}$ for any $k'\leq k-1$ and any $(x,a).$ Then, $${Q}_{k,H}(x,a)= (1-\alpha_t)Q_{k_t,H}(x,a) + \alpha_t\left(r_H(x,a)+b_t\right)\leq \max\left\{H\sqrt{\iota}, 1+\frac{H\sqrt{\iota}}{4}\right\}\leq H\sqrt{\iota},$$ where $t=N_{k,H}(x,a)$ is the number of visits to state-action pair $(x,a)$ when in step $H$ by episode $k$ (but not include episode $k$) and $k_t$ is the index of the episode of the most recent visit. Therefore, the upper bound holds for $h=H.$ Note that $Q_{0,h}=H\leq H(H-h+1)\sqrt{\iota}.$ Now suppose the upper bound holds for $h+1,$ and also holds for $k'\leq k-1.$ Consider step $h$ in episode $k:$ \begin{align*} {Q}_{k,h}(x,a)= &(1-\alpha_t)Q_{k_t, h}(x,a) + \alpha_t\left(r_{h}(x,a)+V_{k_t, {h}+1}(x_{k_t, {h}+1})+b_t\right), \end{align*} where $t=N_{k,{h}}(x,a)$ is the number of visits to state-action pair $(x,a)$ when in step ${h}$ by episode $k$ (but not include episode $k$) and $k_t$ is the index of the episode of the most recent visit. We also note that $V_{k,h+1}(x)\leq \max_a Q_{k,h+1}(x,a)\leq H(H-h)\sqrt{\iota}.$ Therefore, we obtain \begin{align*} {Q}_{k,h}(x,a)\leq \max \left\{H(H-h+1)\sqrt{\iota}, 1+H(H-h)\sqrt{\iota}+\frac{H\sqrt{\iota}}{4}\right\}\leq H(H-h+1)\sqrt{\iota}. \end{align*} Therefore, we can conclude that $Q_{k,h}(x,a)\leq H^2\sqrt{\iota}$ for any $k,$ $h$ and $(x,a).$ The proof for $C_{k,h}(x,a)$ is identical. \end{proof} Next, we present the following lemma from \cite{JinAllZey_18}, which establishes a recursive relationship between $Q_{k,h}$ and $Q^\pi_h$ for any $\pi.$ We include the proof so the paper is self-contained. \begin{lemma}\label{le:qk-qpi} Consider any $(x,a,h,k)\in\mathcal{S}\times\mathcal{A}\times[H]\times[K],$ and any policy $\pi.$ Let t=$N_{k,h}(x,a)$ be the number of visits to $(x,a)$ when at step $h$ in frame $T$ before episode $k,$ and $k_1,\dots,k_t$ be the indices of the episodes in which these visits occurred. We have the following two equations: \begin{align} (Q_{k,h} - Q_{h}^{\pi})(x,a) =& \alpha_t^0\left\{Q_{(T-1)K^\alpha+1,h}-Q_{h}^{\pi}\right\}(x,a)\nonumber \\ &+ \sum_{i=1}^t\alpha_t^i\left( \left\{V_{k_i,h+1}-V_{h+1}^{\pi}\right\}(x_{k_i,h+1})+\left\{\hat{\mathbb{P}}_h^{k_i}V_{h+1}^{\pi}-\mathbb{P}_hV_{h+1}^{\pi} \right\}(x,a)+b_i\right), \label{le:qk-qki-1}\\ (C_{k,h} - C_{h}^{\pi})(x,a)=& \alpha_t^0\left\{C_{(T-1)K^\alpha+1,h}-C_{h}^{\pi}\right\}(x,a)\nonumber\\ &+ \sum_{i=1}^t\alpha_t^i \left(\left\{W_{k_i,h+1} - W_{h+1}^{\pi}\right\}(x_{k_i,h+1})+\left\{\hat{\mathbb{P}}_h^{k_i}W_{h+1}^\pi -\mathbb{P}_h W_{h+1}^{\pi}\right\}(x,a)+b_i\right),\label{le:qk-qki-2} \end{align} where $\hat{\mathbb{P}}_h^kV_{h+1}(x,a):=V_{h+1}(x_{k,h+1})$ is the empirical counterpart of $\mathbb{P}_hV_{h+1}^\pi(x,a)=\mathbb{E}_{x^\prime\sim\mathbb{P}_h(\cdot\vert x,a)}V_{h+1}^\pi (x^\prime).$ This definition can also be applied to $W_h^\pi$ as well. \end{lemma} \begin{proof} We will prove \eqref{le:qk-qki-1}. The proof for \eqref{le:qk-qki-2} is identical. Recall that under Triple-Q, $Q_{k+1,h}(x,a)$ is updated as follows: \begin{align*} Q_{k+1,h}(x,a) & = \begin{cases} (1-\alpha_t)Q_{k,h}(x,a)+\alpha_t\left(r_h(x,a)+V_{k,h+1} (x_{h+1,k})+b_t \right) & \text{if $(x,a)= (x_{k,h},a_{k,h})$}\\ Q_{k,h}(x,a) & \text{otherwise} \end{cases}. \end{align*} From the update equation above, we have in episode $k,$ \begin{align*} Q_{k,h}(x, a) = &(1-\alpha_t) Q_{k_t,h}(x, a) + \alpha_t \left( r_h(x, a) + V_{k_t,h+1} (x_{k_t,h+1})+b_t\right). \end{align*} Repeatedly using the equation above, we obtain \begin{align} Q_{k,h}(x, a) = &(1-\alpha_t)(1-\alpha_{t-1})Q_{k_{t-1},h}(x, a) + (1-\alpha_t)\alpha_{t-1}\left(r_h(x, a) + V_{k_{t-1},h+1}(x_{k_{t-1},h+1})+b_{t-1}\right)\nonumber\\ &+\alpha_t \left( r_h(x, a) + V_{k_t,h+1} (x_{k_t,h+1})+b_t\right)\nonumber \\ =&\cdots\nonumber\\ =& \alpha_t^0 Q_{(T-1)K^\alpha+1,h}(x,a) + \sum_{i=1}^t\alpha_t^i \left(r_h(x, a) +V_{k_i,h+1} (x_{k_i,h+1}) + b_i \right),\label{eq:qupdate} \end{align} where the last equality holds due to the definition of $\alpha_t^i$ in \eqref{le:lr-def} and the fact that all $Q_{1,h}(x,a)$s are initialized to be $H.$ Now applying the Bellman equation $Q_{h}^\pi(x,a) = \left\{r_h + \mathbb{P}_hV_{h+1}^\pi\right\}(x,a)$ and the fact that $\sum_{i=1}^t\alpha_t^i=1,$ we can further obtain \begin{align} Q_{h}^{\pi}(x,a) &= \alpha_t^0 Q_{h}^{\pi}(x,a) + (1-\alpha_t^0 )Q_{h}^{\pi}(x,a) \nonumber \\ &= \alpha_t^0 Q_{h}^{\pi}(x,a) + \sum_{i=1}^t\alpha_t^i\left(r(x,a) + \mathbb{P}_hV_{h+1}^{\pi}(x,a) + V_{h+1}^{\pi}(x_{k_i,h+1}) - V_{h+1}^{\pi}(x_{k_i,h+1}) \right)\nonumber\\ &= \alpha_t^0 Q_{h}^{\pi}(x,a) + \sum_{i=1}^t\alpha_t^i\left(r_h(x,a) + \mathbb{P}_hV_{h+1}^{\pi}(x,a) + V_{h+1}^{\pi}(x_{k_i,h+1}) - \hat{\mathbb{P}}_h^{k_i}V_{h+1}^{\pi} (x,a) \right)\nonumber\\ &= \alpha_t^0 Q_{h}^{\pi}(x,a) + \sum_{i=1}^t \alpha_t^i \left(r_h(x,a)+V_{h+1}^{\pi}(x_{k_i,h+1}) + \left\{\mathbb{P}_hV_{h+1}^{\pi}-\hat{\mathbb{P}}_h^{k_i}V_{h+1}^{\pi}\right\}(x,a) \right).\label{eq:qpi} \end{align} Then subtracting \eqref{eq:qpi} from \eqref{eq:qupdate} yields \begin{align*} (Q_{k,h} - Q_{h}^{\pi})(x,a) =& \alpha_t^0\left\{Q_{(T-1)K^\alpha+1,h}-Q_{h}^{\pi}\right\}(x,a)\nonumber\\ &+ \sum_{i=1}^t\alpha_t^i\left( \left\{V_{k_i,h+1}-V_{h+1}^{\pi}\right\}(x_{k_i,h+1})+\left\{\hat{\mathbb{P}}_h^{k_i}V_{h+1}^{\pi}-\mathbb{P}_hV_{h+1}^{\pi} \right\}(x,a)+b_i\right). \end{align*} \end{proof} \begin{lemma}\label{le:u-hoeffding} Consider any frame $T.$ Let t=$N_{k,h}(x,a)$ be the number of visits to $(x,a)$ at step $h$ before episode $k$ in the current frame and let $k_1,\dots,k_t < k$ be the indices of these episodes. Under any policy $\pi,$ with probability at least $1-\frac{1}{K^3},$ the following inequalities hold simultaneously for all $(x,a,h,k)\in\mathcal{S}\times\mathcal{A}\times[H]\times[K]$ \begin{align*} \left\vert \sum_{i=1}^t\alpha_t^i\left\{(\hat{\mathbb{P}}_h^{k_i}-\mathbb{P}_h) V_{h+1}^{\pi}\right\}(x,a)\right\vert \leq &\frac{1}{4} \sqrt{\frac{H^2\iota(\chi+1)}{(\chi+t)}}, \\ \left\vert \sum_{i=1}^t\alpha_t^i\left\{(\hat{\mathbb{P}}_h^{k_i}-\mathbb{P}_h) W_{h+1}^{\pi}\right\}(x,a)\right\vert \leq &\frac{1}{4} \sqrt{\frac{H^2\iota(\chi+1)}{(\chi+t)}}. \end{align*} \end{lemma} \begin{proof} Without loss of generality, we consider $T=1.$ Fix any $(x,a,h)\in\mathcal{S}\times\mathcal{A}\times[H].$ For any $n\in[K^\alpha],$ define $$X(n)=\sum_{i=1}^n\alpha_\tau^i\cdot \mathbb{I}_{\{k_i\leq K\}}\left\{(\hat{\mathbb{P}}_h^{k_i}-\mathbb{P}_h )V_{h+1}^\pi\right\}(x,a).$$ Let $\mathcal{F}_i$ be the $\sigma-$algebra generated by all the random variables until step $h$ in episode $k_i.$ Then $$\mathbb{E}[X(n+1)\vert \mathcal{F}_n]= X(n) + \mathbb{E}\left[\alpha_\tau^{n+1}\mathbb{I}_{\{k_{n+1}\leq K\}}\left\{(\hat{\mathbb{P}}_h^{k_{n+1}}-\mathbb{P}_h )V_{h+1}^\pi\right\}(x,a) \vert \mathcal{F}_n\right]=X(n),$$ which shows that $X(n)$ is a martingale. We also have for $1\leq i \leq n,$ \begin{align*} \vert X(i)-X(i-1)\vert \leq \alpha_\tau^i \left\vert \left\{(\hat{\mathbb{P}}_h^{k_{n+1}}-\mathbb{P}_h )V_{h+1}^\pi\right\}(x,a)\right\vert \leq \alpha_\tau^i H \end{align*} Then let $\sigma = \sqrt{8\log\left(\sqrt{2SAH}K\right)\sum_{i=1}^\tau(\alpha_\tau^iH)^2}.$ By applying the Azuma-Hoeffding inequality, we have with probability at least $1-2\exp\left(-\frac{\sigma^2}{2\sum_{i=1}^\tau(\alpha^i_\tau H )^2 }\right)=1-\frac{1}{SAHK^4},$ $$ \vert X(\tau)\vert \leq \sqrt{8\log\left(\sqrt{2SAH}K\right)\sum_{i=1}^\tau(\alpha_\tau^i H)^2}\leq \sqrt{\frac{\iota}{16} H^2\sum_{i=1}^\tau(\alpha_\tau^i)^2}\leq \frac{1}{4}\sqrt{\frac{H^2\iota(\chi+1)}{\chi+\tau}},$$ where the last inequality holds due to $\sum_{i=1}^\tau(\alpha_\tau^i)^2\leq \frac{\chi+1}{\chi+\tau}$ from Lemma \ref{le:lr}.\ref{le:lr-e}. Because this inequality holds for any $\tau\in[K]$, it also holds for $\tau=t=N_{k,h}(x,a)\leq K,$ Applying the union bound, we obtain that with probability at least $1-\frac{1}{K^3}$ the following inequality holds simultaneously for all $(x,a,h,k)\in\mathcal{S}\times\mathcal{A}\times[H]\times[K],$: $$\left\vert \sum_{i=1}^t\alpha_t^i\left\{(\hat{\mathbb{P}}_h^{k_i}-\mathbb{P}_h) V_{h+1}^{\pi}\right\}(x,a)\right\vert \leq \frac{1}{4} \sqrt{\frac{H^2\iota(\chi+1)}{(\chi+t)}}.$$ Following a similar analysis we also have that with probability at least $1-\frac{1}{K^3}$ the following inequality holds simultaneously for all $(x,a,h,k)\in\mathcal{S}\times\mathcal{A}\times[H]\times[K],$: $$\left\vert \sum_{i=1}^t\alpha_t^i\left\{(\hat{\mathbb{P}}_h^{k_i}-\mathbb{P}_h) W_{h+1}^{\pi}\right\}(x,a)\right\vert \leq \frac{1}{4} \sqrt{\frac{H^2\iota(\chi+1)}{(\chi+t)}}.$$ \end{proof} \begin{lemma}\label{le:drift_epi_neg} Given $\delta\geq 2\epsilon,$ under Triple-Q, the conditional expected drift is \begin{align} \mathbb{E}\left[L_{T+1}-L_T\vert Z_T=z \right]\leq - \frac{\delta}{2}Z_T+ \frac{4H^2\iota}{K^{2}}+ \eta \sqrt{H^2\iota}+ H^4\iota+\epsilon^2 \end{align}\label{le:drift_epi} \end{lemma} \begin{proof} Recall that $L_T = \frac{1}{2} Z_T^2,$ and the virtual queue is updated by using $$ Z_{T+1} = \left( Z_T + \rho + \epsilon -\frac{\bar{C}_T}{K^\alpha}\right)^+.$$ From inequality \eqref{eq:drift-1}, we have \begin{align*} & \mathbb{E}\left[L_{T+1}-L_T\vert Z_T=z \right] \\ \leq & \frac{1}{K^\alpha}\sum_{k=(T-1)K^\alpha+1}^{TK^\alpha}\mathbb E\left[ Z_T\left(\rho+\epsilon-C_{k,1}(x_{k,1},a_{k,1}) \right) -\eta Q_{k,1} (x_{k,1},a_{k,1}) + \eta Q_{k,1} (x_{k,1},a_{k,1}) \vert Z_T=z \right]+H^4\iota +\epsilon^2\\ \leq_{(a)} & \frac{1}{K^\alpha} \sum_{k=(T-1)K^\alpha+1}^{TK^\alpha}\mathbb E\left[Z_T\left( \rho+\epsilon-\sum_a \left\{C_{k,1}q_1^{\pi}\right\}(x_{k,1},a)\right) -\eta \sum_a \{Q_{k,1}q_1^{\pi}\} (x_{k,1},a)+ \eta Q_{k,1} (x_{k,1},a_{k,1})\vert Z_T=z \right]\\ &+\epsilon^2 +H^4\iota \\ \leq & \frac{1}{K^\alpha}\sum_{k=(T-1)K^\alpha+1}^{TK^\alpha} \mathbb E\left[ Z_T\left(\rho+\epsilon-\sum_a \left\{C_{1}^{\pi}q_1^{\pi}\right\}(x_{k,1},a) \right) -\eta \sum_a \{Q_{k,1}q_1^{\pi}\} (x_{k,1},a)+ \eta Q_{k,1} (x_{k,1},a_{k,1})\vert Z_T=z\right] \\ &+\frac{1}{K^\alpha}\sum_{k=(T-1)K^\alpha+1}^{TK^\alpha} \mathbb E\left[Z_T\sum_a \left\{C_{1}^{\pi}q_1^{\pi}\right\}(x_{k,1},a) - Z_T\sum_a \left\{C_{k,1}q_1^{\pi}\right\}(x_{k,1},a)\vert Z_T=z\right] \\ &+\frac{1}{K^\alpha}\sum_{k=(T-1)K^\alpha+1}^{TK^\alpha}\mathbb E\left[\eta \sum_a \left\{Q_{1}^{\pi}q_1^{\pi}\right\}(x_{k,1},a) - \eta \sum_a \left\{Q_{1}^{\pi}q_1^{\pi}\right\}(x_{k,1},a) \vert Z_T=z\right]+H^4\iota+\epsilon^2\\ \leq_{(b)} & - \frac{\delta}{2}z+ \frac{1}{K^\alpha}\sum_{k=(T-1)K^\alpha+1}^{TK^\alpha}\mathbb E\left[\eta \sum_a\left\{(F_1^{\pi}-F_{k,1})q_{1}^{\pi}\right\}(x_{k,1},a)\ + \eta Q_{k,1} (x_{k,1},a_{k,1})\vert Z_T=z\right]+H^4\iota+\epsilon^2 \\ \leq_{(c)} & - \frac{\delta}{2}z+ \frac{4H^2\iota}{K^{2}}+ \eta \sqrt{H^2\iota}+ H^4\iota+\epsilon^2. \end{align*} Inequality $(a)$ holds because of our algorithm. Inequality $(b)$ holds because $\sum_a \left\{Q_{1}^{\pi}q_1^{\pi}\right\}(x_{k,1},a)$ is non-negative, and under Slater's condition, we can find policy $\pi$ such that $$\epsilon+\rho-\mathbb E\left[\sum_a {C}^{\pi}_{1}(x_{k,1},a){q}^{\pi}_{1}(x_{k,1},a) \right]=\rho+\epsilon-\mathbb E\left[\sum_{h,x,a} {q}^{\pi}_h(x,a)g_h(x,a)\right]\leq -\delta+\epsilon \leq -\frac{\delta}{2}.$$ Finally, inequality $(c)$ is obtained similar to \eqref{eq:F-bound}, and the fact that $Q_{k,1} (x_{k,1},a_{k,1})$ is bounded by using Lemma \ref{le:q1-bound} \end{proof} \section{Conclusions}\label{sec:col} This paper considered CMDPs and proposed a model-free RL algorithm without a simulator, named {Triple-Q}. From a theoretical perspective, {\em Triple-Q} achieves sublinear regret and {\em zero} constraint violation. We believe it is the first {\em model-free} RL algorithm for CMDPs with provable sublinear regret, without a simulator. From an algorithmic perspective, {Triple-Q} has similar computational complexity with SARSA, and can easily incorporate recent deep Q-learning algorithms to obtain a deep {\em Triple-Q} algorithm, which makes our method particularly appealing for complex and challenging CMDPs in practice. While we only considered a single constraint in the paper, it is straightforward to extend the algorithm and the analysis to multiple constraints. Assuming there are $J$ constraints in total, Triple-Q can maintain a virtual queue and a utility Q-function for each constraint, and then selects an action at each step by solving the following problem: $$\max_a \left(Q_{h} (x_{h},a) + \frac{1}{\eta}\sum_{j=1}^J {Z^{(j)}} C^{(j)}_{h}(x_{h},a)\right).$$ \section{Introduction} Reinforcement learning (RL), with its success in gaming and robotics, has been widely viewed as one of the most important technologies for next-generation, AI-driven complex systems such as autonomous driving, digital healthcare, and smart cities. However, despite the significant advances (such as deep RL) over the last few decades, a major obstacle in applying RL in practice is the lack of ``safety'' guarantees. Here ``safety'' refers to a broad range of operational constraints. The objective of a traditional RL problem is to maximize the expected cumulative reward, but in practice, many applications need to be operated under a variety of constraints, such as collision avoidance in robotics and autonomous driving \cite{OnoPavKuw_15,GarFer_12,FisAkaZei_18}, legal and business restrictions in financial engineering \cite{AbePreCez_10}, and resource and budget constraints in healthcare systems \cite{YuLiuNem_19}. These applications with operational constraints can often be modeled as Constrained Markov Decision Processes (CMDPs), in which the agent's goal is to learn a policy that maximizes the expected cumulative reward subject to the constraints. Earlier studies on CMDPs assume the model is known. A comprehensive study of these early results can be found in \cite{Alt_99}. RL for unknown CMDPs has been a topic of great interest recently because of its importance in Artificial Intelligence (AI) and Machine Learning (ML). The most noticeable advances recently are {\em model-based} RL for CMDPs, where the transition kernels are learned and used to solve the linear programming (LP) problem for the CMDP \cite{SinGupShr_20,BraDudLyk_20,KriRahPie_20,EfrManPir_20}, or the LP problem in the primal component of a primal-dual algorithm \cite{QiuWeiYan_20,EfrManPir_20}. If the transition kernel is linear, then it can be learned in a sample efficient manner even for infinite state and action spaces, and then be used in the policy evaluation and improvement in a primal-dual algorithm \cite{DinWeiYan_20}. \cite{DinWeiYan_20} also proposes a model-based algorithm (Algorithm 3) for the tabular setting (without assuming a linear transition kernel). \begin{table*}[t] \caption{The Exploration-Exploitation Tradeoff in Episodic CMDPs.} \label{ta:algorithms} \begin{center} \begin{tabular}{|c|l|l|l|} \toprule & {\bf Algorithm} & {\bf Regret} & {\bf Constraint Violation} \\ \hline \multirow{3}{*}{Model-based} & OPDOP \cite{DinWeiYan_20} & $\tilde{\mathcal{O}}(H^3\sqrt{S^2AK})$& $\tilde{\mathcal{O}}(H^3\sqrt{S^2AK})$ \\\cline{2-4} & OptDual-CMDP \cite{EfrManPir_20} & $\tilde{\mathcal{O}}(H^2\sqrt{S^3AK})$ & $\tilde{\mathcal{O}}(H^2\sqrt{S^3AK})$ \\\cline{2-4} & OptPrimalDual-CMDP \cite{EfrManPir_20} & $\tilde{\mathcal{O}}(H^2\sqrt{S^3AK})$ & $\tilde{\mathcal{O}}(H^2\sqrt{S^3AK})$ \\ \bottomrule \toprule Model-free & \cellcolor{lightgray} Triple-Q &$\tilde{\cal O}\left(\frac{1 }{\delta}H^4 S^{\frac{1}{2}}A^{\frac{1}{2}}K^{\frac{4}{5}} \right)$ &0 \\ \bottomrule \end{tabular} \end{center} \end{table*} The performance of a model-based RL algorithm depends on how accurately a model can be estimated. For some complex environments, building accurate models is challenging computationally and data-wise \cite{SutBar_18}. For such environments, model-free RL algorithms often are more desirable. However, there has been little development on model-free RL algorithms for CMDPs with provable optimality or regret guarantees, with the exceptions \cite{DinZhaBas_20,XuLiaLan_20,CheDonWan_21}, all of which require simulators. In particular, the sample-based NPG-PD algorithm in \cite{DinZhaBas_20} requires a simulator which can simulate the MDP from any initial state $x,$ and the algorithms in \cite{XuLiaLan_20,CheDonWan_21} both require a simulator for policy evaluation. It has been argued in \cite{AzaRemHil_12,AzaRemHil_13,JinAllZey_18} that with a perfect simulator, exploration is not needed and sample efficiency can be easily achieved because the agent can query any (state, action) pair as it wishes. Unfortunately, for complex environments, building a perfect simulator often is as difficult as deriving the model for the CMDP. For those environments, sample efficiency and the exploration-exploitation tradeoff are critical and become one of the most important considerations of RL algorithm design. \subsection{Main Contributions} In this paper, we consider the online learning problem of an episodic CMDP with a model-free approach {\em without} a simulator. We develop the first {\em model-free} RL algorithm for CMDPs with sublinear regret and {\em zero} constraint violation (for large $K$). The algorithm is named {Triple-Q} because it has three key components: (i) a Q-function (also called action-value function) for the expected cumulative reward, denoted by $Q_{h}(x,a)$ where $h$ is the step index and $(x,a)$ denotes a state-action pair, (ii) a Q-function for the expected cumulative utility for the constraint, denoted by $C_{h}(x,a),$ and (iii) a virtual-Queue, denoted by $Z,$ which (over)estimates the cumulative constraint violation so far. At step $h$ in the current episode, when observing state $x,$ the agent selects action $a^*$ based on a {\em pseudo-Q-value} that is a combination of the three ``Q'' values: \begin{align*} a^*\in \underbrace{\arg\max_a Q_{h}(x,a)+\frac{Z}{\eta} C_{h}(x,a)}_{{\text{pseudo-Q-value of state $(x,a)$ at step $h$}}}, \end{align*} where $\eta$ is a constant. Triple-Q uses UCB-exploration when learning the Q-values, where the UCB bonus and the learning rate at each update both depend on the visit count to the corresponding (state, action) pair as in \cite{JinAllZey_18}). Different from the optimistic Q-learning for unconstrained MDPs (e.g. \cite{JinAllZey_18,WanDonChe_20,WeiJahLuo_20}), the learning rates in Triple-Q need to be periodically reset at the beginning of each frame, where a frame consists of $K^\alpha$ consecutive episodes. The value of the virtual-Queue (the dual variable) is updated once in every frame. So Triple-Q can be viewed as a two-time-scale algorithm where virtual-Queue is updated at a slow time-scale, and Triple-Q learns the pseudo-Q-value for fixed $Z$ at a fast time scale within each frame. Furthermore, it is critical to update the two Q-functions ($Q_h(x,a)$ and $C_h(x,a)$) following a rule similar to SARSA \cite{RumNir_94} instead of Q-learning \cite{Wat_89}, in other words, using the Q-functions of the action that is taken instead of using the $\max$ function. We prove {Triple-Q} achieves $\tilde{\cal O}\left(\frac{1 }{\delta}H^4 S^{\frac{1}{2}}A^{\frac{1}{2}}K^{\frac{4}{5}} \right)$ reward regret and guarantees {\em zero} constraint violation when the total number of episodes $K\geq\left(\frac{16\sqrt{SAH^6\iota^3}}{\delta}\right)^5,$ where $\iota$ is logarithmic in $K.$ Therefore, in terms of constraint violation, our bound is sharp for large $K.$ To the best of our knowledge, this is the first {\em model-free}, {\em simulator-free} RL algorithm with sublinear regret and {\em zero} constraint violation. For model-based approaches, it has been shown that a model-based algorithm achieves both $\tilde{\cal O}(\sqrt{H^4SAK})$ regret and constraint violation (see, e.g. \cite{EfrManPir_20}). It remains open what is the fundamental lower bound on the regret under model-free algorithms for CMDPs and whether the regret bound under Triple-Q is order-wise sharp or can be further improved. Table \ref{ta:algorithms} summarizes the key results on the exploration-exploitation tradeoff of CMDPs in the literature. As many other model-free RL algorithms, a major advantage of {Triple-Q} is its low computational complexity. The computational complexity of {Triple-Q} is similar to SARSA for unconstrained MDPs, so it retains both its effectiveness and efficiency while solving a much harder problem. While we consider a tabular setting in this paper, {Triple-Q} can easily incorporate function approximations (linear function approximations or neural networks) by replacing the $Q(x,a)$ and $C(x,a)$ with their function approximation versions, making the algorithm a very appealing approach for solving complex CMDPs in practice. We will demonstrate this by applying Deep Triple-Q, Triple-Q with neural networks, to the Dynamic Gym benchmark \cite{YanSimTin_21} in Section \ref{sec:simu}. \section{Problem Formulation} We consider an episodic CMDP, denoted by $(\mathcal{S},\mathcal{A},H,\mathbb{P},r,g),$ where $\mathcal{S}$ is the state space with $\vert \mathcal{S}\vert=S,$ $\mathcal{A}$ is the action space with $\vert \mathcal{A}\vert=A,$ $H$ is the number of steps in each episode, and $\mathbb{P}=\{\mathbb{P}_h\}_{h=1}^H$ is a collection of transition kernels (transition probability matrices). At the beginning of each episode, an initial state $x_{1}$ is sampled from distribution $\mu_0.$ Then at step $h,$ the agent takes action $a_h$ after observing state $x_h$. Then the agent receives a reward $r_h(x_h,a_h)$ and incurs a utility $g_h(x_h,a_h).$ The environment then moves to a new state $x_{h+1}$ sampled from distribution $\mathbb{P}_h(\cdot\vert x_h,a_h).$ Similar to \cite{JinAllZey_18}, we assume that $r_h(x,a)(g_h(x,a)):\mathcal{S}\times \mathcal{A}\rightarrow [0,1],$ are deterministic for convenience. Given a policy $\pi,$ which is a collection of $H$ functions $\{\pi_h:\mathcal{S}\rightarrow\mathcal{A}\}_{h=1}^H,$ the reward value function $V_{h}^\pi$ at step $h$ is the expected cumulative rewards from step $h$ to the end of the episode under policy $\pi:$ $$V_{h}^\pi(x)=\mathbb{E}\left[\left.\sum_{i=h}^H r_i(x_i,\pi_i(x_i))\right\vert x_h=x \right].$$ The (reward) $Q$-function $Q_{h}^\pi(x,a)$ at step $h$ is the expected cumulative rewards when agent starts from a state-action pair $(x,a)$ at step $h$ and then follows policy $\pi:$ $$Q_{h}^\pi(x,a )=r_h(x,a) + \mathbb{E}\left[\left.\sum_{i=h+1}^H r_i(x_i,\pi_i(x_i))\right\vert\begin{array}{cc} x_h=x\\a_h=a \end{array} \right].$$ Similarly, we use $W_{h}^\pi(x):\mathcal{S}\rightarrow\mathbb{R}^+$ and $C_{h}^\pi(x,a):\mathcal{S}\times\mathcal{A}\rightarrow\mathbb{R}^+$ to denote the utility value function and utility $Q$-function at step $h$: \begin{align*} W_{h}^\pi(x) &=\mathbb{E}\left[\left.\sum_{i=h}^H g_i(x_i,\pi_i(x_i))\right\vert x_h=x \right],\\ C_{h}^\pi(x,a) &=g_h(x,a) + \mathbb{E}\left[\left.\sum_{i=h+1}^H g_i(x_i,\pi_i(x_i))\right\vert \begin{array}{cc} x_h=x\\a_h=a \end{array}\right]. \end{align*} For simplicity, we adopt the following notation (some used in \cite{JinAllZey_18,DinWeiYan_20}): \begin{align*} \mathbb{P}_hV_{h+1}^\pi(x,a)=\mathbb{E}_{x^\prime\sim\mathbb{P}_h(\cdot\vert x,a)}V^\pi_{h+1}(x^\prime), &\quad Q_{h}^\pi(x,\pi_h(x)) = \sum_a Q_{h}^\pi(x,a) \mathbb{P}(\pi_h(x)=a)\\ \mathbb{P}_hW_{h+1}^\pi(x,a)=\mathbb{E}_{x^\prime\sim\mathbb{P}_h(\cdot\vert x,a)}W^\pi_{h+1}(x^\prime), &\quad C_{h}^\pi(x,\pi_h(x)) = \sum_a C_{h}^\pi(x,a) \mathbb{P}(\pi_h(x)=a). \end{align*} From the definitions above, we have \begin{align*} V_{h}^\pi(x)=Q_{h}^\pi(x,\pi_h(x)),\quad &Q_{h}^\pi(x,a)=r_h(x,a)+\mathbb{P}_h V_{h+1}^\pi(x,a), \end{align*} and \begin{align*} W_{h}^\pi(x)=C_{h}^\pi(x,\pi_h(x)),\quad &C_{h}^\pi(x,a)=g_h(x,a)+\mathbb{P}_h W_{h+1}^\pi(x,a). \end{align*} Given the model defined above, the objective of the agent is to find a policy that maximizes the expected cumulative reward subject to a constraint on the expected utility: \begin{equation} \underset{\pi\in\Pi}{\text{maximize}}\ \mathbb E\left[V_{1}^\pi(x_1)\right] \ \text{subject to:} \mathbb E\left[W_{1}^\pi(x_1)\right]\geq \rho,\label{eq:obj} \end{equation} where we assume $\rho\in[0,H]$ to avoid triviality and the expectation is taken with respect to the initial distribution $x_1\sim \mu_0.$ \begin{remark} The results in the paper can be directly applied to a constraint in the form of \begin{equation} \mathbb E\left[W_{1}^\pi(x_1)\right]\leq \rho.\label{cost-constraint} \end{equation} Without loss of generality, assume $\rho\leq H.$ We define $\tilde{g}_h(x,a)=1-g_h(x,a)\in[0,1]$ and $\tilde{\rho}=H-\rho\geq 0,$ the the constraint in \eqref{cost-constraint} can be written as \begin{equation} \mathbb E\left[\tilde{W}_{1}^\pi(x_1)\right]\geq \tilde{\rho}, \end{equation} where \begin{align*} \mathbb E\left[\tilde{W}_{1}^\pi(x_1)\right]=\mathbb{E}\left[\sum_{i=1}^H \tilde{g}_i(x_i,\pi_i(x_i)) \right]=H-\mathbb E\left[W_{1}^\pi(x_1)\right]. \end{align*} \end{remark} Let $\pi^*$ denote the optimal solution to the CMDP problem defined in \eqref{eq:obj}. We evaluate our model-free RL algorithm using regret and constraint violation defined below: \begin{align} \text{Regert}(K) &=\mathbb E\left[\sum_{k=1}^K\left(V_{1}^*(x_{k,1})-V_{1}^{\pi_k}(x_{k,1})\right)\right],\label{def:regret}\\ \text{Violation}(K) &=\mathbb E\left[ \sum_{k=1}^K \left(\rho-W_1^{\pi_k}(x_{k,1})\right)\right], \end{align} where $V_1^*(x)=V_1^{\pi^*}(x),$ $\pi_k$ is the policy used in episode $k$ and the expectation is taken with respect to the distribution of the initial state $x_{k,1} \sim \mu_0.$ In this paper, we assume the following standard Slater's condition hold. \begin{assumption} \label{as:1} (Slater's Condition). Given initial distribution $\mu_0,$ there exist $\delta>0$ and policy $\pi$ such that $$\mathbb E\left[W_{1}^\pi(x_1)\right] -\rho \geq \delta.$$ \end{assumption} In this paper, Slater's condition simply means there exists a feasible policy that can satisfy the constraint with a slackness $\delta.$ This has been commonly used in the literature \cite{DinWeiYan_20,DinZhaBas_20,EfrManPir_20,PatChaCal_19}. We call $\delta$ Slater's constant. While the regret and constraint violation bounds depend on $\delta,$ our algorithm does not need to know $\delta$ under the assumption that $K$ is large (the exact condition can be found in Theorem \ref{thm:main}). This is a noticeable difference from some of works in CMDPs in which the agent needs to know the value of this constant (e.g. \cite{DinWeiYan_20}) or alternatively a feasible policy (e.g. \cite{AchHelDav_17}) . \section{Proof of the Main Theorem} We now present the complete proof of the main theorem. \subsection{Notation} In the proof, we explicitly include the episode index in our notation. In particular, \begin{itemize} \item $x_{k,h}$ and $a_{k,h}$ are the state and the action taken at step $h$ of episode $k.$ \item $Q_{k,h},$ $C_{k,h},$ $Z_k,$ and $\bar C_k$ are the reward Q-function, the utility Q-function, the virtual-Queue, and the value of $\bar C$ {\em at the beginning} of episode $k.$ \item $N_{k,h},$ $V_{k,h}$ and $W_{k,h}$ are the visit count, reward value-function, and utility value-function {\em after} they are updated at step $h$ of episode $k$ (i.e. after line 9 of Triple-Q). \end{itemize} We also use shorthand notation $$\{f-g\}(x)=f(x)-g(x),$$ when $f(\cdot)$ and $g(\cdot)$ take the same argument value. Similarly $$\{(f-g)q\}(x)=(f(x)-g(x))q(x).$$ In this shorthand notation, we put functions inside $\{\ \},$ and the common argument(s) outside. A summary of notations used throughout this paper can be found in Table \ref{ta:notations} in the appendix. \subsection{Regret} To bound the regret, we consider the following offline optimization problem as our regret baseline \cite{Alt_99,PutMar_14}: \begin{align} \underset{q_h }{\max} &\sum_{h,x,a} q_h(x,a)r_h(x,a) \label{eq:lp}\\ \hbox{s.t.:} &\sum_{h,x,a} q_h(x,a)g_h(x,a) \geq \rho \label{lp:cost}\\ & \sum_a q_h(x,a) = \sum_{x^\prime,a^\prime} \mathbb P_{h-1}(x\vert x^\prime,a^\prime) q_{h-1} (x^\prime,a^\prime)\label{lp:gb}\\ & \sum_{x,a}q_h(x,a) =1, \forall h\in[H] \label{lp:normalization}\\ &\sum_{a} q_1(x,a)= \mu_0(x)\label{lp:ini} \\ & q_h(x,a) \geq 0, \forall x\in\mathcal{S},\forall a\in\mathcal{A},\forall h\in[H]. \label{lp:p} \end{align} Recall that $\mathbb P_{h-1}(x\vert x^\prime,a^\prime)$ is the probability of transitioning to state $x$ upon taking action $a'$ in state $x'$ at step $h-1.$ This optimization problem is linear programming (LP), where $q_h(x,a)$ is the probability of (state, action) pair $(x,a)$ occurs in step $h,$ $\sum_a q_h(x,a)$ is the probability the environment is in state $x$ in step $h,$ and $$\frac{q_h(x,a)}{\sum_{a'} q_h(x,a')}$$ is the probability of taking action $a$ in state $x$ at step $h,$ which defines the policy. We can see that \eqref{lp:cost} is the utility constraint, \eqref{lp:gb} is the global-balance equation for the MDP, \eqref{lp:normalization} is the normalization condition so that $q_h$ is a valid probability distribution, and \eqref{lp:ini} states that the initial state is sampled from $\mu_0.$ Therefore, the optimal solution to this LP solves the CMDP (if the model is known), so we use the optimal solution to this LP as our baseline. To analyze the performance of {Triple-Q}, we need to consider a tightened version of the LP, which is defined below: \begin{align} \underset{q_h }{\max} &\sum_{h,x,a} q_h (x,a)r_h(x,a) \label{eq:lp-epsilon}\\ \hbox{s.t.:} &\sum_{h,x,a} q_h (x,a)g_h(x,a) \geq \rho+\epsilon \nonumber\\ &\eqref{lp:gb}-\eqref{lp:p}\nonumber, \end{align} where $\epsilon>0$ is called a tightness constant. When $\epsilon\leq \delta,$ this problem has a feasible solution due to Slater's condition. We use superscript ${ }^*$ to denote the optimal value/policy related to the original CMDP \eqref{eq:obj} or the solution to the corresponding LP \eqref{eq:lp} and superscript ${ }^{\epsilon,*}$ to denote the optimal value/policy related to the $\epsilon$-tightened version of CMDP (defined in \eqref{eq:lp-epsilon}). Following the definition of the regret in \eqref{def:regret}, we have \begin{align} \hbox{Regret}(K) = \mathbb E\left[\sum_{k=1}^{K} V^*_{1}(x_{k,1}) - V_{1}^{\pi_k}(x_{k,1}) \right] =\mathbb E\left[\sum_{k=1}^{K} \left( \sum_a \left\{Q^*_{1}q_1^*\right\}(x_{k,1},a)\right) - Q_{1}^{\pi_k}(x_{k,1}, a_{k,1}) \right] \nonumber. \end{align} Now by adding and subtracting the corresponding terms, we obtain \begin{align} & \hbox{Regret}(K)\nonumber\\ = & \mathbb E \left[\sum_{k=1}^{K} \left( \sum_a \left\{{Q}_{1}^{*}{q}^{*}_1 -{Q}_{1}^{\epsilon,*}{q}^{\epsilon,*}_1\right\}(x_{k,1},a) \right)\right] +\label{step:epsilon-dif} \\ &\mathbb E \left[\sum_{k=1}^{K} \left( \sum_a \left\{{Q}_{1}^{\epsilon,*}{q}^{\epsilon,*}_1\right\}(x_{k,1},a)-Q_{k,1}(x_{k,1}, a_{k,1}) \right)\right]+\label{step(i)}\\ &\mathbb E \left[\sum_{k=1}^{K} \left\{Q_{k,1}- Q_{1}^{\pi_k}\right\}(x_{k,1}, a_{k,1}) \right].\label{step:biase} \end{align} Next, we establish the regret bound by analyzing the three terms above. We first present a brief outline. \subsubsection{Outline of the Regret Analysis} \begin{itemize}[leftmargin=*] \item {\bf Step 1:} First, by comparing the LP associated with the original CMDP \eqref{eq:lp} and the tightened LP \eqref{eq:lp-epsilon}, Lemma \ref{le:epsilon-dif} will show $$\mathbb{E}\left[ \sum_a \left\{Q_{1}^{*}q_1^*- {Q}_{1}^{\epsilon,*}{q}_1^{\epsilon,*}\right\}(x_{k,1},a)\right] \leq \frac{H \epsilon }{\delta},$$ which implies that under our choices of $\epsilon,$ $\delta,$ and $\iota,$ $$\eqref{step:epsilon-dif} \leq \frac{KH\epsilon}{\delta}= \tilde{\cal O}\left(\frac{1 }{\delta}H^4 S^{\frac{1}{2}}A^{\frac{1}{2}}K^{\frac{4}{5}} \right).$$ \item {\bf Step 2:} Note that $Q_{k,h}$ is an estimate of $Q^{\pi_k}_h,$ and the estimation error \eqref{step:biase} is controlled by the learning rates and the UCB bonuses. In Lemma \ref{le:qk-qpi-bound}, we will show that the cumulative estimation error over one frame is upper bounded by $$H^2SA +\frac{H^3\sqrt{\iota}K^\alpha}{\chi} + \sqrt{H^4SA\iota K^{\alpha}(\chi+1)}.$$ Therefore, under our choices of $\alpha,$ $\chi,$ and $\iota,$ the cumulative estimation error over $K$ episodes satisfies \begin{align*} \eqref{step:biase}\leq H^2SA K^{1-\alpha} +\frac{H^3\sqrt{\iota}K}{\chi} + \sqrt{H^4SA\iota K^{2-\alpha}(\chi+1)}=\tilde{\cal O}\left(H^3 S^{\frac{1}{2}}A^{\frac{1}{2}}K^{\frac{4}{5}} \right). \end{align*} The proof of Lemma \ref{le:qk-qpi-bound} is based on a recursive formula that relates the estimation error at step $h$ to the estimation error at step $h+1,$ similar to the one used in \cite{JinAllZey_18}, but with different learning rates and UCB bonuses. \item {\bf Step 3:} Bounding \eqref{step(i)} is the most challenging part of the proof. For unconstrained MDPs, the optimistic Q-learning in \cite{JinAllZey_18} guarantees that $Q_{k,h}(x,a)$ is an overestimate of $Q^*_h(x,a)$ (so also an overestimate of $Q^{\epsilon,*}_h(x,a)$) for all $(x,a,h,k)$ simultaneously with a high probability. However, this result does not hold under Triple-Q because Triple-Q takes greedy actions with respect to the pseudo-Q-function instead of the reward Q-function. To overcome this challenge, we first add and subtract additional terms to obtain \begin{align} &\mathbb E \left[\sum_{k=1}^{K} \left( \sum_a \left\{{Q}_{1}^{\epsilon,*}{q}^{\epsilon,*}_1\right\}(x_{k,1},a)-Q_{k,1}(x_{k,1}, a_{k,1}) \right)\right]\nonumber\\ =& \mathbb{E}\left[ \sum_{k} \sum_a \left(\left\{{Q}_{1}^{\epsilon,*}{q}^{\epsilon,*}_1+\frac{Z_k}{\eta} C_{1}^{\epsilon,*}{q}^{\epsilon,*}_1\right\}(x_{k,1},a) - \left\{Q_{k,1}{q}^{\epsilon,*}_1 +\frac{Z_k}{\eta}C_{k,1}{q}^{\epsilon,*}_1\right\}(x_{k,1},a)\right)\right] \label{F-new}\\ &+ \mathbb{E}\left[\sum_{k} \left(\sum_a \left\{Q_{k,1} {q}^{\epsilon,*}_1\right\}(x_{k,1},a) - Q_{k,1} (x_{k,1},a_{k,1})\right)\right] +\mathbb{E}\left[ \sum_{k} \frac{Z_k}{\eta} \sum_a \left\{\left(C_{k,1} - {C}^{\epsilon,*}_1 \right){q}^{\epsilon,*}_1\right\}(x_{k,1},a) \right].\label{eq:(i)expanded-new} \end{align} We can see \eqref{F-new} is the difference of two pseudo-Q-functions. Using a three-dimensional induction (on step, episode, and frame), we will prove in Lemma \ref{le:qk-qpi-relation} that $\left\{Q_{k,h} +\frac{Z_k}{\eta}C_{k,h}\right\}(x,a)$ is an overestimate of $\left\{{Q}_{h}^{\epsilon,*}+\frac{Z_k}{\eta} C_{h}^{\epsilon,*}\right\}(x,a)$ (i.e. $\eqref{F-new}\leq 0$) for all $(x,a,h,k)$ simultaneously with a high probability. Since $Z_k$ changes from frame to frame, Triple-Q adds the extra bonus in line 21 so that the induction can be carried out over frames. Finally, to bound \eqref{eq:(i)expanded-new}, we use the Lyapunov-drift method and consider Lyapunov function $L_T=\frac{1}{2} Z_T^2,$ where $T$ is the frame index and $Z_T$ is the value of the virtual queue at the beginning of the $T$th frame. We will show in Lemma \ref{le:drift} that the Lyapunov-drift satisfies \begin{align} &\mathbb{E}[L_{T+1}-L_T] \leq \hbox{a negative drift}+H^4\iota+\epsilon^2- \frac{\eta}{K^\alpha}\sum_{k=TK^\alpha+1}^{(T+1)K^\alpha} \Phi_k , \label{outline:drift} \end{align} where \begin{align*} \Phi_k=\mathbb{E}\left[ \left(\sum_a \left\{Q_{k,1} {q}^{\epsilon,*}_1\right\}(x_{k,1},a) - Q_{k,1} (x_{k,1},a_{k,1})\right)\right] +\mathbb{E}\left[\frac{Z_k}{\eta} \sum_a \left\{\left(C_{k,1} - {C}^{\epsilon,*}_1 \right){q}^{\epsilon,*}_1\right\}(x_{k,1},a) \right], \end{align*} and we note that $\eqref{eq:(i)expanded-new}=\sum_k \Phi_k.$ Inequality \eqref{outline:drift} will be established by showing that Triple-Q takes actions to {\em almost} greedily reduce virtual-Queue $Z$ when $Z$ is large, which results in the negative drift in \eqref{outline:drift}. From \eqref{outline:drift}, we observe that \begin{align} &\mathbb{E}[L_{T+1}-L_T]\leq H^4\iota+\epsilon^2-\frac{\eta}{K^\alpha}\sum_{k=TK^\alpha+1}^{(T+1)K^\alpha} \Phi_k. \end{align} So we can bound \eqref{eq:(i)expanded-new} by applying the telescoping sum over the $K^{1-\alpha}$ frames on the inequality above: $$\eqref{eq:(i)expanded-new}=\sum_k\Phi_k \leq \frac{K^\alpha\mathbb{E}\left[L_1-L_{K^{1-\alpha}+1}\right]}{\eta}+\frac{K(H^4\iota+\epsilon^2)}{\eta}\leq \frac{K(H^4\iota+\epsilon^2)}{\eta},$$ where the last inequality holds because $L_1=0$ and $L_T\geq 0$ for all $T.$ Combining the bounds on \eqref{F-new} and \eqref{eq:(i)expanded-new}, we conclude that under our choices of $\iota,$ $\epsilon$ and $\eta,$ $$\eqref{step(i)}=\tilde{\cal O}(H^4S^\frac{1}{2}A^{\frac{1}{2}}K^{\frac{4}{5}}).$$ \end{itemize} Combining the results in the three steps above, we obtain the regret bound in Theorem \ref{thm:main}. \subsubsection{Detailed Proof} We next present the detailed proof. The first lemma bounds the difference between the original CMDP and its $\epsilon$-tightened version. The result is intuitive because the $\epsilon$-tightened version is a perturbation of the original problem and $\epsilon\leq \delta.$ \begin{lemma}\label{le:epsilon-dif} Given $\epsilon\leq \delta$, we have $$\mathbb{E}\left[ \sum_a \left\{Q_{1}^{*}q_1^*- {Q}_{1}^{\epsilon,*}{q}_1^{\epsilon,*}\right\}(x_{k,1},a)\right] \leq \frac{H \epsilon }{\delta}.$$ \hfill{$\square$} \end{lemma} \begin{proof} Given ${q}_h^*(x,a)$ is the optimal solution, we have $$\sum_{h,x,a} {q}_h^*(x,a)g_h(x,a) \geq \rho.$$ Under Assumption \ref{as:1}, we know that there exists a feasible solution $\{q^{\xi_1}_h(x,a)\}_{h=1}^H$ such that $$\sum_{h,x,a} q_h^{\xi_1}(x,a)g_h(x,a) \geq \rho+\delta.$$ We construct $q_h^{\xi_2}(x,a) = (1-\frac{\epsilon }{\delta})q^*_h(x,a) + \frac{\epsilon}{\delta} q^{\xi_1}_h(x,a),$ which satisfies that \begin{align*} \sum_{h,x,a} q_h^{\xi_2}(x,a)g_h(x,a) & = \sum_{h,x,a} \left( (1-\frac{\epsilon }{\delta}) q^*_h(x,a) +\frac{\epsilon }{\delta} q^{\xi_1}_h(x,a) \right)g_h(x,a)\geq \rho + \epsilon ,\\ \sum_{h,x,a} q_h^{\xi_2}(x,a) &= \sum_{x^\prime,a^\prime} p_{h-1} (x\vert x^\prime,a^\prime) q_{h-1}^{\xi_2}(x^\prime,a^\prime),\\ \sum_{h,x,a} q_h^{\xi_2}(x,a) &= 1. \end{align*} Also we have $q_h^{\xi_2}(x,a)\geq 0 $ for all $(h,x,a).$ Thus $\{q^{\xi_2}_h(x,a)\}_{h=1}^H$ is a feasible solution to the $\epsilon$-tightened optimization problem \eqref{eq:lp-epsilon}. Then given $\{{q}^{\epsilon,*}_h(x,a)\}_{h=1}^H$ is the optimal solution to the $\epsilon$-tightened optimization problem, we have \begin{align*} & \sum_{h,x,a} \left( {q}_h^{*}(x,a) - {q}_h^{\epsilon,*}(x,a)\right)r_h(x,a) \\ \leq & \sum_{h,x,a} \left( q_h^{*}(x,a) - q_h^{\xi_2}(x,a)\right)r_h(x,a) \\ \leq &\sum_{h,x,a} \left( q_h^{*}(x,a) - \left(1-\frac{\epsilon }{\delta} \right)q_h^*(x,a) - \frac{\epsilon }{\delta} q_h^{\xi_1}(x,a)\right)r_h(x,a) \\ \leq & \sum_{h,x,a} \left( q_h^{*}(x,a) - \left(1-\frac{\epsilon }{\delta} \right)q_h^*(x,a) \right)r_h(x,a) \\ \leq &\frac{\epsilon }{\delta} \sum_{h,x,a} q_h^{*}(x,a) r_h(x,a) \\ \leq & \frac{H\epsilon }{\delta}, \end{align*} where the last inequality holds because $0\leq r_h(x,a)\leq 1$ under our assumption. Therefore the result follows because \begin{align*} \sum_a Q_{1}^{*}(x_{k,1},a)q_1^*(x_{k,1},a) =&\sum_{h,x,a} {q}_h^{*}(x,a)r_h(x,a) \\ \sum_a {Q}_{1}^{\epsilon,*}(x_{k,1},a) {q}_1^{\epsilon,*}(x_{k,1},a) =&\sum_{h,x,a} {q}_h^{\epsilon,*}(x,a)r_h(x,a). \end{align*} \end{proof} The next lemma bounds the difference between the estimated Q-functions and actual Q-functions in a frame. The bound on \eqref{step:biase} is an immediate result of this lemma. \begin{lemma}\label{le:qk-qpi-bound} Under Triple-Q, we have for any $T\in[K^{1-\alpha}],$ \begin{align*} &\mathbb{E}\left[ \sum_{k=(T-1)K^\alpha+1}^{TK^\alpha} \left\{{Q}_{k,1} - Q_{1}^{\pi_k}\right\}(x_{k,1},a_{k,1}) \right] \leq H^2SA +\frac{H^3\sqrt{\iota} K^\alpha}{\chi} + \sqrt{H^2SA\iota K^{\alpha}(\chi+1)},\\ &\mathbb{E}\left[ \sum_{k=(T-1)K^\alpha+1}^{TK^\alpha} \left\{{C}_{k,1} - C_{1}^{\pi_k}\right\}(x_{k,1},a_{k,1}) \right] \leq H^2SA +\frac{H^3\sqrt{\iota} K^\alpha}{\chi} + \sqrt{H^2SA\iota K^{\alpha}(\chi+1)}. \end{align*} \end{lemma} \begin{proof} We will prove the result on the reward Q-function. The proof for the utility Q-function is almost identical. We first establish a recursive equation between a Q-function with the value-functions in the earlier episodes in the same frame. Recall that under Triple-Q, ${Q}_{k+1,h}(x,a)$, where $k$ is an episode in frame $T,$ is updated as follows: \begin{align*} {Q}_{k+1,h}(x,a) & = \begin{cases} (1-\alpha_t) {Q}_{k,h}(x,a)+\alpha_t\left(r_h(x,a)+ {V}_{k,h+1} (x_{k,h+1})+b_t \right) & \text{if $(x,a)= (x_{k,h},a_{k,h})$}\\ {Q}_{k,h}(x,a) & \text{otherwise} \end{cases}, \end{align*} where $t=N_{k,h}(x,a).$ Define $k_t$ to be the index of the episode in which the agent visits $(x,a)$ in step $h$ for the $t$th time in the current frame. The update equation above can be written as: \begin{align*} {Q}_{k,h}(x, a) = &(1-\alpha_t) {Q}_{k_t,h}(x, a) + \alpha_t \left( r_h(x, a) + {V}_{k_t,h+1} (x_{k_t,h+1})+b_t\right). \end{align*} Repeatedly using the equation above, we obtain \begin{align} {Q}_{k,h}(x, a) = &(1-\alpha_t)(1-\alpha_{t-1}){Q}_{k_{t-1},h}(x, a) + (1-\alpha_t)\alpha_{t-1}\left(r_h(x, a) + {V}_{k_{t-1},h+1}(x_{k_{t-1},h+1})+b_{t-1}\right)\nonumber\\ &+\alpha_t \left( r_h(x, a) + {V}_{k_t,h+1} (x_{k_t,h+1})+b_t\right)\nonumber \\ =&\cdots\nonumber\\ =& \alpha_t^0 Q_{(T-1)K^\alpha+1, h} (x,a)+ \sum_{i=1}^t\alpha_t^i \left(r_h(x, a) +{V}_{k_i,h+1} (x_{k_i,h+1}) + b_i \right)\nonumber\\ \leq & \alpha_t^0H + \sum_{i=1}^t\alpha_t^i \left(r_h(x,a)+{V}_{k_i,h+1}(x_{k_i,h+1})+ b_i\right),\end{align} where $\alpha_t^0=\prod_{j=1}^t(1-\alpha_j)$ and $\alpha_t^i=\alpha_i\prod_{j=i+1}^t(1-\alpha_j).$ From the inequality above, we further obtain \begin{align} \sum_{k=(T-1)K^\alpha+1}^{TK^\alpha} {Q}_{k,h} (x,a) \leq \sum_{k=(T-1)K^\alpha+1}^{TK^\alpha} \alpha_t^0 H+ \sum_{k=(T-1)K^\alpha+1}^{TK^\alpha} \sum_{i=1}^{N_{k,h}(x,a)}\alpha_{N_{k,h}}^i \left(r_h(x,a)+{V}_{k_i,h+1}(x_{k_i,h+1})+ b_i \right).\label{eq:Q-V} \end{align} The notation becomes rather cumbersome because for each $(x_{k,h}, a_{k,h}),$ we need to consider a corresponding sequence of episode indices in which the agent sees $(x_{k,h}, a_{k,h}).$ Next we will analyze a given sample path (i.e. a specific realization of the episodes in a frame), so we simplify our notation in this proof and use the following notation: \begin{align*} N_{k,h}=&N_{k,h}(x_{k,h},a_{k,h})\\ k^{(k,h)}_i=&k_i(x_{k,h},a_{k,h}), \end{align*} where $k^{(k,h)}_i$ is the index of the episode in which the agent visits state-action pair $(x_{k,h}, a_{k,h})$ for the $i$th time. Since in a given sample path, $(k,h)$ can uniquely determine $(x_{k,h},a_{k,h}),$ this notation introduces no ambiguity. Furthermore, we will replace $\sum_{k=(T-1)K^\alpha+1}^{TK^\alpha}$ with $\sum_k$ because we only consider episodes in frame $T$ in this proof. We note that \begin{equation} \sum_k\sum_{i=1}^{N_{k,h}} \alpha_{N_{k,h}}^i V_{k_i^{(k,h)}, h+1}\left(x_{k_i^{(k,h)},h+1}\right)\leq \sum_k V_{k, h+1} (x_{k,h+1})\sum_{t=N_{k,h}}^\infty \alpha_t^{N_{k,h}} \leq \left(1+\frac{1}{\chi}\right)\sum_k V_{k, h+1} (x_{k,h+1}),\label{eq:Vbound} \end{equation} where the first inequality holds because because $V_{k,h+1}(x_{k,h+1})$ appears in the summation on the left-hand side each time when in episode $k'>k$ in the same frame, the environment visits $(x_{k,h},a_{k,h})$ again, i.e. $(x_{k',h},a_{k',h})=(x_{k,h},a_{k,h}),$ and the second inequality holds due to the property of the learning rate proved in Lemma \ref{le:lr}-\ref{le:lr-d}. By substituting \eqref{eq:Vbound} into \eqref{eq:Q-V} and noting that $\sum_{i=1}^{N_{k,h}(x,a)}\alpha_{N_{k,h}}^i=1$ according to Lemma Lemma \ref{le:lr}-\ref{le:lr-b}, we obtain \begin{align*} &\sum_k Q_{k,h} (x_{k,h},a_{k,h}) \\ \leq &\sum_k \alpha_t^0H +\sum_k \left(r_h(x_{k,h},a_{k,h}) +V_{k,h+1}(x_{k,h+1})\right)+ \frac{1}{\chi} \sum_k V_{k,h+1}(x_{k,h+1})+\sum_k \sum_{i=1}^{N_{k,h}}\alpha_{N_{k,h}}^i b_i\\ \leq &\sum_k \left(r_h(x_{k,h},a_{k,h})+V_{k,h+1}(x_{k,h+1})\right) +HSA +\frac{H^2\sqrt{\iota} K^\alpha}{\chi} + \frac{1}{2}\sqrt{H^2SA\iota K^{\alpha}(\chi+1)}, \end{align*} where the last inequality holds because (i) we have \begin{align*} \sum_k \alpha_{N_{k,h}}^0 H =\sum_k H\mathbb{I}_{\{N_{k,h}=0\}}\leq HSA, \end{align*} (ii) $V_{k,h+1}(x_{k,h+1}) \leq H^2\sqrt{\iota}$ by using Lemma \ref{le:q1-bound}, and (iii) we know that \begin{align*} &\sum_k \sum_{i=1}^{N_{k,h}} \alpha_{N_{k,h}}^i b_i = \frac{1}{4}\sum_{k=(T-1)K^\alpha+1}^{TK^\alpha} \sum_{i=1}^{N_{k,h}} \alpha_{N_{k,h}}^i \sqrt{\frac{H^2\iota(\chi+1)}{\chi+i}} \leq \frac{1}{2}\sum_{k=(T-1)K^\alpha+1}^{TK^\alpha} \sqrt{\frac{H^2\iota(\chi+1)}{\chi+N_{k,h}}}\\ = &\frac{1}{2}\sum_{x,a}\sum_{n=1}^{N_{TK^\alpha,h}(x,a)}\sqrt{\frac{H^2\iota(\chi+1)}{\chi+n}} \leq \frac{1}{2}\sum_{x,a}\sum_{n=1}^{N_{TK^\alpha,h}(x,a)}\sqrt{\frac{H^2\iota(\chi+1)}{n}} \overset{(1)}{\leq} \sqrt{H^2SA\iota K^{\alpha}(\chi+1)}, \end{align*} where the last inequality above holds because the left hand side of $(1)$ is the summation of $K^\alpha$ terms and $\sqrt{\frac{H^2\iota(\chi+1)}{\chi+n}}$ is a decreasing function of $n.$ Therefore, it is maximized when $N_{TK^\alpha,h} = K^\alpha / SA$ for all $x,a,$ i.e. by picking the largest $K^\alpha$ terms. Thus we can obtain \begin{align*} &\sum_k Q_{k,h} (x_{k,h},a_{k,h}) -\sum_k Q_{h}^{\pi_k}(x_{k,h},a_{k,h})\\ \leq &\sum_k\left(V_{k,h+1}(x_{k,h+1})-\mathbb P_h V_{h+1}^{\pi_k}(x_{k,h},a_{k,h})\right) +HSA +\frac{H^2\sqrt{\iota}K^\alpha}{\chi} + \sqrt{H^2SA\iota K^{\alpha}(\chi+1)}\\ \leq &\sum_k\left(V_{k,h+1}(x_{k,h+1})-\mathbb P_h V_{h+1}^{\pi_k}(x_{k,h},a_{k,h})+V_{h+1}^{\pi_k}(x_{k,h+1})-V_{h+1}^{\pi_k}(x_{k,h+1})\right)\\ &+HSA +\frac{H^2\sqrt{\iota}K^\alpha}{\chi} + \sqrt{H^2SA\iota K^{\alpha}(\chi+1)}\\ =&\sum_k\left(V_{k,h+1}(x_{k,h+1}))-V_{h+1}^{\pi_k}(x_{k,h+1})-\mathbb P_h V_{h+1}^{\pi_k}(x_{k,h},a_{k,h})+\hat{\mathbb P}_h^k V^{\pi_k}_{h+1}(x_{k,h}, a_{k,h})\right)\\ &+HSA +\frac{H^2\sqrt{\iota}K^\alpha}{\chi} + \sqrt{H^2SA\iota K^{\alpha}(\chi+1)}\\ = & \sum_k\left(Q_{k,h+1}(x_{k,h+1},a_{k,h+1})-Q_{h+1}^{\pi_k}(x_{k,h+1},a_{k,h+1})-\mathbb P_h V_{h+1}^{\pi_k}(x_{k,h},a_{k,h})+\hat{\mathbb P}_h^k V^{\pi_k}_{h+1}(x_{k,h}, a_{k,h}\right)\\ &+HSA +\frac{H^2\sqrt{\iota}K^\alpha}{\chi} + \sqrt{H^2SA\iota K^{\alpha}(\chi+1)}. \end{align*} Taking the expectation on both sides yields \begin{align*} &\mathbb E\left[\sum_k Q_{k,h} (x_{k,h},a_{k,h}) -\sum_k Q_{h}^{\pi_k}(x_{k,h},a_{k,h})\right]\\ \leq & \mathbb E\left[\sum_k\left(Q_{k,h+1}(x_{k,h+1}, a_{k,h+1}))-Q_{h+1}^{\pi_k}(x_{k,h+1}, a_{k,h+1})\right)\right]+HSA +\frac{H^2\sqrt{\iota}K^\alpha}{\chi} + \sqrt{H^2SA\iota K^{\alpha}(\chi+1)}. \end{align*} Then by using the inequality repeatably, we obtain for any $h\in[H],$ \begin{align*} \mathbb E\left[\sum_k Q_{k,h} (x_{k,h},a_{k,h}) -\sum_k Q_{h}^{\pi_k}(x_{k,h},a_{k,h})\right] \leq & H^2SA +\frac{H^3\sqrt{\iota}K^\alpha}{\chi} + \sqrt{H^4SA\iota K^{\alpha}(\chi+1)}, \end{align*} so the lemma holds. \end{proof} From the lemma above, we can immediately conclude: \begin{align*} &\mathbb{E}\left[ \sum_{k=1}^{K} \left\{Q_{k,1} - Q_{1}^{\pi_k}\right\}(x_{k,1},a_{k,1}) \right] \leq H^2SA K^{1-\alpha} +\frac{H^3\sqrt{\iota}K}{\chi} + \sqrt{H^4SA\iota K^{2-\alpha}(\chi+1)}\\ &\mathbb{E}\left[ \sum_{k=1}^{K} \left\{C_{k,1} - C_{1}^{\pi_k}\right\}(x_{k,1},a_{k,1}) \right] \leq H^2SA K^{1-\alpha} +\frac{H^3\sqrt{\iota}K}{\chi} + \sqrt{H^4SA\iota K^{2-\alpha}(\chi+1)}. \end{align*} We now focus on \eqref{step(i)}, and further expand it as follows: \begin{align} &\eqref{step(i)}\nonumber\\ =&\mathbb E \left[\sum_{k=1}^{K} \left( \sum_a \left\{{Q}_{1}^{\epsilon,*}{q}^{\epsilon,*}_1\right\}(x_{k,1},a)-Q_{k,1}(x_{k,1}, a_{k,1}) \right)\right]\nonumber\\ =& \mathbb{E}\left[ \sum_{k} \sum_a \left\{\left({F}^{\epsilon,*}_{k,1} -F_{k,1}\right) {q}^{\epsilon,*}_1\right\}(x_{k,1},a) \right] \label{F}\\ &+ \mathbb{E}\left[\sum_{k} \left(\sum_a \left\{Q_{k,1} {q}^{\epsilon,*}_1\right\}(x_{k,1},a) - Q_{k,1} (x_{k,1},a_{k,1})\right)\right] +\mathbb{E}\left[ \sum_{k} \frac{Z_k}{\eta} \sum_a \left\{\left(C_{k,1} - {C}^{\epsilon,*}_1 \right){q}^{\epsilon,*}_1\right\}(x_{k,1},a) \right],\label{eq:(i)expanded} \end{align} where \begin{align*} F_{k,h}(x,a) &= Q_{k,h}(x,a) +\frac{Z_k}{\eta}C_{k,h}(x,a)\\ {F}_{h}^{\epsilon,*}(x,a) &= {Q}_{h}^{\epsilon,*}(x,a)+\frac{Z_k}{\eta} C_{h}^{\epsilon,*}(x,a). \end{align*} We first show \eqref{F} can be bounded using the following lemma. This result holds because the choices of the UCB bonuses and the additional bonuses added at the beginning of each frame guarantee that $F_{k,h}(x,a)$ is an over-estimate of ${F}_{h}^{\epsilon,*}(x,a)$ for all $k,$ $h$ and $(x,a)$ with a high probability. \begin{lemma} \label{le:qk-qpi-relation} With probability at least $1-\frac{1}{K^3},$ the following inequality holds simultaneously for all $(x,a,h,k)\in\mathcal{S}\times\mathcal{A}\times[H]\times[K]:$ \begin{equation} \left\{ F_{k,h}-F_{h}^{\pi}\right\}(x,a)\geq 0,\label{eq:qk-qpi-relation-c} \end{equation} which further implies that \begin{equation} \mathbb{E}\left[ \sum_{k=1}^{K} \sum_a \left\{\left({F}^{\epsilon,*}_{k,1} -F_{k,1}\right) {q}^{\epsilon,*}_1\right\}(x_{k,1},a) \right] \leq \frac{4H^4\iota}{\eta K}. \end{equation} \label{le:qk-qpi-relation-c} \end{lemma} \begin{proof} Consider frame $T$ and episodes in frame $T.$ Define $Z=Z_{(T-1)K^\alpha+1}$ because the value of the virtual queue does not change during each frame. We further define/recall the following notations: \begin{align*} F_{k,h}(x,a) = Q_{k,h}(x,a)+\frac{Z}{\eta}C_{k,h}(x,a), \quad & U_{k,h}(x)= V_{k,h}(x)+ \frac{Z}{\eta} W_{k,h}(x),\nonumber\\ F_{h}^\pi(x,a)= Q_{h}^\pi(x,a)+ \frac{Z}{\eta} C_{h}^\pi(x,a),\quad & U_{h}^\pi(x) = V_{h}^\pi(x)+ \frac{Z}{\eta}W_{h}^\pi(x). \end{align*} According to Lemma \ref{le:qk-qpi} in the appendix, we have \begin{align} &\{F_{k,h} - F_{h}^\pi\}(x,a) \nonumber\\ = &\alpha_t^0\left\{F_{(T-1)K^\alpha +1, h}-F_{h}^\pi\right\}(x,a) \nonumber\\ &+\sum_{i=1}^t\alpha_t^i\left(\left\{U_{k_i,h+1}-U_{h+1}^\pi \right\}(x_{k_i,h+1}) + \{(\hat{\mathbb{P}}_h^{k_i}-\mathbb{P}_h) U_{h+1}^{\pi}\}(x,a) + \left(1+\frac{Z}{\eta}\right)b_i\right)\nonumber\\ \geq&_{(a)} \alpha_t^0\left\{F_{(T-1)K^\alpha+1, h}-F_{h}^\pi\right\}(x,a) +\sum_{i=1}^t\alpha_t^i\left\{U_{k_i,h+1}-U_{h+1}^\pi \right\}(x_{k_i,h+1})\nonumber\\ = &_{(b)} \alpha_t^0\left\{F_{(T-1)K^\alpha+1, h}-F_{h}^\pi\right\}(x,a) +\sum_{i=1}^t\alpha_t^i\left(\max_a F_{k_i,h+1} (x_{k_i,h+1},a) -F_{h+1}^\pi(x_{k_i,h+1},\pi(x_{k_i,h+1})) \right)\nonumber\\ \geq &\alpha_t^0\left\{F_{(T-1)K^\alpha+1, h}-F_{h}^\pi\right\}(x,a)+ \sum_{i=1}^t\alpha_t^i\left\{F_{k_i,h+1} -F_{h+1}^\pi\right\}(x_{k_i,h+1},\pi(x_{k_i,h+1})), \label{eq:induction-F} \end{align} where inequality $(a)$ holds because of the concentration result in Lemma \ref{le:u-hoeffding} in the appendix and $$\sum_{i=1}^t\alpha_t^i(1 +\frac{Z}{\eta})b_i = \frac{1}{4}\sum_{i=1}^t\alpha_t^i(1 +\frac{Z}{\eta})\sqrt{\frac{H^2\iota(\chi+1)}{\chi + i}} \geq\frac{\eta +Z}{4\eta}\sqrt{\frac{H^2\iota(\chi+1)}{\chi + t}}$$ by using Lemma \ref{le:lr}-\ref{le:lr-c}, and equality $(b)$ holds because Triple-Q selects the action that maximizes $F_{k_i,h+1} (x_{k_i,h+1},a)$ so $U_{k_i,h+1}(x_{k_i,h+1})=\max_a F_{k_i,h+1} (x_{k_i,h+1},a)$. The inequality above suggests that we can prove $\{F_{k,h} - F_{h}^\pi\}(x,a)$ for any $(x,a)$ if (i) $$\left\{F_{(T-1)K^\alpha+1, h}-F_{h}^\pi\right\}(x,a)\geq 0,$$ i.e. the result holds at the beginning of the frame and (ii) $$\left\{F_{k',h+1} -F_{h+1}^\pi\right\}(x,a)\geq 0\quad\hbox{ for any }\quad k'<k$$ and $(x,a),$ i.e. the result holds for step $h+1$ in all the previous episodes in the same frame. We now prove the lemma using induction. We first consider $T=1$ and $h=H$ i.e. the last step in the first frame. In this case, inequality \eqref{eq:induction-F} becomes \begin{align} \{F_{k,H} - F_{H}^\pi\}(x,a) \geq \alpha_t^0\left\{H+\frac{Z_1}{\eta}H-F_{h}^\pi\right\}(x,a)\geq 0. \end{align} Based on induction, we can first conclude that \begin{align*} \{F_{k,h} - F_{h}^\pi\}(x,a) \geq 0 \end{align*} for all $h$ and $k\leq K^{\alpha}+1,$ where $\{F_{K^\alpha+1, h}\}_{h=1,\cdots, H}$ are the values before line 20, i.e. before adding the extra bonuses and thresholding Q-values at the end of a frame. Now suppose that \eqref{eq:qk-qpi-relation-c} holds for any episode $k$ in frame $T,$ any step $h,$ and any $(x,a).$ Now consider \begin{align} \left\{F_{TK^\alpha+1, h}-F_{h}^\pi\right\}(x,a)= Q_{TK^\alpha+1,h}(x,a)+\frac{Z_{TK^\alpha+1}}{\eta}C_{TK^\alpha+1,h}(x,a)-Q_{h}^\pi(x,a)- \frac{Z_{TK^\alpha+1}}{\eta} C_{h}^\pi(x,a).\label{eq:new-induction} \end{align} Note that if $Q^+_{TK^\alpha+1,h}(x,a)=C^+_{TK^\alpha+1,h}(x,a)=H,$ then $\eqref{eq:new-induction}\geq 0.$ Otherwise, from line 21-23, we have $Q^+_{TK^\alpha+1,h}(x,a)=Q^-_{TK^\alpha+1,h}(x,a)+\frac{2H^3\sqrt{\iota}}{\eta}<H$ and $C^+_{TK^\alpha+1,h}(x,a)=C^-_{TK^\alpha+1,h}(x,a)<H.$ Here, we use superscript $-$ and $+$ to indicate the Q-values before and after 21-24 of Triple-Q. Therefore, at the beginning of frame $T+1,$ we have \begin{align} \left\{F_{TK^\alpha+1, h}-F_{h}^\pi\right\}(x,a)=& Q^-_{TK^\alpha+1,h}(x,a)+\frac{Z}{\eta}C^-_{TK^\alpha+1,h}(x,a)-Q_{h}^\pi(x,a)- \frac{Z}{\eta} C_{h}^\pi(x,a)\nonumber\\ +& \frac{2H^3\sqrt{\iota}}{\eta}+\frac{Z_{TK^\alpha+1}-Z}{\eta}C^-_{TK^\alpha+1,h}(x,a)-\frac{Z_{TK^\alpha+1}-Z}{\eta} C_{h}^\pi(x,a)\nonumber\\ \geq_{(a)}&\frac{2H^3\sqrt{\iota}}{\eta}-2\frac{|Z_{TK^\alpha+1}-Z|}{\eta}H\nonumber\\ \geq_{(b)}& 0,\label{eq:induction-frame} \end{align} where inequality $(a)$ holds due to the induction assumption and the fact $C^-_{TK^\alpha+1,h}(x,a)<H,$ and $(b)$ holds because according to Lemma \ref{le:q1-bound}, $$|Z_{TK^\alpha+1}-Z_{TK^\alpha}|\leq \max\left\{\rho+\epsilon, \frac{\sum_{k=(T-1)K^\alpha+1}^{TK^\alpha}C_{k,1}(x_{k,1},a_{k,1})}{K^\alpha}\right\}\leq H^2\sqrt{\iota}.$$ Therefore, by substituting inequality \eqref{eq:induction-frame} into inequality \eqref{eq:induction-F}, we obtain for any $TK^\alpha + 1\leq k\leq (T+1)K^\alpha+1,$ \begin{align} \{F_{k,h} - F_{h}^\pi\}(x,a) \geq \sum_{i=1}^t\alpha_t^i\left\{F_{k_i,h+1} -F_{h+1}^\pi\right\}\left(x_{k_i,h+1},\pi(x_{k_i,h+1})\right). \end{align} Considering $h=H,$ the inequality becomes \begin{align} \{F_{k,H} - F_{H}^\pi\}(x,a) \geq 0. \end{align} By applying induction on $h$, we conclude that \begin{align} \{F_{k,h} - F_{h}^\pi\}(x,a) \geq 0. \end{align} holds for any $TK^\alpha + 1\leq k\leq (T+1)K^\alpha+1,$ $h,$ and $(x,a),$ which completes the proof of \eqref{eq:qk-qpi-relation-c}. Let $\cal E$ denote the event that \eqref{eq:qk-qpi-relation-c} holds for all $k,$ $h$ and $(x,a).$ Then based on Lemma \ref{le:q1-bound}, we conclude that \begin{align} &\mathbb{E}\left[ \sum_{k=1}^{K} \sum_a \left\{\left({F}^{\epsilon,*}_{k,1} -F_{k,1}\right) {q}^{\epsilon,*}_1\right\}(x_{k,1},a) \right]\nonumber\\ =& \mathbb{E}\left[\left. \sum_{k=1}^{K} \sum_a \left\{\left({F}^{\epsilon,*}_{k,1} -F_{k,1}\right) {q}^{\epsilon,*}_1\right\}(x_{k,1},a) \right| {\cal E}\right]\Pr({\cal E})\nonumber\\ &+ \mathbb{E}\left[\left. \sum_{k=1}^{K} \sum_a \left\{\left({F}^{\epsilon,*}_{k,1} -F_{k,1}\right) {q}^{\epsilon,*}_1\right\}(x_{k,1},a) \right| {\cal E}^c\right]\Pr({\cal E}^c)\nonumber\\ \leq& 2K \left(1+\frac{K^{1-\alpha}H^2\sqrt{\iota}}{\eta}\right)H^2\sqrt{\iota}\frac{1}{K^3}\leq \frac{4H^4\iota}{\eta K}.\label{eq:F-bound} \end{align} \end{proof} Next we bound \eqref{eq:(i)expanded} using the Lyapunov drift analysis on virtual queue $Z$. Since the virtual queue is updated every frame, we abuse the notation and define $Z_T$ to be the virtual queue used in frame $T.$ In particular, $Z_T=Z_{(T-1)K^\alpha+1}.$ We further define $$\bar{C}_T=\sum_{k=(T-1)K^\alpha+1}^{TK^\alpha}C_{k,1}(x_{k,1}, a_{k,1}).$$ Therefore, under Triple-Q, we have \begin{align}Z_{T+1}=\left(Z_{T}+\rho+\epsilon-\frac{\bar{C}_T}{K^\alpha}\right)^+ \label{eq:zupdate}\end{align} Define the Lyapunov function to be $$L_T = \frac{1}{2} Z_T^2.$$ The next lemma bounds the expected Lyapunov drift conditioned on $Z_T.$ \begin{lemma}\label{le:drift} Assume $\epsilon \leq \delta.$ The expected Lyapunov drift satisfies \begin{align} & \mathbb{E}\left[L_{T+1}-L_T\vert Z_T=z \right] \nonumber\\ \leq & \frac{1}{K^\alpha}\sum_{k=(T-1)K^\alpha+1}^{TK^\alpha}\left(-\eta \mathbb{E} \left[ \left.\sum_a \left\{Q_{k,1}{q}^{\epsilon,*}_1\right\}(x_{k,1},a)-Q_{k,1} (x_{k,1},a_{k,1}) \right\vert Z_T= z \right]\right.\nonumber\\ &\left.+ z \mathbb{E}\left[\left. \sum_a \left\{\left({C}^{\epsilon,*}_1-C_{k,1}\right){q}^{\epsilon,*}_1\right\}(x_{k,1},a)\right\vert Z_T=z \right]\right) +H^4\iota+\epsilon^2. \label{eq:drift-inq} \end{align} \end{lemma} \begin{proof} Based on the definition of $L_T,$ the Lyapunov drift is \begin{align*} L_{T+1}-L_T \leq & Z_T\left(\rho+ \epsilon - \frac{\bar{C}_T}{K^\alpha} \right) + \frac{\left( \frac{\bar{C}_T}{K^\alpha} +\epsilon -\rho\right)^2}{2} \\ \leq & Z_T\left(\rho +\epsilon -\frac{\bar{C}_T}{K^\alpha} \right)+H^4\iota+\epsilon^2\\ \leq & \frac{Z_T}{K^\alpha}\sum_{k=TK^\alpha+1}^{(T+1)K^\alpha} \left(\rho +\epsilon - C_{k,1}(x_{k,1},a_{k,1}) \right)+H^4\iota+\epsilon^2 \end{align*} where the first inequality is a result of the upper bound on $\vert C_{k,1} (x_{k,1},a_{k,1})\vert$ in Lemma \ref{le:q1-bound}. Let $\{q^{\epsilon}_h\}_{h=1}^H$ be a feasible solution to the tightened LP \eqref{eq:lp-epsilon}. Then the expected Lyapunov drift conditioned on $Z_T=z$ is \begin{align} & \mathbb{E}\left[L_{T+1}-L_T\vert Z_T=z \right] \nonumber\\ \leq & \frac{1}{K^\alpha}\sum_{k=(T-1)K^\alpha+1}^{TK^\alpha} \left(\mathbb{E}\left[\left.z\left( \rho+ \epsilon -C_{k,1} (x_{k,1},a_{k,1}) \right) -\eta Q_{k,1}(x_{k,1},a_{k,1}) \right\vert Z_T=z \right] + \eta\mathbb{E}\left[\left. Q_{k,1} (x_{k,1},a_{k,1}) \right\vert Z_T=z \right]\right)\nonumber\\ &+ H^4\iota +\epsilon^2. \label{eq:drift-1} \end{align} Now we focus on the term inside the summation and obtain that \begin{align*} &\left(\mathbb{E}\left[\left.z\left( \rho+ \epsilon -C_{k,1} (x_{k,1},a_{k,1}) \right) -\eta Q_{k,1}(x_{k,1},a_{k,1}) \right\vert Z_T=z \right] + \eta\mathbb{E}\left[\left. Q_{k,1} (x_{k,1},a_{k,1}) \right\vert Z_T=z \right]\right) \\ \leq &_{(a)} z(\rho+\epsilon)- \mathbb{E} \left[\left. \eta\left(\sum_a\left\{\frac{z}{\eta} C_{k,1}q^{\epsilon}_1 + Q_{k,1}q^{\epsilon}_1\right\}(x_{k,1},a)\right) \right\vert Z_T=z \right] + \eta\mathbb{E}\left[\left. Q_{k,1} (x_{k,1},a_{k,1}) \right\vert Z_T=z \right]\nonumber\\ = & \mathbb{E} \left[ \left. z\left( \rho +\epsilon -\sum_aC_{k,1} (x_{k,1},a)q^{\epsilon}_1(x_{k,1},a) \right) \right\vert Z_T=z \right]\\ &-\mathbb{E}\left[\left. \eta \sum_a Q_{k,1} (x_{k,1},a)q^{\epsilon}_1(x_{k,1},a) - \eta Q_{k,1} (x_{k,1},a_{k,1})\right\vert Z_T=z\right] \nonumber\\ =& \mathbb{E} \left[ z\left(\left.\rho +\epsilon - \sum_a C^{\epsilon}_1 (x_{k,1},a)q^{\epsilon}_1(x_{k,1},a) \right) \right\vert Z_T=z \right]\\ &-\mathbb{E}\left[\left. \eta \sum_a Q_{k,1} (x_{k,1},a)q^{\epsilon}_1(x_{k,1},a)- \eta Q_{k,1} (x_{k,1},a_{k,1})\right\vert Z_T=z\right] + \mathbb{E} \left[\left. z \sum_a \left\{(C^{\epsilon}_1-C_{k,1})q^{\epsilon}_1\right\}(x_{k,1},a) \right\vert Z_T=z \right] \nonumber\\ \leq & -\eta \mathbb{E} \left[\left. \sum_a Q_{k,1} (x_{k,1},a)q^{\epsilon}_1(x_{k,1},a) - Q_{k,1} (x_{k,1},a_{k,1}) \right\vert Z_T=z \right] + \mathbb{E}\left[\left. z \sum_a \left\{ (C^\epsilon_1-C_{k,1})q^{\epsilon}_1\right\}(x_{k,1},a)\right\vert Z_T=z \right], \end{align*} where inequality $(a)$ holds because $a_{k,h}$ is chosen to maximize $ Q_{k,h} (x_{k,h},a) + \frac{Z_T}{\eta} C_{k,h} (x_{k,h},a)$ under Triple-Q, and the last equality holds due to that $\{q^{\epsilon}_h(x,a)\}_{h=1}^H$ is a feasible solution to the optimization problem \eqref{eq:lp-epsilon}, so \begin{align*} \left(\rho +\epsilon -\sum_a {C}_1^{\epsilon}(x_{k,1},a)q^{\epsilon}_1(x_{k,1},a) \right)&=\left(\rho +\epsilon -\sum_{h,x,a}g_h(x,a){q}^{\epsilon}_h(x,a) \right)\leq 0. \end{align*} Therefore, we can conclude the lemma by substituting ${q}^{\epsilon}_h(x,a)$ with the optimal solution ${q}^{\epsilon,*}_h(x,a)$. \end{proof} After taking expectation with respect to $Z,$ dividing $\eta$ on both sides, and then applying the telescoping sum, we obtain \begin{align} & \mathbb{E} \left[\sum_{k=1}^{K} \left(\sum_a \left\{Q_{k,1} {q}^{\epsilon,*}_1\right\}(x_{k,1},a) - Q_{k,1} (x_{k,1},a_{k,1})\right) \right] +\mathbb{E}\left[ \sum_{k=1}^{K} \frac{Z_k}{\eta} \sum_a \left\{\left(C_{k,1} - {C}^{\epsilon,*}_1 \right){q}^{\epsilon,*}_1\right\}(x_{k,1},a) \right] \nonumber\\ \leq & \frac{K^\alpha \mathbb{E}\left[L_{1}-L_{K^{1-\alpha}+1}\right]}{\eta} + \frac{K\left(H^4\iota+\epsilon^2\right)}{\eta}\leq \frac{K\left(H^4\iota+\epsilon^2\right)}{\eta}\label{eq:ldrift}, \end{align} where the last inequality holds because that $L_1=0$ and $L_{T+1}$ is non-negative. Now combining Lemma \ref{le:qk-qpi-relation} and inequality \eqref{eq:ldrift}, we conclude that \begin{align*} \eqref{step(i)}\leq \frac{K\left(H^4\iota+\epsilon^2\right)}{\eta}+\frac{4H^4\iota}{\eta K}. \end{align*} Further combining inequality above with Lemma \ref{le:epsilon-dif} and Lemma \ref{le:qk-qpi-bound}, \begin{align} \text{Regret} (K) \leq \frac{KH\epsilon}{\delta} + H^2SA K^{1-\alpha} +\frac{H^3\sqrt{\iota}K}{\chi} + \sqrt{H^4SA\iota K^{2-\alpha}(\chi+1)}+ \frac{K\left(H^4\iota+\epsilon^2\right)}{\eta}+\frac{4H^4\iota}{\eta K}. \label{eq:regret-final} \end{align} By choosing $\alpha=0.6,$ i.e each frame has $K^{0.6}$ episodes, $\chi=K^{0.2},$ $\eta=K^{0.2},$ and $\epsilon = \frac{8\sqrt{SAH^6\iota^3}}{K^{0.2}},$ we conclude that when $K \geq \left(\frac{8\sqrt{SAH^6\iota^3}}{\delta}\right)^5,$ which guarantees that $\epsilon<\delta/2,$ we have \begin{align} \text{Regret} (K) \leq \frac{13}{\delta} H^4 {\sqrt{SA\iota^3}}{K^{0.8}} +\frac{4H^4\iota}{ K^{1.2}} = \tilde{\cal O}\left(\frac{1 }{\delta}H^4 S^{\frac{1}{2}}A^{\frac{1}{2}}K^{0.8} \right). \end{align} \subsection{Constraint Violation} \subsubsection{Outline of the Constraint Violation Analysis} Again, we use $Z_T$ to denote the value of virtual-Queue in frame $T.$ According to the virtual-Queue update defined in {Triple-Q}, we have \begin{align*} Z_{T+1} = \left( Z_T + \rho + \epsilon -\frac{\bar{C}_T}{K^\alpha}\right)^+ \geq Z_T + \rho + \epsilon -\frac{\bar{C}_T}{K^\alpha}, \end{align*} which implies that \begin{align*} \sum_{k=(T-1)K^\alpha+1}^{TK^\alpha}\left(-C_{1}^{\pi_k} (x_{k,1},a_{k,1}) +\rho \right) \leq K^\alpha\left(Z_{T+1} - Z_T \right)+ \sum_{k=(T-1)K^\alpha+1}^{TK^\alpha} \left(\left\{C_{k,1}- C_{1}^{\pi_k} \right\} (x_{k,1},a_{k,1}) - \epsilon \right). \end{align*} Summing the inequality above over all frames and taking expectation on both sides, we obtain the following upper bound on the constraint violation: \begin{align} \mathbb{E} \left[\sum^{K}_{k=1}\rho-C_{1}^{\pi_k} (x_{k,1},a_{k,1}) \right] \leq -K\epsilon + K^\alpha \mathbb{E}\left[ Z_{K^{1-\alpha}+1} \right]+\mathbb{E}\left[\sum_{k=1}^K\left\{C_{k,1}- C_{1}^{\pi_k}\right\} (x_{k,1},a_{k,1})\right],\label{eq:violation} \end{align} where we used the fact $Z_1=0.$ In Lemma \ref{le:qk-qpi-bound}, we already established an upper bound on the estimation error of $C_{k,1}:$ \begin{align} \mathbb{E}\left[\sum_{k=1}^K\left\{C_{k,1}-C_{1}^{\pi_k}\right\} (x_{k,1},a_{k,1})\right]\leq H^2SA K^{1-\alpha} +\frac{H^3 \sqrt{\iota} K}{\chi} + \sqrt{H^4SA\iota K^{2-\alpha}(\chi+1)}. \label{eq:C-error} \end{align} Next, we study the moment generating function of $Z_T,$ i.e. $\mathbb{E}\left[e^{rZ_T}\right]$ for some $r>0.$ Based on a Lyapunov drift analysis of this moment generating function and Jensen's inequality, we will establish the following upper bound on $Z_T$ that holds for any $1\leq T\leq K^{1-\alpha}+1$ \begin{align} \mathbb{E}[ Z_{T}] \leq & \frac{54H^4\iota}{\delta}\log \left( \frac{16H^2\sqrt{\iota}}{\delta} \right) +\frac{16H^2\iota}{K^2\delta} + \frac{4\eta\sqrt{H^2\iota} }{\delta}.\label{eq:Z_T} \end{align} Under our choices of $\epsilon,$ $\alpha,$ $\chi,$ $\eta$ and $\iota,$ it can be easily verified that $K\epsilon$ dominates the upper bounds in \eqref{eq:C-error} and \eqref{eq:Z_T}, which leads to the conclusion that the constraint violation because zero when $K$ is sufficiently large in Theorem \ref{thm:main}. \subsubsection{Detailed Proof} To complete the proof, we need to establish the following upper bound on $\mathbb E[Z_{T+1}]$ based on a bound on the moment generating function. \begin{lemma}\label{le:zk-bound} Assuming $\epsilon \leq \frac{\delta}{2},$ we have for any $1\leq T\leq K^{1-\alpha}$ \begin{align} \mathbb{E}[ Z_{T}] \leq & \frac{54H^4\iota}{\delta}\log \left( \frac{16H^2\sqrt{\iota}}{\delta} \right) +\frac{16H^2\iota}{K^2\delta} + \frac{4\eta\sqrt{H^2\iota} }{\delta}. \label{eq:zk-bound} \end{align} \end{lemma} The proof will also use the following lemma from \cite{Nee_16}. \begin{lemma}\label{le:drift-bond-cond} Let $S_t$ be the state of a Markov chain, $L_t$ be a Lyapunov function with $L_0=l_0,$ and its drift $\Delta_t= L_{t+1}-L_t.$ Given the constant $\gamma$ and $v$ with $0<\gamma\leq v,$ suppose that the expected drift $\mathbb{E}[\Delta_t\vert S_t=s]$ satisfies the following conditions: \begin{itemize} \item[(1)] There exists constant $\gamma>0$ and $\theta_t>0$ such that $\mathbb{E}[\Delta_t\vert S_t=s]\leq -\gamma$ when $L_t\geq \theta_t.$ \item[(2)] $\vert L_{t+1}-L_t\vert \leq v$ holds with probability one. \end{itemize} Then we have $$\mathbb{E}[e^{rL_t}]\leq e^{rl_0}+\frac{2e^{r(v+\theta_t)}}{r\gamma},$$ where $r=\frac{\gamma}{v^2+v\gamma/3}.$\hfill{$\square$} \end{lemma} \begin{proof}[Proof of Lemma \ref{le:zk-bound}] We apply Lemma \ref{le:drift-bond-cond} to a new Lyapunov function: $$\bar{L}_T= Z_T.$$ To verify condition (1) in Lemma \ref{le:drift-bond-cond}, consider $\bar{L}_T =Z_T\geq \theta_T =\frac{4(\frac{4H^2\iota}{K^{2}}+ \eta \sqrt{H^2\iota}+ H^4\iota+\epsilon^2 )}{\delta}$ and $2\epsilon\leq \delta.$ The conditional expected drift of $\bar{L}_T$ is \begin{align*} &\mathbb{E} \left[ Z_{T+1} - Z_T \vert Z_T=z\right]\\ =& \mathbb{E}\left[ \left. \sqrt{Z_{T+1}^2} - \sqrt{z^2} \right\vert Z_T=z \right] \\ \leq & \frac{1}{2z} \mathbb{E} \left[ \left. Z_{T+1}^2 - z^2 \right\vert Z_T=z\right]\\ \leq_{(a)}& -\frac{\delta}{2} + \frac{\frac{4H^2\iota}{K^{2}}+ \eta \sqrt{H^2\iota}+ H^4\iota+\epsilon^2 }{z} \\ \leq & -\frac{\delta}{2} + \frac{\frac{4H^2\iota}{K^{2}}+ \eta \sqrt{H^2\iota}+ H^4\iota+\epsilon^2 }{\theta_T}\\ = & -\frac{\delta}{4}, \end{align*} where inequality ($a$) is obtained according to Lemma \ref{le:drift_epi_neg}; and the last inequality holds given $z \geq\theta_T.$ To verify condition (2) in Lemma \ref{le:drift-bond-cond}, we have $$Z_{T+1}-Z_T \leq \vert Z_{T+1} - Z_{T}\vert \leq \left|\rho+\epsilon -\bar{C}_T\right|\leq (H^2+\sqrt{H^4\iota})+\epsilon\leq 2\sqrt{H^4\iota},$$ where the last inequality holds because $2\epsilon\leq \delta\leq 1.$ Now choose $\gamma = \frac{\delta}{4}$ and $v=2\sqrt{H^4\iota}.$ From Lemma \ref{le:drift-bond-cond}, we obtain \begin{align} \mathbb{E}\left[e^{rZ_T}\right]\leq e^{rZ_1} + \frac{2e^{r(v+\theta_T)}}{r\gamma},\quad\hbox{where}\quad r=\frac{\gamma}{v^2+v\gamma/3}. \label{eq:rzk-bound} \end{align} By Jensen's inequality, we have $$e^{r\mathbb{E}\left[ Z_T \right] }\leq \mathbb{E}\left[e^{r Z_T }\right],$$ which implies that \begin{align*} & \mathbb{E}[ Z_T] \leq \frac{1}{r}\log{\left(1 + \frac{2e^{r(v+\theta_T)}}{r\gamma} \right)} \\ = & \frac{1}{r}\log{\left( 1 + \frac{6v^2+2v\gamma}{3\gamma^2} e^{r(v+\theta_T)} \right)}\\ \leq & \frac{1}{r}\log{\left(1+ \frac{8v^2}{3\gamma^2} e^{r(v+\theta_T)} \right)}\\ \leq & \frac{1}{r}\log{\left(\frac{11v^2}{3\gamma^2} e^{r(v+\theta_T)} \right)}\\ \leq & \frac{4v^2}{3\gamma}\log{\left(\frac{11v^2}{3\gamma^2} e^{r(v+\theta_T)} \right)}\\ \leq & \frac{3v^2}{\gamma} \log \left(\frac{2v}{\gamma} \right) + v + \theta_T \\ \leq&\frac{3v^2}{\gamma} \log \left(\frac{2v}{\gamma} \right)+ v + \frac{4(\frac{4H^2\iota}{K^{2}}+ \eta \sqrt{H^2\iota}+ H^4\iota+\epsilon^2 )}{\delta} \\ = & \frac{48H^4\iota}{\delta}\log \left( \frac{16H^2\sqrt{\iota}}{\delta} \right) + 2\sqrt{H^4\iota} + \frac{4(\frac{4H^2\iota}{K^{2}}+ \eta \sqrt{H^2\iota}+ H^4\iota+\epsilon^2 )}{\delta} \\ \leq & \frac{54H^4\iota}{\delta}\log \left( \frac{16H^2\sqrt{\iota}}{\delta} \right) +\frac{16H^2\iota}{K^2\delta} + \frac{4\eta\sqrt{H^2\iota} }{\delta} =\tilde{\cal O}\left(\frac{\eta H}{\delta}\right), \end{align*} which completes the proof of Lemma \ref{le:zk-bound}. \end{proof} Substituting the results from Lemmas \ref{le:qk-qpi-bound} and \ref{le:zk-bound} into \eqref{eq:violation}, under assumption $K \geq \left(\frac{16\sqrt{SAH^6\iota^3}}{\delta} \right)^5,$ which guarantees $\epsilon\leq \frac{\delta}{2}.$ Then by using the facts that $\epsilon = \frac{8\sqrt{SAH^6\iota^3}}{ K^{0.2}},$ we can easily verify that \begin{align*} &\hbox{Violation}(K) \leq \frac{54H^4{\iota}K^{0.6} }{\delta}\log{\frac{16H^2\sqrt{\iota}}{\delta}} +\frac{4\sqrt{H^2\iota}}{\delta}K^{0.8}- 5\sqrt{SAH^6\iota^3}K^{0.8}. \end{align*} If further we have $K\geq e^{\frac{1}{\delta}},$ we can obtain $$\hbox{Violation}(K) \leq \frac{54H^4{\iota}K^{0.6} }{\delta}\log{\frac{16H^2\sqrt{\iota}}{\delta}} - \sqrt{SAH^6\iota^3}K^{0.8} = 0.$$ Now to prove the high probability bound, recall that from inequality \eqref{eq:zupdate}, we have \begin{align} \sum^{K}_{k=1}\rho-C_{1}^{\pi_k} (x_{k,1},a_{k,1}) \leq -K\epsilon + K^\alpha Z_{K^{1-\alpha}+1} +\sum_{k=1}^K\left\{C_{k,1}- C_{1}^{\pi_k}\right\} (x_{k,1},a_{k,1}).\label{eq:violation-bound} \end{align} According to inequality \eqref{eq:rzk-bound}, we have $$\mathbb{E}\left[e^{rZ_T}\right]\leq e^{rZ_1} + \frac{2e^{r(v+\theta_T)}}{r\gamma}\leq \frac{11v^2}{3\gamma^2} e^{r(v+\theta_T)},$$ which implies that \begin{align} &\Pr\left(Z_T \geq \frac{1}{r}\log \left( \frac{11v^2}{3\gamma^2} \right) +2(v+\theta_T)\right) \nonumber\\ = & \Pr (e^{rZ_T} \geq e^{\log \left( \frac{11v^2}{3\gamma^2} \right) +2r(v+\theta_T) } )\nonumber \\ \leq & \frac{\mathbb E [e^{rZ_T}]}{ \frac{11v^2}{3\gamma^2} e^{2r(v+\theta_T)}} \nonumber \\ \leq & \frac{1}{e^{r(v+\theta_T)} }= \tilde{\mathcal{O}}\left(e^{-\eta} \right)\label{eq:high-1}, \end{align} where the first inequality is from the Markov inequality. In the proof of Lemma \ref{le:qk-qpi-bound}, we have shown \begin{align} &\left\vert \sum_{k=(T-1)K^\alpha+1}^{TK^\alpha} C_{k,h} (x_{k,h},a_{k,h}) - C_{h}^{\pi_k}(x_{k,h},a_{k,h})\right\vert \nonumber\\ \leq &\left\vert \sum_{k=(T-1)K^\alpha+1}^{TK^\alpha} C_{k,h+1}(x_{k,h+1},a_{k,h+1})-C_{h+1}^{\pi_k}(x_{k,h+1},a_{k,h+1})\right\vert + \left\vert \sum_{k=(T-1)K^\alpha+1}^{TK^\alpha} (\hat{\mathbb P}_h^k-\mathbb P_h) V_{h+1}^{\pi_k}(x_{k,h},a_{k,h})\right\vert \nonumber\\ &+HSA +\frac{H^2\sqrt{\iota}K^\alpha}{\chi} + \sqrt{H^2SA\iota K^{\alpha}(\chi+1)} \label{eq:probbound} \end{align} Following a similar proof as the proof of Lemma \ref{le:u-hoeffding}, we can prove that $$\left\vert \sum_{k=(T-1)K^\alpha+1}^{TK^\alpha} (\hat{\mathbb P}_h^k-\mathbb P_h) V_{h+1}^{\pi_k}(x_{k,h},a_{k,h})\right\vert \leq \frac{1}{4}\sqrt{H^2\iota K^\alpha}$$ holds with probability at least $1-\frac{1}{K^3}$. By iteratively using inequality \eqref{eq:probbound} over $h$ and by summing it over all frames, we conclude that with probability at at least $1-\frac{1}{K^2},$ \begin{align} \left\vert \sum_{k=1}^K\{ C_{k,1}-C_1^{\pi_k}\}(x_{k,1},a_{k,1})\right\vert \leq & K^{1-\alpha}H^2SA +\frac{H^3\sqrt{\iota}K}{\chi} + \sqrt{H^4SA\iota K^{2-\alpha}(\chi+1)}+\frac{1}{4}\sqrt{H^4\iota K^{2-\alpha}}\nonumber \\ \leq & 4 \sqrt{H^4SA\iota}K^{0.8},\label{eq:high-2} \end{align} where the last inequality holds because $\alpha=0.6$ and $\chi=K^{0.2}.$ Now, by combining inequalities \eqref{eq:high-1} and \eqref{eq:high-2}, and using the union bound, we can show that when $K \geq \max\left\{\left(\frac{8\sqrt{SAH^6\iota^3}}{\delta}\right)^5,e^{\frac{1}{\delta}}\right\},$ with probability at least $1-\tilde{\mathcal{O}}\left(e^{-K^{0.2}} + \frac{1}{K^2}\right)$ \begin{align} & \sum^{K}_{k=1}\rho-C_{1}^{\pi_k} (x_{k,1},a_{k,1}) \nonumber\\ &\leq -K\epsilon+ K^\alpha\left(\frac{1}{r}\log \left( \frac{11v^2}{3\gamma^2} \right) +2(v+\theta_T) \right) + 4 \sqrt{H^4SA\iota}K^{0.8} \nonumber\\ &\leq -\sqrt{SAH^6\iota^3}K^{0.8} \leq 0, \end{align} which completes the proof of our main result. \section{{Triple-Q}} In this section, we introduce {Triple-Q} for CMDPs. The design of our algorithm is based on the primal-dual approach in optimization. While RL algorithms based on the primal-dual approach have been developed for CMDPs \cite{DinWeiYan_20,DinZhaBas_20,QiuWeiYan_20,EfrManPir_20}, a model-free RL algorithm with sublinear regrets and {\em zero} constraint violation is new. The design of {Triple-Q} is based on the primal-dual approach in optimization. Given Lagrange multiplier $\lambda,$ we consider the Lagrangian of problem \eqref{eq:obj} from a given initial state $x_1:$ \begin{align} &\max_\pi V_{1}^\pi(x_1)+ \lambda\left(W_{1}^\pi(x_1)-\rho\right)\label{eq:lag}\\ =& \max_\pi \mathbb{E}\left[\sum_{h=1}^H r_h(x_h,\pi_h(x_h))+\lambda g_h(x_h,\pi_h(x_h)) \right]-\lambda\rho,\nonumber \end{align} which is an unconstrained MDP with reward $r_h(x_h,\pi_h(x_h))+\lambda g_h(x_h,\pi_h(x_h))$ at step $h.$ Assuming we solve the unconstrained MDP and obtain the optimal policy, denoted by $\pi^*_\lambda,$ we can then update the dual variable (the Lagrange multiplier) using a gradient method: $$\lambda \leftarrow \left(\lambda +\rho - \mathbb E\left[W_1^{\pi_\lambda^*}(x_1)\right]\right)^+.$$ While primal-dual is a standard approach, analyzing the finite-time performance such as regret or sample complexity is particularly challenging. For example, over a finite learning horizon, we will not be able to exactly solve the unconstrained MDP for given $\lambda.$ Therefore, we need to carefully design how often the Lagrange multiplier should be updated. If we update it too often, then the algorithm may not have sufficient time to solve the unconstrained MDP, which leads to divergence; and on the other hand, if we update it too slowly, then the solution will converge slowly to the optimal solution and will lead to large regret and constraint violation. Another challenge is that when $\lambda$ is given, the primal-dual algorithm solves a problem with an objective different from the original objective and does not consider any constraint violation. Therefore, even when the asymptotic convergence may be established, establishing the finite-time regret is still difficult because we need to evaluate the difference between the policy used at each step and the optimal policy. Next we will show that a low-complexity primal-dual algorithm can converge and have sublinear regret and {\em zero} constraint violation when carefully designed. In particular, {Triple-Q} includes the following key ideas: \begin{itemize}[leftmargin=*] \item A sub-gradient algorithm for estimating the Lagrange multiplier, which is updated at the beginning of each frame as follows: \begin{align} Z \leftarrow \left(Z+ \rho+\epsilon- \frac{\bar{C}}{K^\alpha}\right)^+, \label{eq:vq} \end{align} where $(x)^+=\max\{x,0\}$ and $\bar{C}$ is the summation of all $C_{1}(x_{1},a_{1})$s of the episodes in the previous frame. We call $Z$ a virtual queue because it is terminology that has been widely used in stochastic networks (see e.g. \cite{Nee_10,SriYin_14}). If we view $\rho+\epsilon$ as the number of jobs that arrive at a queue within each frame and $\bar{C}$ as the number of jobs that leave the queue within each frame, then $Z$ is the number of jobs that are waiting at the queue. Note that we added extra utility $\epsilon$ to $\rho.$ By choosing $\epsilon =\frac{8\sqrt{SAH^6\iota^3}}{K^{0.2}}$, the virtual queue pessimistically estimates constraint violation so Triple-Q achieves {\em zero} constraint violation when the number of episodes is large. \item A carefully chosen parameter $\eta=K^{0.2}$ so that when $\frac{Z}{\eta}$ is used as the estimated Lagrange multiplier, it balances the trade-off between maximizing the cumulative reward and satisfying the constraint. \item Carefully chosen learning rate $\alpha_t$ and Upper Confidence Bound (UCB) bonus $b_t$ to guarantee that the estimated Q-value does not significantly deviate from the actual Q-value. We remark that the learning rate and UCB bonus proposed for unconstrained MDPs \cite{JinAllZey_18} do not work here. Our learning rate is chosen to be $\frac{K^{0.2}+1}{K^{0.2}+t},$ where $t$ is the number of visits to a given (state, action) pair in a particular step. This decays much slower than the classic learning rate $\frac{1}{t}$ or $\frac{H+1}{H+t}$ used in \cite{JinAllZey_18}. The learning rate is further reset from frame to frame, so Triple-Q can continue to learn the pseudo-Q-values that vary from frame to frame due to the change of the virtual-Queue (the Lagrange multiplier). \end{itemize} We now formally introduce {Triple-Q}. A detailed description is presented in Algorithm \ref{alg:triple-Q}. The algorithm only needs to know the values of $H,$ $A,$ $S$ and $K,$ and no other problem-specific values are needed. Furthermore, Triple-Q includes updates of two Q-functions per step: one for $Q_{h}$ and one for $C_{h};$ and one simple virtual queue update per frame. So its computational complexity is similar to SARSA. \begin{algorithm}[htb] \label{alg:triple-Q} \SetAlgoLined Choose $\chi = K^{0.2},$ $\eta= K^{0.2},$ $\iota=128\log\left(\sqrt{2SAH}K\right),\alpha=0.6$ and $\epsilon = \frac{8\sqrt{SAH^6\iota^3}}{K^{0.2}}$ \; Initialize $Q_{h}(x,a)=C_{h}(x,a)\leftarrow H$ and $Z=\bar{C}=N_{h}(x,a)=V_{H+1}(x)=W_{H+1}(x)\leftarrow 0$ for all $(x,a,h)\in{\cal S}\times {\cal A}\times [H]$\; \For{episode $k = 1,\dots,K $ }{ Sample the initial state for episode $k:$ $x_{1} \sim \mu_0$\; \For{step $h=1,\dots,H+1$}{ \If{$h\leq H$ \tcp*{\small take a greedy action based on the pseudo-Q-function}}{ Take action $a_{h} \leftarrow \arg\max_a\left( Q_{h} (x_{h},a) + \frac{Z}{\eta}C_{h}(x_{h},a)\right)$\; Observe $r_h(x_{h},a_{h}), g_h(x_{h},a_{h}), $ and $x_{h+1}$ \; $N_{h}(x_{h},a_{h})\leftarrow N_{h}(x_{h},a_{h})+1,V_{h}(x_{h})\leftarrow Q_{h}(x_{h},a_{h}), W_{h}(x_{h})\leftarrow C_{h}(x_{h},a_{h})$; } \If{$h\geq 2$ \tcp*{\small update the Q-values for $(x_{h-1},a_{h-1})$ after observing $(s_h,a_h)$}}{ Set $t=N_{h-1}(x_{h-1},a_{h-1}), b_t = \frac{1}{4}\sqrt{\frac{H^2\iota\left(\chi +1 \right) }{\chi+t}}, \alpha_t=\frac{\chi+1}{\chi+t}$ \; Update the reward Q-value: ${Q}_{h-1} (x_{h-1},a_{h-1})\leftarrow (1-\alpha_t)Q_{h-1} (x_{h-1},a_{h-1}) + \alpha_t\left(r_{h-1}(x_{h-1},a_{h-1})+V_{h} (x_{h})+b_t\right)$\; Update the utility Q-value: ${C}_{h-1} (x_{h-1},a_{h-1})\leftarrow (1-\alpha_t)C_{h-1} (x_{h-1},a_{h-1}) + \alpha_t\left(g_{h-1}(x_{h-1},a_{h-1})+W_{h}(x_{h})+b_t\right)$\; } \If{$h=1$}{ $\bar{C} \leftarrow \bar{C}+C_{1}(x_{1},a_{1})$ \tcp*{\small Add $C_1(x_1,a_1)$ to $\bar{C}$} } } \If{$k\mod(K^\alpha)=0$ \tcp*{\small Reset the visit counts, add extra bonuses, and update the virtual-queue at the beginning of each frame}} { $N_{h}(x,a)\leftarrow 0, Q_{h}(x,a)\leftarrow Q_{h}(x,a)+\frac{2H^3\sqrt{\iota}}{\eta}, \forall (x,a,h)$\; \If{$Q_{h}(x,a)\geq H$ or $C_{h}(x,a)\geq H$}{ $Q_{h}(x,a)\leftarrow H$ and $C_{h}(x,a)\leftarrow H;$ } $Z\leftarrow \left(Z +\rho+\epsilon - \frac{\bar{C}}{K^\alpha}\right)^+,$ and $\bar{C}\leftarrow 0$ \tcp*{\small update the virtual-queue length} } } \caption{{Triple-Q}} \end{algorithm} The next theorem summarizes the regret and constraint violation bounds guaranteed under {Triple-Q}. \begin{theorem}\label{thm:main} Assume $K \geq \left(\frac{16\sqrt{SAH^6\iota^3}}{\delta} \right)^5,$ where $\iota=128\log(\sqrt{2SAH}K).$ Triple-Q achieves the following regret and constraint violation bounds: \begin{align*} \text{\em Regret}(K) & \leq \frac{13}{\delta} H^4 {\sqrt{SA\iota^3}}{K^{0.8}} +\frac{4H^4\iota}{ K^{1.2}} \\ \text{\em Violation}(K) &\leq \frac{54H^4{\iota}K^{0.6} }{\delta}\log{\frac{16H^2\sqrt{\iota}}{\delta}} +\frac{4\sqrt{H^2\iota}}{\delta}K^{0.8}- 5\sqrt{SAH^6\iota^3}K^{0.8}. \end{align*} If we further have $K\geq e^{\frac{1}{\delta}},$ then $\text{\em Violation}(K)\leq 0$ and \begin{align*} \Pr\left(\sum^{K}_{k=1}\rho-W_{1}^{\pi_k} (x_{k,1})\leq 0\right)= 1-\tilde{\mathcal{O}}\left(e^{-K^{0.2} + }+\frac{1}{K^2} \right), \end{align*} in other words, Triple-Q guarantees zero constraint violation both on expectation and with a high probability. \end{theorem} \section{Convergence and $\epsilon$-Optimal Policy}\label{sec:near} The Triple-Q algorithm is an online learning algorithm and is not a stationary policy. In theory, we can obtain a near-optimal, stationary policy following the idea proposed in \cite{JinAllZey_18}. Assume the agent stores all the policies used during learning. Note that each policy is defined by the two Q tables and the value of the virtual queue. At the end of learning horizon $K,$ the agent constructs a stochastic policy $\bar{\pi}$ such that at the beginning of each episode, the agent uniformly and randomly selects a policy from the $K$ policies , i.e. $\bar{\pi}=\pi_k$ with probability $\frac{1}{K}.$ We note that given any initial state $x,$ $$\frac{1}{K}\sum_{k=1}^K V_{1}^{\pi_k}(x)= V^{\bar{\pi}}_1(x).$$ $$\frac{1}{K}\sum_{k=1}^K W_{1}^{\pi_k}(x)= W^{\bar{\pi}}_1(x).$$ Therefore, under policy $\bar{\pi},$ we have \begin{align*} & \mathbb{E} \left[V_1^*(x_{k,1}) -V_1^{\bar{\pi}}(x_{k,1}) \right]\\ = & \mathbb{E} \left[ \frac{1}{K}\sum_{k=1}^K \left(V_1^*(x_{k,1}) -V_1^{\bar{\pi}}(x_{k,1}\right) \right] \\ =&\mathbb{E}\left[ \frac{1}{K}\sum_{k=1}^K \left(V_1^*(x_{k,1}) -V_1^{\pi_k}(x_{k,1}\right)\right] \\ = & \tilde{O}\left( \frac{H^4\sqrt{SA}}{\delta K^{0.2}} \right), \end{align*} and \begin{align*} & \mathbb{E} \left[\rho -W_1^{\bar{\pi}}(x_{k,1}) \right]\\ = & \mathbb{E} \left[ \frac{1}{K}\sum_{k=1}^K \left(\rho -W_1^{\bar{\pi}}(x_{k,1}\right) \right] \\ = & \mathbb{E} \left[\frac{1}{K} \sum_{k=1}^K\left(\rho-W_1^{\pi_k}(x_{k,1}) \right)\right]\\ \leq &0. \end{align*} Therefore, given any $\epsilon,$ $\bar{\pi}$ is an $\epsilon$-optimal policy when $K$ is sufficiently large. While $\bar{\pi}$ is a near-optimal policy, in practice, it may not be possible to store all policies during learning due to memory constraint. A heuristic approach to obtain a near optimal, stationary policy is to fix the two Q functions (reward and utility) after learning horizon $K$ and continue to adapt the virtual queue with frame size $\sqrt{K}.$ This is a stochastic policy where the randomness comes from the virtual queue. When the virtual queue reaches its steady state, we obtain a stationary policy. The resulted policy has great performance in our experiment (see Section \ref{sec:simu}). \section{Evaluation} \label{sec:simu} We evaluated Triple-Q using a grid-world environment \cite{ChoNacDue_18}. We further implemented Triple-Q with neural network approximations, called Deep Triple-Q, for an environment with continuous state and action spaces, called the Dynamic Gym benchmark \cite{YanSimTin_21}. In both cases, Triple-Q and Deep Triple-Q quickly learn a safe policy with a high reward. \subsection{A Tabular Case} We first evaluated our algorithm using a grid-world environment studied in \cite{ChoNacDue_18}. The environment is shown in Figure~\ref{fig:envs}-(a). The objective of the agent is to travel to the destination as quickly as possible while avoiding obstacles for safety. Hitting an obstacle incurs a cost of $1$. The reward for the destination is $100$, and for other locations are the Euclidean distance between them and the destination subtracted from the longest distance. The cost constraint is set to be $6$ (we transferred utility to cost as we discussed in the paper), which means the agent is only allowed to hit the obstacles as most six times. To account for the statistical significance, the result of each experiment was averaged over $5$ trials. The result is shown in Figure~\ref{fig:re_grid}, from which we can observe that Triple-Q can quickly learn a well performed policy (with about $20,000$ episodes) while satisfying the safety constraint. Triple-Q-stop is a stationary policy obtained by stopping learning (i.e. fixing the Q tables) at $40,000$ training steps (note the virtual-Queue continues to be updated so the policy is a stochastic policy). We can see that Triple-Q-stop has similar performance as Triple-Q, and show that Triple-Q yields a near-optimal, stationary policy after the learning stops. \begin{figure}[htb] \centering \includegraphics[width=0.5\linewidth]{./figures/environments_2.png} \caption{Grid World and DynamicEnv\protect\footnotemark \ with Safety Constraints} \label{fig:envs} \end{figure} \begin{figure}[htb] \centering \includegraphics[width=0.58\linewidth]{./figures/result_gridworld_stop.png} \caption{The average reward and cost under Triple-Q during training. The shaded region represents the standard deviations} \label{fig:re_grid} \end{figure} \footnotetext{{\bf Image Sorce:} The environment is generated using safety-gym: https://github.com/openai/safety-gym.} \subsection{Triple-Q with Neural Networks} We further evaluated our algorithm on the Dynamic Gym benchmark (DynamicEnv) \cite{YanSimTin_21} as shown in Figure.~\ref{fig:envs}-(b). In this environment, a point agent (one actuator for turning and another for moving) navigates on a 2D map to reach the goal position while trying to avoid reaching hazardous areas. The initial state of the agent, the goal position and hazards are randomly generated in each episode. At each step, the agents get a cost of $1$ if it stays in the hazardous area; and otherwise, there is no cost. The constraint is that the expected cost should not exceed 15. In this environment, both the states and action spaces are continuous, we implemented the key ideas of Triple-Q with neural network approximations and the actor-critic method. In particular, two Q functions are trained simultaneously, the virtual queue is updated slowly every few episodes, and the policy network is trained by optimizing the combined three ``Q''s (Triple-Q). The details can be found in Table \ref{tab:hyper}. We call this algorithm Deep Triple-Q. The simulation results in Figure~\ref{fig:re_dynamic} show that Deep Triple-Q learns a safe-policy with a high reward much faster than WCSAC \cite{YanSimTin_21}. In particular, it took around $0.45$ million training steps under Deep Triple-Q, but it took $4.5$ million training steps under WCSAC. \begin{table}[htb] \centering \caption{Hyperparameters} \begin{tabular}{l|c} Parameter & Value\\ \hline \quad optimizer & Adam \\ \quad learning rate & $3\times 1^{-3}$\\ \quad discount & 0.99 \\ \quad replay buffer size & $10^6$ \\ \quad number of hidden layers (all networks) & 2 \\ \quad batch Size & 256 \\ \quad nonlinearity & ReLU \\ \quad number of hidden units per layer (Critic) & 256 \\ \quad number of hidden units per layer (Actor) & 256 \\ \quad virtual queue update frequency & 3 episode \\ \hline \end{tabular} \label{tab:hyper} \end{table} \begin{figure}[htb] \centering \includegraphics[width=0.58\linewidth]{./figures/result_dynamic.png} \caption{The rewards and costs of Deep Triple-Q versus WCSAC during Training} \label{fig:re_dynamic} \end{figure}
{'timestamp': '2021-10-26T02:08:12', 'yymm': '2106', 'arxiv_id': '2106.01577', 'language': 'en', 'url': 'https://arxiv.org/abs/2106.01577'}
arxiv
\section{Introduction} Image Inpainting is the process of restoring damaged or missing regions of a given image based on the information of the undamaged regions. It has a wide range of real-world applications such as the restoration of damaged images and the removal of unwanted objects. So far, plenty of inpainting approaches have been proposed, among which generative adversarial networks (GANs) \cite{goodfellow2014generative} based deep inpainting techniques \cite{pathak2016context,iizuka2017globally,yu2018generative,li2019generative,Yu_2019_ICCV,Li_2020_CVPR} have been demonstrated to be the most effective ones. One distinguished advantage of deep inpainting models is the ability to adaptively predict semantic structures and produce super realistic and fine-detailed textures. \begin{figure}[t!] \centering \setlength{\tabcolsep}{0.05em} { \begin{tabular}{cccc} \includegraphics[width=2.1cm]{fig1/00.png}& \includegraphics[width=2.1cm]{fig1/01.png}& \includegraphics[width=2.1cm]{fig1/10.png}& \includegraphics[width=2.1cm]{fig1/11.png} \\ \scriptsize (a) Original image & \scriptsize(b) Inpainted image & \scriptsize(c) Inpainting mask & \scriptsize(d) Detected mask \\ \end{tabular} } \caption{(a) The original image; (b) The inpainted image by the deep inpainting method in \protect\cite{Yu_2019_ICCV}; (c) The mask that defines the inpainting region; (d) The detected mask by our approach.} \label{ijcai2021:exampleCompare} \end{figure} However, like a two-edged sword cuts both ways, deep inpainting techniques come along with the risk of being manipulated for image forgery. Due to the super realistic inpainting effects, these techniques can be easily applied to replace the critical objects in an image with fake contents, and the tampered image may appear as photo-realistic as real images. Figure~\ref{ijcai2021:exampleCompare} (b) shows one such example crafted from the real image in Figure~\ref{ijcai2021:exampleCompare} (a) by a recent deep inpainting method \cite{Yu_2019_ICCV}. Inpainted images can potentially be used to create fake news, spread rumors on the internet or even fabricate false evidences. It is thus imperative to develop detection algorithms to identify whether and more importantly \emph{where} an image has been modified by deep inpainting. Specifically, the goal of deep inpainting detection is to locate the exact inpainted regions in an image, as shown in Figure~\ref{ijcai2021:exampleCompare} (d). While Li et al. \shortcite{li2019localization} recently proposed the first method for deep inpainting detection, its effectiveness is restricted to the inpainting technique the detector was trained on and does not generalize well to other inpainting techniques. However, in real-world scenarios, the exact techniques used to inpaint the images are often unknown. In this paper, we aim to address this generalization limitation and introduce a \emph{universal} detector that works well even on unseen deep inpainting techniques. Our approach is motivated by one important yet so far overlooked common characteristic of all deep inpainting methods: the patterns of the noise exists in real and synthesized contents are different. It has been shown that conventional image acquisition devices (e.g. camera sensors) leave distinctive noise patterns on each image~\cite{Farid2009}, however, GAN-generated contents do not have the same type of noise patterns~\cite{8695364}. As shown in Figure \ref{ijcai2021:noise}, given an inpainted image that contains both the device-captured real pixels and GAN-generated inpainted pixels, % there are obvious discrepancies between inpainted region and non-inpainted region in the noise residual (i.e., pixel-wise subtraction between the inpainted image and its denoised version by a denoising filter). Motivated by this observation, we propose a universal deep inpainting detection framework with the following two important designs. First, we present a novel way of generating universal dataset for training universal detectors. The universal training dataset contains: 1) images with synthesized (using a pre-trained autoencoder) contents of arbitrary shapes at random locations, and 2) the corresponding masks. It imitates the noise pattern discrepancies between the real and synthesized contents in a more principled manner, without using any specific deep inpainting methods. Second, we propose a Noise-Image Cross-fusion Network (NIX-Net) to effectively exploit the discriminative information contained in both the images and their noise residuals. After training on the universal dataset, our NIX-Net can reliably recognize the regions inpainted by different deep inpainting methods. \begin{figure}[t!] \centering \setlength{\tabcolsep}{0.2em} { \begin{tabular}{ccc} \includegraphics[width=2.0cm]{fig2/01.png}& \includegraphics[width=2.0cm]{fig2/10.png}& \includegraphics[width=2.0cm]{fig2/11.png} \\ \scriptsize (a) Masked image & \scriptsize (b) Inpainted image & \scriptsize (c) Noise residual \\ \end{tabular} } \caption{Noise analysis on an inpainted image. (a) The image with the inpainting mask (the white region); (b) The inpainted image by the method in \protect\cite{Yu_2019_ICCV}; (c) The pixel-wise difference between (b) and a denoised version of (b), i.e., a noise residual pattern.} \label{ijcai2021:noise} \end{figure} In summary, our main contributions are: \begin{itemize} \item We propose a novel framework for universal deep inpainting detection, which consists of 1) a new method of generating universal training data, and 2) a two-stream multi-scale Noise-Image Cross-fusion detection Network (NIX-Net). \item We empirically show, on multiple benchmark datasets, that our proposed approach can consistently outperform existing detection methods, especially when applied to detect unseen deep inpainting techniques. \item Our universal training dataset can also improve the generalizability of existing detection methods, making it an indispensable part of future detection methods. \end{itemize} \section{Related Work} \subsection{Deep Image Inpainting} Different from conventional image inpainting approaches, deep learning based image inpainting (or deep inpainting for short) trains inpainting networks on large-scale datasets and can generate more visually plausible details or fill large missing regions with new contents that never exist in the input image. By far, the generative adversarial networks (GAN) \cite{goodfellow2014generative} based inpainting methods are arguably the most powerful methods for deep image inpainting. These methods all employ a GAN-based training approach with two sub-networks: an inpainting network and a discriminative network. The former learns image semantics and fills the missing regions with predicted contents, whereas the latter distinguishes whether the image is real or inpainted. Phatak et al. \shortcite{pathak2016context} proposed the Context-Encoder (CE) for single image inpainting, which is known as the first GAN-based image inpainting technique. This technique was later improved by \cite{iizuka2017globally} using dilated convolution and global-local adversarial training. Yu et al. \shortcite{yu2018generative} proposed a two-stage inpainting network with a coarse-to-fine learning strategy. A gated convolution network along with a learnable dynamic feature selection mechanism (for each channel and at each spatial location) was proposed in \cite{Yu_2019_ICCV} for image inpainting. Li et al. \shortcite{Li_2020_CVPR} devised the Recurrent Feature Reasoning network which recurrently enriches information for the hole region. Despite the diversity of existing deep inpainting methods, they all share a common characteristic: the noise patterns in generated contents are different from those in the real image contents. While this characteristic has been observed in understanding the artificial fingerprints of GANs~\cite{8695364}, it has not been exploited for deep inpainting detection. In this paper, we will leverage such a universal characteristic of generated contents to build universal deep inpainting detectors. \subsection{Inpainting Forensics} Deep inpainting detection falls into the general scope of image forensics, but quite different from the conventional image manipulation detection or deepfake detection. Conventional image manipulation detection deals with traditional image forgery operations such as splicing \cite{huh2018fighting} and copy-move \cite{wu2018busternet}. Deepfake (or deep face swapping) is the other type of deep learning forgery techniques that swaps one person's face in a video to that of a different person, which often requires heavy post-processing including color transfer and boundary blending \cite{li2020face}. Different from conventional image manipulation or deepfake, deep inpainting takes one image and a mask as inputs and generates new content for the mask region, based on information of the non-mask regions within the same image. In this paper, we focus on deep image inpainting detection and the generalizability of the detector to unseen deep inpainting techniques (not to conventional image manipulation or deepfake). Most of existing inpainting forensic methods are developed to detect traditional image inpainting techniques. For example, the detection of traditional diffusion-based inpainting based on local variance of image Laplacian \cite{li2017localization}, and the detection of traditional patch-based inpainting via patch similarities computed by zero-connectivity length \cite{wu2008detection}, two-stage suspicious region search \cite{chang2013forgery} or CNN-based encoder-decoder detection networks \cite{Zhu2018ADL}. These methods are generally less effective on deep inpainting techniques that can synthesize extremely photo-realistic contents or new objects that never exist in the original image. Deep inpainting detection is a fairly new research topic. The high-pass fully convolutional network by \cite{li2019localization} is the only known detection method for deep inpainting detection. However, training this detection network requires knowing the deep inpainting technique to be detected. This tends to limit its generalizability to unseen deep inpainting methods, as shown in our experiments. In this paper, we focus on developing universal deep inpainting detectors, which we believe is a crucial step towards more powerful and practical deep inpainting detectors. \begin{figure}[t!] \centering \includegraphics[width=8.5cm]{fig4/combine.png} \caption{The procedure of universal training dataset generation.} \label{ijcai2021:combine} \end{figure} \begin{figure}[t!] \centering \includegraphics[width=6cm]{fig3/equalGAN.png} \caption{The procedure of training the autoencoder $G$.} \label{ijcai2021:EqualGAN} \end{figure} \section{Problem Formulation and Universal Training Dataset Generation} \begin{figure*}[ht] \centering \includegraphics[width=0.88\linewidth]{fig5/framework.png} \caption{Overview of the proposed Noise-Image Cross-Fusion Network (best viewed in color). Here ``upsample $1 \times 1$" and ``stride-2 $3 \times 3$" refer to bilinear upsampling followed by a $1 \times 1$ convolution, and $3 \times 3$ convolution with stride 2, respectively.} \label{ijcai2021:detection} \end{figure*} \subsection{Problem Formulation} Given an image $X_{i}$ inpainted by a certain deep inpainting method on regions defined by a binary mask $M_{i}$, deep inpainting detection aims to locate the inpainted regions $M_{i}$. A detection network can be trained to take the inpainted image $X_{i}$ as input and output the predicted mask $\hat{M}_{i}$. To train the detector, a straightforward approach is to use inpainted images generated by a deep inpainting method as the training data \cite{li2019localization}. However, this \emph{inpainting-method-aware} approach often generalizes poorly when applied to detect inpainted images generated by unseen deep inpainting methods. An empirically analysis can be found in Section~\ref{ijcai2021:sectionQuan}. In contrast, we propose to generate a universal training dataset to capture the common characteristics shared by different deep inpainting methods, and train the detection model on this universal dataset. Such an \emph{inpainting-method-agnostic} approach can improve the generalization of the detection model to unseen deep inpainting methods. Next, we will introduce our proposed universal training dataset generation method inspired by the distinctive noise patterns exist in real versus generated contents. \subsection{Universal Training Dataset Generation} \label{universal} A universal training dataset should consider the common characteristics of different deep inpainting methods, rather than relying on the specific artifacts of one particular deep inpainting method. Motivated by our observation in Figure \ref{ijcai2021:noise}, here we propose to create the universal training dataset by simulating ``inpainted" images from autoencoder reconstructions, instead of using any existing deep inpainting methods. The complete generation procedure is illustrated in Figure~\ref{ijcai2021:combine}. For a set of real images $I \coloneqq \{I_{1},I_{2},...,I_{n}\}$, the generation process generates a set of simulated (as it does not use any real inpainting methods) inpainted images $X \coloneqq \{X_{1},X_{2},...,X_{n}\}$ using a pre-trained autoencoder with a set of random binary masks $M \coloneqq \{M_{1},M_{2},...,M_{n}\}$. Specifically, given a real image $I_{i}$, we first obtain its reconstructed version $G(I_{i})$ from an autoencoder $G$. We train the autoencoder following a typical GAN~\cite{goodfellow2014generative} approach using the autoencoder as the GAN generator and an additional classification network as the GAN discriminator. The overall structure is illustrated in Figure \ref{ijcai2021:EqualGAN}. The autoencoder is trained to have small reconstruction error, and at the same time, the reconstructed images should be as realistic as the real images according to the discriminator. The overall training loss of this autoencoder is: \begin{equation} \mathcal{L} = \sum_{i=1}^{n}\underbrace{\log (D(I_{i}) + \log (1-D(G(I_{i})))}_\text{$\mathcal{L}_{\text{adv}}$} + \lambda \underbrace{\Vert G(I_{i}) - I_{i} \Vert_{2}}_\text{$\mathcal{L}_{\text{rec}}$} \end{equation} where, $\mathcal{L}_{\text{adv}}$ and $\mathcal{L}_{\text{rec}}$ are the adversarial and reconstruction loss respectively, and $\lambda=0.1$ is a trade-off parameter. After training, the autoencoder $G$ is applied to reconstruct each real image in $I$. With the reconstructed images, our next step is to simulate the inpainting process. Specifically, we simulate an ``inpainted'' image $X_{i}$ by combining $I_{i}$ and its reconstruction $G(I_{i})$ according to a random mask $M_i$: \begin{equation} X_{i} = M_{i} \odot I_{i} + (1-M_{i}) \odot G(I_{i}), \end{equation} where $\odot$ is the element-wise multiplication and $M_{i}$ is a binary mask with 0 elements indicating the inpainting region (white region) and 1 elements indicating the non-inpainting region (black region). In $X_{i}$, the ``inpainted" region carries over the noise patterns of the synthesized contents from the autoencoder, while the rest of the regions preserve the noise patterns from the real contents. Following this procedure, we can obtain a set of images with synthesized regions to create the universal training dataset: $UT = \{X, M\}$, with $X$ being the simulated inpainted images and $M$ being the inpainting masks. Our universal dataset $UT$ distinguishes itself from existing inpainting-method-aware datasets as a general formulation of real versus generated contents. However, having this dataset is not enough to train accurate deep inpainting detectors. It requires an effective learning framework to exploit the discriminative information contained in the dataset, especially the noise patterns. Next we will introduce our proposed detection network that serves this purpose. \section{Noise-Image Cross-fusion Network (NIX-Net)} As shown in Figure~\ref{ijcai2021:noise} (c), the noise residual patterns between inpainted and non-inpainted regions in an inpainted image are distinct. Unlike previous works that ignore this important cue for mask detection, we propose NIX-Net which leverages both the inpainted image $X_{i}$ and its noise residual $R_i$ to enhance detection performance. As shown in Figure~\ref{ijcai2021:detection}, the proposed NIX-Net consists of three components: 1) feature extraction, 2) multi-scale cross fusion, and 3) mask detection. \paragraph{Feature extraction.} Given an inpainted image $X_i$, we define its noise residual as following: \begin{equation} R_{i} = X_{i} - d(X_{i}), \end{equation} Inspired by recent studies on image forensics using SRM features \cite{zhou2018learning}, we choose the SRM filter as our denoising filter $d(\cdot)$. The feature extraction component includes two parallel feature extraction streams to learn multi-scale feature maps of the input image and its noise residual, respectively. Each feature extraction module consists of three ResNet blocks \cite{he2016identity}, resulting in three feature maps of $X_{i}$, namely, $\phi_{I_{1}}(X_{i})$, $\phi_{I_{2}}(X_{i})$ and $\phi_{I_{3}}(X_{i})$. The numbers of channels in the feature maps are 128, 256 and 512, respectively. Likewise, the three feature maps of $R_{i}$ are $\phi_{N_{1}}(R_{i})$, $\phi_{N_{2}}(R_{i})$ and $\phi_{N_{3}}(R_{i})$. Since the last convolution layer of each ResNet block has a stride of 2 to reduce the spatial scale \cite{he2016deep}, the spatial scales of the feature maps are $1/2, 1/4$ and $1/8$ of the input spatial size. \paragraph{Multi-scale cross fusion.} The multi-scale cross fusion component aims to effectively incorporate noise features and image features in a multi-scale manner. Specifically, both the noise stream and the image stream are followed by a fusion module. The fusion module takes the three-scale feature maps as input, and outputs the crossly fused three-scale feature maps. Each fused feature map is the sum of the three transformed (upsampled, downsampled or unchanged) input feature maps. The outputs of fusion module 1 in the image stream are $\phi_{I_{1}}^{F}(X_{i})$, $\phi_{I_{2}}^{F}(X_{i})$ and $\phi_{I_{3}}^{F}(X_{i})$, while the outputs of fusion module 2 in the noise stream are $\phi_{N_{1}}^{F}(R_{i})$, $\phi_{N_{2}}^{F}(R_{i})$ and $\phi_{N_{3}}^{F}(R_{i})$. The purpose of this fusion module is to exchange the information across multi-scale feature representations, and produce richer feature representations with strengthened position sensitivity ~\cite{Sun_2019_CVPR}. For each scale, we concatenate the feature maps of the image stream and the noise stream along the channel dimension, followed by a Conv block. The outputs are denoted as $\psi_{1}(X_{i},R_{i})$, $\psi_{2}(X_{i},R_{i})$ and $\psi_{3}(X_{i},R_{i})$. The Conv block consists of two $3 \times 3$ convolutions, each of which is followed by a batch normalization and a ReLU Layer. Finally, fusion module 3 further consolidates the connection between the image and noise features over different scales, and output three fused feature maps $\psi_{1}^{F}(X_{i},R_{i})$, $\psi_{2}^{F}(X_{i},R_{i})$ and $\psi_{3}^{F}(X_{i},R_{i})$. \paragraph{Mask detection.} The mask detection module first upsamples the two lower-resolution feature maps $\psi_{2}^{F}(X_{i},R_{i})$ and $\psi_{3}^{F}(X_{i},R_{i})$ using bilinear upsampling so that they have the same resolution as $\psi_{1}^{F}(X_{i},R_{i})$. The three feature maps are then concatenated along the channel dimension, followed by a Conv block and an upsampling layer which outputs a $w \times h \times 1$ feature map. The feature map is then fed into a Sigmoid layer for classification, rendering the possibility map $P_{i}$ with pixel-wise predictions. Finally, the detected mask $\hat{M}_{i}$ can be obtained by binarizing $P_{i}$ according to a threshold value. In this paper, we set the threshold value as 0.5. \paragraph{Network training.} We train the entire network end-to-end using the focal loss \cite{lin2017focal} on the universal training dataset $UT$. Note that the network can also be trained on any other inpainting detection datasets including the inpainting-method-aware datasets. The use of the focal loss is to mitigate the effect of class imbalance (the inpainted regions are often small compared to the entire image). The focal loss $\mathcal{L}_{f}$ is defined as following: \begin{equation} \resizebox{.9\hsize}{!}{$ \mathcal{L}_{f} = \sum_{i}^{n}(-M_{i} (1-\hat{M}_{i})^{\gamma }\log \hat{M}_{i} - (1-M_{i})\hat{M}_{i}^{\gamma }\log (1- \hat{M}_{i})) $ } \end{equation} where $\gamma$ is the focusing parameter and is set to 2. \section{Experiments} In this section, we first introduce the experimental settings, then evaluate the performance of our proposed approach via extensive experiments and ablation studies. \paragraph{Inpainting methods and datasets.} We use three different deep inpainting techniques including \textbf{GL} \cite{iizuka2017globally}, \textbf{CA} \cite{yu2018generative} and \textbf{GC} \cite{Yu_2019_ICCV} to generate inpainted images on two datasets Places2~\cite{zhou2017places} and CelebA~\cite{liu2015deep}. For each of the two datasets, we randomly select (without replacement) 50K, 10K and 10K images to create the training, validation and testing subsets respectively, following either our universal data generation or using one of the above three inpainting techniques (GL, CA and GC). We train the detection models on the training subset and test their performance on the test subset. \paragraph{Mask generation.} To simulate more diverse and complex real-world scenarios, we utilize the irregular mask setting in \cite{Yu_2019_ICCV} with arbitrary shapes and random locations for both training and testing. Besides, object-shape masks are also adopted for visual comparison, as shown in Figure~\ref{ijcai2021:QualitativeCompare1}. \paragraph{Baseline models.} We consider two baseline models: 1) \textbf{LDICN} \cite{li2019localization}, a fully convolutional network designed for deep inpainting detection; and 2) \textbf{ManTra-Net} \cite{Wu_2019_CVPR}, a state-of-the-art detection model for traditional image forgery such as splicing. \paragraph{Performance metric.} We use the Intersection over Union (IoU) as the performance metric, and report the mean IoU (mIoU) over the entire test subset of inpainted images. \paragraph{Training setting.} We train the networks using the Adam optimizer with initial learning rate $1\times10^{-4}$. An early stopping strategy is also adopted based on the mIoU on the validation dataset: the model with the highest validation mIoU is saved as the final model. All of our experiments were run with a Nvidia Tesla V100 GPU. \begin{table}[!htb] \large \renewcommand\arraystretch{1.05} \begin{center} \scalebox{0.71} { \begin{tabular}{l|cc|ccc|ccc} \toprule \multirow{3}{*}{\textbf{Model}} & \multicolumn{2}{c|}{\textbf{Training}} & \multicolumn{6}{c}{\textbf{Test mIoU}} \\ \cline{4-9} & \multicolumn{2}{c|}{\textbf{Data}} & \multicolumn{3}{c|}{Places2} & \multicolumn{3}{c}{CelebA} \\ \cline{2-9} & GL & UT & GL & CA & GC & GL & CA & GC \\ \hline LDICN & \checkmark & & 83.47 & 66.70 & 56.24 & 87.27 & 67.61 & 64.16\\ ManTra-Net & \checkmark & & 88.76 & 70.18 & 64.60 & 92.53 & 76.22 & 70.98 \\ \textbf{NIX-Net} & \checkmark & & \textbf{91.82} & \textbf{80.55} & \textbf{77.63} & \textbf{93.37} & \textbf{84.48} & \textbf{81.24} \\ \hline \textbf{NIX-Net} & \checkmark & \checkmark & \textbf{92.14} & \textbf{86.09} & \textbf{81.98} & \textbf{93.71} & \textbf{89.63} & \textbf{87.95} \\ \hline \hline & CA & UT & GL & CA & GC & GL & CA & GC\\ \hline LDICN & \checkmark & & 69.53 & 82.48 & 57.73 & 75.85 & 87.04 & 68.49 \\ ManTra-Net & \checkmark & & 76.22 & 86.08 & 69.61 & 81.21 & 89.40 & 77.39 \\ \textbf{NIX-Net} & \checkmark & & \textbf{83.57} & \textbf{88.75} & \textbf{76.49} & \textbf{87.93} & \textbf{92.30} & \textbf{83.77} \\ \hline \textbf{NIX-Net} & \checkmark & \checkmark & \textbf{90.50} & \textbf{89.16} & \textbf{83.80} & \textbf{92.49} & \textbf{92.74} & \textbf{88.36} \\ \hline \hline & GC & UT & GL & CA & GC & GL & CA & GC\\ \hline LDICN & \checkmark & & 70.55 & 68.16 & 84.24 & 77.62 & 73.81 & 87.29 \\ ManTra-Net & \checkmark & & 80.85 & 74.69 & 84.90 & 83.31 & 81.25 & 88.46 \\ \textbf{NIX-Net} & \checkmark & & \textbf{84.77} & \textbf{81.03} & \textbf{85.38} & \textbf{90.57} & \textbf{86.44} & \textbf{88.97} \\ \hline \textbf{NIX-Net} & \checkmark & \checkmark & \textbf{91.48} & \textbf{87.25} & \textbf{85.61} & \textbf{93.11} & \textbf{91.82} & \textbf{90.34} \\ \hline \hline & & UT & GL & CA & GC & GL & CA & GC\\ \hline LDICN & & \checkmark & 82.95 & 80.79 & 78.29 & 85.52 & 82.98 & 81.43 \\ ManTra-Net & & \checkmark & 88.42 & 83.15 & 80.52 & 89.71 & 86.64 & 85.38 \\ \textbf{NIX-Net} & & \checkmark & \textbf{91.33} & \textbf{88.46} & \textbf{84.71} & \textbf{93.06} & \textbf{91.59} & \textbf{88.20} \\ \bottomrule \end{tabular} } \end{center} \caption{Quantitative Comparison on Places2 and CelebA datasets.} \label{ijcai2021:tab0} \end{table} \begin{figure*}[t!] \centering \setlength{\tabcolsep}{0.05em} { \begin{tabular}{cccccc @{\hspace{0.15cm}} cccccc} \includegraphics[width=1.44cm]{fig6/places/60.jpg}& \includegraphics[width=1.44cm]{fig6/places/61.png}& \includegraphics[width=1.44cm]{fig6/places/62.png}& \includegraphics[width=1.44cm]{fig6/places/63.png}& \includegraphics[width=1.44cm]{fig6/places/64.png}& \includegraphics[width=1.44cm]{fig6/places/65.png}& \includegraphics[width=1.44cm]{fig6/celeba/00.png}& \includegraphics[width=1.44cm]{fig6/celeba/01.png}& \includegraphics[width=1.44cm]{fig6/celeba/02.png}& \includegraphics[width=1.44cm]{fig6/celeba/03.png}& \includegraphics[width=1.44cm]{fig6/celeba/04.png}& \includegraphics[width=1.44cm]{fig6/celeba/05.png} \\ \addlinespace[-0.23em] \includegraphics[width=1.44cm]{fig6/places/40.jpg}& \includegraphics[width=1.44cm]{fig6/places/41.png}& \includegraphics[width=1.44cm]{fig6/places/42.png}& \includegraphics[width=1.44cm]{fig6/places/43.png}& \includegraphics[width=1.44cm]{fig6/places/44.png}& \includegraphics[width=1.44cm]{fig6/places/45.png}& \includegraphics[width=1.44cm]{fig6/celeba/20.png}& \includegraphics[width=1.44cm]{fig6/celeba/21.png}& \includegraphics[width=1.44cm]{fig6/celeba/22.png}& \includegraphics[width=1.44cm]{fig6/celeba/23.png}& \includegraphics[width=1.44cm]{fig6/celeba/24.png}& \includegraphics[width=1.44cm]{fig6/celeba/25.png} \\ \addlinespace[-0.24em] \includegraphics[width=1.44cm]{fig6/places/10.jpg}& \includegraphics[width=1.44cm]{fig6/places/11.jpg}& \includegraphics[width=1.44cm]{fig6/places/12.png}& \includegraphics[width=1.44cm]{fig6/places/13.png}& \includegraphics[width=1.44cm]{fig6/places/14.png}& \includegraphics[width=1.44cm]{fig6/places/15.png}& \includegraphics[width=1.44cm]{fig6/celeba/10.png}& \includegraphics[width=1.44cm]{fig6/celeba/11.png}& \includegraphics[width=1.44cm]{fig6/celeba/12.png}& \includegraphics[width=1.44cm]{fig6/celeba/13.png}& \includegraphics[width=1.44cm]{fig6/celeba/14.png}& \includegraphics[width=1.44cm]{fig6/celeba/15.png} \\ \addlinespace[-0.24em] \includegraphics[width=1.44cm]{fig6/places/50.jpg}& \includegraphics[width=1.44cm]{fig6/places/51.png}& \includegraphics[width=1.44cm]{fig6/places/52.png}& \includegraphics[width=1.44cm]{fig6/places/53.png}& \includegraphics[width=1.44cm]{fig6/places/54.png}& \includegraphics[width=1.44cm]{fig6/places/55.png}& \includegraphics[width=1.44cm]{fig6/celeba/40.png}& \includegraphics[width=1.44cm]{fig6/celeba/41.png}& \includegraphics[width=1.44cm]{fig6/celeba/42.png}& \includegraphics[width=1.44cm]{fig6/celeba/43.png}& \includegraphics[width=1.44cm]{fig6/celeba/44.png}& \includegraphics[width=1.44cm]{fig6/celeba/45.png} \\ \addlinespace[-0.23em] \includegraphics[width=1.44cm]{fig6/places/20.jpg}& \includegraphics[width=1.44cm]{fig6/places/21.jpg}& \includegraphics[width=1.44cm]{fig6/places/22.png}& \includegraphics[width=1.44cm]{fig6/places/23.png}& \includegraphics[width=1.44cm]{fig6/places/24.png}& \includegraphics[width=1.44cm]{fig6/places/25.png}& \includegraphics[width=1.44cm]{fig6/celeba/30.png}& \includegraphics[width=1.44cm]{fig6/celeba/31.png}& \includegraphics[width=1.44cm]{fig6/celeba/32.png}& \includegraphics[width=1.44cm]{fig6/celeba/33.png}& \includegraphics[width=1.44cm]{fig6/celeba/34.png}& \includegraphics[width=1.44cm]{fig6/celeba/35.png} \\ \scriptsize Original & \scriptsize Inpainted &\scriptsize Mask GT &\scriptsize LDICN &\scriptsize ManTra-Net &\scriptsize Ours & \scriptsize Original & \scriptsize Inpainted &\scriptsize Mask GT &\scriptsize LDICN &\scriptsize ManTra-Net &\scriptsize Ours\\ \end{tabular} } \caption{Qualitative comparisons on Places2 and CelebA. The original images are inpainted by CA. Mask GT refers to the ground truth of inpainting mask. LDICN and ManTra-Net are only trained on data generated by GL. Our model is only trained with UT data.} \label{ijcai2021:QualitativeCompare1} \end{figure*} \subsection{Quantitative Performance Evaluation} \label{ijcai2021:sectionQuan} We have 3 detection networks (LDICN, ManTra-Net and our NIX-Net) and 2 types of training data including 1) 3 \emph{inpainting-method-aware} training datasets created using 3 inpainting methods (GL, CA and GC), and 2) our \emph{universal} (UT) training dataset. Here, we first train the detection networks on GL/CA/GC then test the performance on the test sets of all three datasets. Besides, we run our NIX-Net on a hybrid dataset that combines UT with one out of the 3 \emph{inpainting-method-aware} datasets. We also train the detection networks on UT only to test the importance of universal training data to generalizability. Note that all these experiments are run separately for Places2 and CelebA. The performance of the 3 detection networks are summarized in Table~\ref{ijcai2021:tab0}. \paragraph{Overall performance.} As shown in Table~\ref{ijcai2021:tab0}, our NIX-Net outperforms existing methods by a large margin in all test scenarios, especially when transferred to detect unseen inpainting methods. When trained on the hybrid datasets, our NIX-Net achieved the best overall performance. Next, we will provide a detailed analysis of these results from two perspectives: 1) the effectiveness of different detection networks, and 2) the importance of universal training data. \paragraph{Effectiveness of different detection networks.} For LDICN and ManTra-Net, although decent results can be obtained on the known (used for generating training data) inpainting method, their performance drops drastically on unseen inpainting methods. Such a poor generalizability indicates that both models overfit to the artifacts of a particular inpainting method and fail to consider the common characteristics of different deep inpainting techniques. By contrast, our NIX-Net demonstrates consistently better generalizability, regardless of the inpainting method used for training. This is largely due to the sufficient (multi-scale and cross fusion) exploitation of the noise information contained in real versus inpainted contents. This also indicates that noise patterns are indeed a reliable cue of detecting inpainted regions. \paragraph{Importance of universal training data.} Revisit Table~\ref{ijcai2021:tab0}, we find that, whenever the UT dataset is used in conjunction with one inpainting-method-aware dataset, the generalization performance of our NIX-Net can be significantly improved. Moreover, the UT dataset alone can lead to much better generalizability of existing methods LDICN and ManTra-Net. This result verifies, from the data perspective, the importance of noise modeling for universal deep inpainting detection. More importantly, such noise modeling like our proposed universal training dataset generation is much easier than generating training data using different deep inpainting techniques, making it more practical for real-world applications. Another important observation is that NIX-Net trained on UT alone can achieve a similar level of performance as it was trained on the hybrid datasets, though combining more training data does improve the performance. \subsection{Qualitative Performance Evaluation} Here, we provide a qualitative comparison by visualizing the detected masks. Figure~\ref{ijcai2021:QualitativeCompare1} illustrates some of the examples on Places2 and CelebA for LDICN/ManTra-Net trained only on data generated by GL and our NIX-Net trained only on UT data. The ten tested images are all inpainted by CA. By comparing the ground truth mask (Mask GT) and the masks predicted by different detection networks, one can find that our NIX-Net can produce the most similar masks to the ground truth. LDICN and ManTra-Net, however, cannot accurately identify the inpainted regions, especially when they are complex (the three bottom rows). These visual inspections confirm the superiority of our proposed universal training data generation approach and the NIX-Net detection network. \subsection{Ablation Study} Here, we run a set of ablation studies to provide a complete understanding of the two key components of our NIX-Net network: two-steam (noise+image) feature learning and multi-scale cross fusion. Table~\ref{ijcai2021:tab2} compares the full NIX-Net detection network with its five variants created by removing or keeping the noise/image stream or the three fusion modules. All these networks are trained on the UT dataset generated from Places2 and tested on test images from Places2 by GL, CA and GC. It shows that, after removing either the noise or the image stream, the performance degrades drastically. This implies that both the image and the noise pattern are crucial for extracting rich features for detection. The worst performance is observed when all 3 fusion modules removed, even though it still has the noise and the image streams. When adding either fusion module 1 and 2 or fusion module 3 back into the network, the performance is clearly improved. These results indicate that the proposed fusion module is essential for exchanging the information across multi-scale representations and achieving semantically richer feature fusion. \begin{table}[thb] \renewcommand\arraystretch{1.05} \begin{center} \scalebox{0.85} { \begin{tabular}{l|ccc} \toprule \multirow{2}{*}{\textbf{Ablation of NIX-Net}} & \multicolumn{3}{c}{\textbf{Test mIoU}} \\ \cline{2-4} & GL & CA & GC \\ \midrule w/o noise stream & 88.24 & 84.11 & 79.87 \\ w/o image stream & 83.67 & 77.59 & 74.14 \\ \hline w/o all fusion modules & 79.36 & 76.22 & 67.84 \\ w/o fusion module 1 and 2 & 84.72 & 82.35 & 77.93 \\ w/o fusion module 3 & 89.19 & 85.35 & 81.44 \\ \hline Full NIX-Net & \textbf{91.33} & \textbf{88.46} & \textbf{84.71} \\ \bottomrule \end{tabular} } \end{center} \caption{Ablation of NIX-Net for (a) the noise/image stream or (2) the 3 multi-scale cross fusion modules. Networks are trained on the UT dataset generated for Places2 and tested on GL/CA/GC test sets.} \label{ijcai2021:tab2} \end{table} \vspace{-0.1in} \section{Conclusion} In this work, we have proposed an effective approach for universal deep inpainting detection. Our approach consists of two important designs: 1) a novel universal training dataset generation method and 2) a Noise-Image Cross-fusion (NIX-Net) detection network. Extensive experiments on two benchmark datasets verify the effectiveness of our proposed approach and its superior generalization ability when applied to detect unseen deep inpainting methods. Our work not only provides a powerful universal detection method but also opens up a new direction for building more advanced universal deep inpainting detectors. \bibliographystyle{named}
{'timestamp': '2021-06-04T02:07:57', 'yymm': '2106', 'arxiv_id': '2106.01532', 'language': 'en', 'url': 'https://arxiv.org/abs/2106.01532'}
arxiv
\section{Introduction} Due to the rapid improvement of generative adversarial networks (GANs), GAN-based image editing has recently become a widely used tool in desktop applications for professional and social media photo editing tools for casual users. Of particular interest are tools to edit photographs of human faces. In this paper, we propose new tools for image editing by mixing elements from multiple example images in order to make a composite image. Our focus is on the task of hair editing. Despite the recent success of face editing based on latent space manipulation~\cite{abdal2019image2stylegan, abdal2020image2stylegan++, zhu2020improved}, most editing tasks operate on an image by changing global attributes such as \textit{pose}, \textit{expression}, \textit{gender}, or \textit{age}. Another approach to image editing is to select features from reference images and mix them together to form a single, composite image. Examples of composite image editing that have seen recent progress are problems of hair-transfer and face-swapping. These tasks are extremely difficult for a variety of reasons. Chief among them is the fact that the visual properties of different parts of an image are not independent of each-other. The {\color{darkblue} visual qualities} of hair, for example, are heavily influenced by ambient and reflected light as well as transmitted colors from the underlying face, clothing, and background. The pose of a head influences the {\color{dartmouthgreen} appearance of the } nose, eyes and mouth, and the geometry of a person's head and shoulders influences shadows and the geometry of their hair. Other challenges include disocclusion of the background {\color{darkblue} (see the evaluation section Fig. 8 rows~1, 8 and Fig.~\ref{fig:qualitative-ablation-study})}, which happens when the hair region shrinks with respect to the background. Disocclusion of the face region can expose new parts of the face, such as ears, forehead, or the jawline {\color{darkblue} (e.g. results are shown in Fig. 8 row 4 which exposes an ear)}. The shape of the hair is influenced by pose and also by the camera intrinsic parameters, and so the pose might have to change to adapt to the hair. Failure to account for the global consistency of an image will lead to noticeable artifacts - the different regions of the image will appear disjointed, even if each part is synthesized with a high level of realism. In order for the composite image to seem plausible, our aim is to make a single coherent composite image that balances the fidelity of each region to the corresponding reference image while also synthesizing an overall convincing and highly realistic image. {\color{darkblue} A key insight we present is that mixing images that are each of high quality, but also where each pixel has the same semantic meaning, produces new images with fewer undesirable artifacts. One particular benefit of semantic alignment is that regions of the image which are disoccluded are filled with semantically correct image contents. Therefore, we introduce a GAN-based semantic alignment step which generates high quality images similar to the input images, but which have a common semantic segmentation. When the semantic regions relevant to the task (e.g. hair) are aligned, artifacts caused by transparency, reflection, or interaction of the hair with the face, are less noticeable. This is illustrated in Fig.~\ref{fig:qualitative-ablation-study} which shows the artifacts that can occur when blending semantically dissimilar pixels. The value of alignment can also be seen in Fig.~\ref{fig:method-overview}(d,g) in which the hair region of the identity image \ref{fig:method-overview}(b) is aligned to the mask, and blending between two semantically similar regions (e.g. the hair) is more likely to produce a plausible result than attempting to blend between semantically dissimilar regions. } Previous methods of hair transfer based on GANs either use a complex pipeline of conditional GAN generators in which each condition module is specialized to represent, process, and convert reference inputs with different visual attributes~\cite{Tan_2020}, or make use of the latent space optimization with carefully designed loss and gradient orthogonalization to explicitly disentangle hair attributes~\cite{saha2021loho}. While both of these methods show very promising initial results, we found that they could be greatly improved. For example, both of them need pretrained inpainting networks to fill holes left over by misaligned hair masks, which may lead to blurry artifacts and unnatural boundaries. We believe that better results can be achieved without an auxiliary inpainting network to fill the holes, as transitions between regions have higher quality if they are synthesized by a single GAN. The previous methods do not make use of a semantic alignment step to merge semantic regions from different reference images in latent space, e.g. to align a hair region and a face region from different images. {\color{darkblue} The concepts of \textit{identity}, \textit{shape}, \textit{structure}, and \textit{appearance} were introduced in Michigan~\cite{Tan_2020} and then used by others including LOHO~\cite{saha2021loho} in order to describe different aspects of hair. The terms lack a precise definition, however \textit{appearance} broadly refers to the fine details (such as hair color) whereas \textit{structure} refers to coarser features (such as the form of locks of hair). The \textit{shape} of the hair is the binary segmentation region, and the \textit{identity} of a head-image encompasses all the features one would need to identify an individual. In this work, we propose Barbershop, a novel optimization method for photo-realistic hairstyle transfer, face swapping, and other composite image editing tasks applied to faces. Our approach, as illustrated in Fig.~\ref{fig:teaser}, is capable of mixing together these four components in order to accomplish a variety of hair transfer tasks.} Our approach uses GAN-inversion to generate high-fidelity reconstructions of reference images. We suggest a novel $FS$ latent space which provides coarse control of the spatial locations of features via a \textit{structure tensor} $\ensuremath{\mathbf{F}}\xspace$, as well as fine control of global style attributes via an \textit{appearance code} $S$. {\color{darkblue}\xspace The elements of the novel space are illustrated in Fig.~\ref{fig:latent_space}}. This latent space allows a trade-off between a latent-code's capacity to maintain the spatial locations of features such as wrinkles and moles while also supporting latent code manipulation. We edit the codes to align reference images to target feature locations. This {\color{darkblue}\xspace semantic} alignment step is a key extension to existing GAN-embedding algorithms. It embeds images while at the same time slightly altering them to conform to a different segmentation mask. Then we find a blended latent code, by mixing reference images in a {\color{darkblue}\xspace new spatially-aware} latent-space, rather than compositing images in the spatial domain. The result is a latent code of an image. By blending in the new latent space, we avoid many of the artifacts of other image compositing approaches. Our proposed approach is demonstrated in Fig.~\ref{fig:teaser}. We are able to transfer only the \textit{shape} of {\color{darkblue}\xspace a region corresponding to} the subject's hair (Fig.~\ref{fig:teaser}b). We influence the shape by altering the hair region in a segmentation mask. We can also transfer the structure (Fig.~\ref{fig:teaser}c) using the structure tensor, and the appearance (Fig.~\ref{fig:teaser}(d,~f)) by mixing appearance codes. Our approach also supports the use of different reference images to be used for structure vs the appearance code as shown in Fig.~\ref{fig:teaser}(g,~h). Our main contributions are: \begin{itemize} \item A novel latent space, called $FS$ space, for representing images. The new space is better at preserving details, and is more capable of encoding spatial information. \item A new GAN-embedding algorithm for aligned embedding. Similar to previous work, the algorithm can embed an image to be similar to an input image. In addition, the image is slightly modified to conform to a new segmentation mask. \item A novel image compositing algorithm that can blend multiple images encoded in our new latent space to yield a high quality results. \item We achieve a significant improvement in hair transfer, with our approach being preferred over existing state-of-the-art approaches by over 95\% of participants in a user study. \end{itemize} \section{Related Work} \paragraph{GAN-based Image Generation.} Since their advent, GANs~\cite{goodfellow2014generative, radford2015unsupervised} have contributed to a surge in high quality image generation research. Several state-of-the-art GAN networks demonstrate significant improvements in the visual quality and diversity of the samples. Some recent GANs such as ProGAN~\cite{karras2017progressive}, StyleGAN\xspace~\cite{STYLEGAN2018}, and StyleGAN2\xspace~\cite{Karras2019stylegan2} show the ability of GANs to produce very highly detailed and high fidelity images that are almost indistinguishable from real images. Especially in the domain of human faces, these GAN architectures are able to produce unmatched quality and can then be applied to a downstream task such as image manipulation~\cite{shen2020interfacegan, abdal2019image2stylegan}. StyleGAN-ada~\cite{Karras2020ada} showed that a GAN can be trained on limited data without compromising the generative ability of a GAN. High quality image generation is also attributed to the availability of high quality datasets like FFHQ~\cite{STYLEGAN2018}, AFHQ~\cite{choi2020starganv2} and LSUN objects~\cite{yu15lsun}. Such datasets provide both sufficient quality and diversity to train GANs and have further contributed to produce realistic applications. On the other hand, BigGAN~\cite{brock2018large} can produce high quality samples using complex datasets like ImageNet~\cite{imagenet_cvpr09}. Some other notable methods for generative modeling include Variational Autoencoders~(VAEs)~\cite{VAE2013}, PixelCNNs~\cite{Salimans2017PixeCNN}, Normalizing Flows~\cite{chen2018neural} and Transformer based VAEs~\cite{esser2020taming} also have some unique advantages. However, in this work, we focus on StyleGAN2\xspace trained on the FFHQ dataset because it is considered state of the art for face image generation. \paragraph{Embedding Images into the GAN Latent Space} In order to edit real images, a given image needs to be projected into the GAN latent space. There are broadly two different ways to project/embed images into the latent space of a GAN. The first one is the optimization based approach. Particularly for StyleGAN\xspace, I2S~\cite{abdal2019image2stylegan} demonstrated high quality embeddings into the extended $W$ space, called $W+$ space, for real image editing. Several followup works~\cite{zhu2020domain,tewari2020pie} show that the embeddings can be improved by including new regularizers for the optimization. An Improved version of Image2StyleGAN (II2S)~\cite{zhu2020improved} demonstrated that regularization in $P-norm$ space can lead to better embeddings and editing quality. It is also noted that the research in these optimization based approaches with StyleGAN lead to commercial software such as Adobe Photoshop’s Neural Filters~\cite{Adobe}. The second approach in this domain is to use encoder based methods that train an encoder on the latent space. Some notable works~\cite{tov2021designing, richardson2020encoding} produce high quality image embeddings that can be manipulated. In this work, we propose several technical extensions to build on previous work in image embedding. \paragraph{Latent Space Manipulation for Image Editing.} GAN interpretability and GAN-based image manipulation has been of recent interest to the GAN research community. There are broadly two spaces where semantic manipulation of images is possible: the latent and the activation space. Some notable works in the latent space manipulation domain try to understand the nature of the latent space of the GAN to extract meaningful directions for edits. For instance, GANspace~\cite{harkonen2020ganspace} is able to extract linear directions from the StyleGAN\xspace latent space (W space) in an unsupervised fashion using Principal Component Analysis (PCA). Another notable work, StyleRig~\cite{tewari2020stylerig} learns a mapping between a riggable face model and the StyleGAN\xspace latent space. On the other hand, studying the non-linear nature of the StyleGAN\xspace latent space, StyleFlow~\cite{abdal2020styleflow} uses normalizing flows to model the latent space of StyleGAN\xspace to produce various sequential edits. Another approach StyleCLIP~\cite{patashnik2021styleclip} uses text information to manipulate the latent space. The other set of papers focus on the layer activations~\cite{Bau:Ganpaint:2019, bau2020units} to produce fine-grained local edits to an image generated by StyleGAN\xspace. Among them are TileGAN~\cite{fruhstuck2019tilegan}, Image2StyleGAN++~\cite{abdal2020image2stylegan++}, EditStyle~\cite{collins2020editing} which try to manipulate the activation maps directly to achieve a desired edit. Recently developed StyleSpace~\cite{wu2020stylespace} studies the style parameters of the channels to produce fine-grained edits. StylemapGAN~\cite{kim2021stylemapgan} on the other hand converts the latent codes into spatial maps that are interpretable and can be used for local editing of an image. \paragraph{Conditional GANs.} One of the main research areas enabling high quality image manipulation is the work on conditional GANs\linebreak (CGANs)~\cite{mirza2014conditional}. One way to incorporate a user's input for manipulation of images is to condition the generation on another image. Such networks can be trained in either paired~\cite{park2019SPADE,Zhu_2020} or unpaired fashion~\cite{Zhu_2017,zhu2017multimodal} using the cycle-consistency losses. One important class of CGANs uses images as conditioning information. Methods such as pix2pix~\cite{pix2pix2017}, BicycleGAN~\cite{zhu2017multimodal}, pix2pixHD~\cite{wang2018pix2pixHD}, SPADE~\cite{park2019SPADE}, MaskGAN~\cite{fedus2018maskgan}, controllable person image synthesis~\cite{Men_2020}, SEAN~\cite{Zhu_2020} and SofGAN~\cite{chen2020free} are able to produce high quality images given the condition. For instance, these networks can take a segmentation mask as an input and can generate the images consistent with manipulations done to the segmentation masks. Particularly on faces, StarGANs1\&2~\cite{Choi_2018, choi2020starganv2} are able to modify multiple attributes. Other notable works, FaceShop~\cite{Portenier_2018}, Deep plastic surgery~\cite{Yang_2020}, Interactive hair and beard synthesis~\cite{Olszewski_2020} and SC-FEGAN~\cite{Jo_2019} can modify the images using the strokes or scribbles on the semantic regions. For the hairstyle and appearance editing, we identified two notable relevant works. MichiGAN~\cite{Tan_2020} demonstrated high quality hair editing using an inpainting network and mask-conditioned SPADE modules to draw new consistent hair. LOHO~\cite{saha2021loho} decomposes the hair into perceptual structure, appearance, and style attributes and uses latent space optimization to infill missing hair structure details in latent space using the StyleGAN2\xspace generator. We compare with both these works quantitatively and qualitatively in Sec.~\ref{sec:competing}. \begin{figure}[thpb] \centering \includegraphics[width=\linewidth]{Figures/latent_space.pdf} \caption{The {\color{darkblue} relation between $FS$ and $W+$} latent space. The first \ensuremath{m}\xspace (for \ensuremath{m}\xspace=7) blocks of the $W+$ code are replaced by the output of style block \ensuremath{m}\xspace to form a structure tensor $\ensuremath{\mathbf{F}}\xspace$, and the remaining parts {\color{darkblue} of $W+$} are used as an appearance code $\ensuremath{\mathbf{S}}\xspace$.} \label{fig:latent_space} \end{figure} \section{Method} \label{sec:method} \subsection{Overview} We create composite images by selecting semantic regions (such as hair, or facial features) from reference images and seamlessly blending them together. To this end, we employ automatic segmentation of reference images and make use of a \textit{target} semantic segmentation mask image \ensuremath{\mathbf{M}}\xspace{}. To perform our most important example edit, hairstyle transfer, one can copy the hairstyle from one image, and use another image for all other semantic categories. More generally, a set of $K$ reference images, $\ensuremath{\Image_k}\xspace$ for $k=1..K$, are each aligned to the target mask and then blended to form a novel image. The output of our approach is a composite image, \ensuremath{\Image^\text{blend}}\xspace, in which the region of semantic-category $k$ has the style of reference image $\ensuremath{\Image_k}\xspace.$ See Fig.~\ref{fig:method-overview} for an overview. \begin{figure*} \centering \includegraphics[width=1.0\textwidth]{Figures/method-overview-88-56-with-schematic.png} \caption{An overview of the method; (a) reference images for the face (top) and hair (bottom) features, (b) reconstructed images using the $FS$ latent space, (c) a target mask {\color{darkblue} with hair region (magenta) from the hair image and all other regions from the face image}, (d) alignment in $W+$ space, (e) a close-up view of the face (top) and hair (bottom) in $W+$ space, (f) close-up views after details are transferred, (g) an entire image with details transferred, (h) the structure tensor is transferred into the blended image {\color{dartmouthgreen} but the appearance code is from $\ensuremath{\mathbf{S}}\xspace_\text{face}$}, and (i) the appearance code is optimized. {\color{darkblue}\xspace The data flow through our process is illustrated in the schematic at the bottom.} } \label{fig:method-overview} \end{figure*} {\color{darkblue} Our approach to image blending finds a latent code for the blended image, which has the benefit of avoiding many of the traditional artifacts of image blending, particularly at the boundaries of the blended regions. In particular, we build on the StyleGAN2\xspace architecture~\cite{Karras2019stylegan2} and extend the II2S~\cite{zhu2020improved} embedding algorithm. The II2S algorithm uses the inputs of the 18 affine style blocks of StyleGAN2\xspace as a single $W+$ latent code. The $W+$ latent code allows the input of each block to vary separately, but II2S is biased towards latent codes that have a higher probability according to the StyleGAN2\xspace training set. There is a potential to suppress or reduce the prominence of less-common features in the training data. } In order to increase the capacity of our embedding and capture image details, we embed images using a latent code $\ensuremath{\mathbf{C}}\xspace = (\ensuremath{\mathbf{F}}\xspace, \ensuremath{\mathbf{S}}\xspace)$ comprised of a \textit{structure tensor}, $\ensuremath{\mathbf{F}}\xspace\in\mathcal{R}^{32\times32\times512}$ which replaces the output of the style block at layer $\ensuremath{m}\xspace$ of the StyleGAN2\xspace image synthesis network, where $\ensuremath{m}\xspace=7$ in our experiments, and an \textit{appearance code}, $\ensuremath{\mathbf{S}}\xspace\in\mathcal{R}^{\ensuremath{(18-m)}\xspace \times512}$ that is used as input to the remaining style blocks. {\color{darkblue}\xspace The relationship of our latent code to the StyleGAN2 architecture is illustrated in Fig.~\ref{fig:latent_space}.} This proposed extension of {\color{dartmouthgreen} conventional} GAN embedding, which we call $FS$ space, provides more degrees of freedom to capture individual facial details such as moles. However, it also requires a careful design of latent code manipulations, because it is easier to create artifacts. Our approach includes the following major steps: \begin{itemize} \item Reference images $\ensuremath{\Image_k}\xspace$ are segmented and a \textit{target} segmentation is generated automatically, or optionally the target segmentation is manually edited. \item {\color{darkblue}\xspace {\color{darkblue} Embed input reference images $\ensuremath{\Image_k}\xspace$ to find latent codes $\ensuremath{\CodeK^\text{rec}}\xspace = (\ensuremath{\StructureTensorK^\text{rec}}\xspace,\ensuremath{\AppearanceCodeK}\xspace)$,}} % \item {\color{darkblue} Find latent codes $\ensuremath{\CodeK^\text{align}}\xspace = (\ensuremath{\StructureTensorK^\text{align}}\xspace, \ensuremath{\AppearanceCodeK}\xspace)$ that are embeddings of images which match the target segmentation $\ensuremath{\mathbf{M}}\xspace$ while also being similar to the input images $\ensuremath{\Image_k}\xspace$.} \item A combined structure tensor $\ensuremath{\StructureTensor^\text{blend}}\xspace$ is formed by copying region $k$ of $\ensuremath{\StructureTensorK^\text{align}}\xspace$ for each $k=1...K$. \item Blending weights for the appearance codes $\ensuremath{\AppearanceCodeK}\xspace$ are found so that the appearance code $\ensuremath{\AppearanceCode^\text{blend}}\xspace$ is a mixture of the appearances of the aligned images. The mixture weights are found using a novel masked-appearance loss function. \end{itemize} \subsection{Initial Segmentation} The first step is to select reference images, (automatically) segment them, and to select regions in the reference images that should be copied to the target image. Let $\ensuremath{\mathbf{M}_k}\xspace = \ensuremath{\textsc{Segment}}\xspace(\ensuremath{\Image_k}\xspace)$ indicate the segmentation of reference image $\ensuremath{\Image_k}\xspace$, where $\ensuremath{\textsc{Segment}}\xspace$ is a segmentation network such as BiSeNET~\cite{Yu2018}. The aim is to form a composite image $\ensuremath{\Image^\text{blend}}\xspace$ consistent with a \textit{target} segmentation mask $\ensuremath{\mathbf{M}}\xspace$ so that at locations $(x,y)$ in the image where $\ensuremath{\mathbf{M}}\xspace(x,y)=k$, the visual properties of $\ensuremath{\Image^\text{blend}}\xspace$ will be transferred from reference images $\ensuremath{\Image_k}\xspace$. The target mask $\ensuremath{\mathbf{M}}\xspace$ is created automatically, however one can also edit the segmentation mask manually to achieve more control over the shapes of each semantic region of the output. {\color{darkblue}\xspace Such editing may, for example, be useful to {\color{darkblue} translate and scale} the regions in cases where the original images are not in the same pose. In the domain of cropped portrait images, images are coarsely aligned by placing the face region in the center of the image.} In this exposition, we will focus our discussion on {\color{darkblue}\xspace automatic processing (without editing)}. To construct a target mask automatically, each pixel $\ensuremath{\mathbf{M}}\xspace(x,y)$ is set to a value $k$ that satisfies the condition that $\ensuremath{\mathbf{M}_k}\xspace(x,y) = k$. {\color{darkblue} To resolve conflicts between segmentation masks (the condition $\ensuremath{\mathbf{M}_k}\xspace(x,y) = k$ is satisfied for two or more $k$), we assume that the values $k$ are sorted according to priority, so that higher values of $k$ are composited over lower values of $k$. A conflict would happen, for example, if a pixel is covered by \textit{skin} (label 1) in a reference image corresponding to the label \textit{skin}, but also covered by \textit{hair} (label 13) in a reference image corresponding to \textit{hair}, and so the label for \textit{hair} would be chosen. Some pixels may not be covered by any of the segmentation masks (the condition $\ensuremath{\mathbf{M}_k}\xspace(x,y) = k$ is not satisfied for any $k$). } In this case, a portion of the target mask will be in-painted using a heuristic method {\color{darkblue} explained in the supplementary materials}. The process of automatically creating a mask is illustrated in Fig.~\ref{fig:make-mask}. \begin{figure} \centering \includegraphics[width=0.8\columnwidth]{Figures/make-mask-v2.pdf} \caption{Generating the target mask. In this example, 19 semantic regions are relabeled to form four semantic categories including background. The label used in the target mask $\ensuremath{\mathbf{M}}\xspace$ is the largest index $k$ such that $\ensuremath{\mathbf{M}_k}\xspace=k$.} \label{fig:make-mask} \end{figure} \subsection{Embedding:} Before blending images, we first align each image to the target mask $\ensuremath{\mathbf{M}}\xspace$. This is important because the appearance of many features such as hair, nose, eyes, and ears depend on the pose of the head as a whole, which introduces a dependency between them. Our approach to aligning the reference images has two parts: \begin{enumerate} \item \textbf{Reconstruction:} A latent code $\ensuremath{\Code^{\text{rec}}}\xspace_k$ is found to reconstruct the input image $\ensuremath{\Image_k}\xspace$. \item \textbf{Alignment:} A nearby latent code $\ensuremath{\mathbf{C}}\xspace_k^\text{align}$ is found that minimizes the cross-entropy between the generated image and the target mask $\ensuremath{\mathbf{M}}\xspace$. \end{enumerate} \subsubsection{Reconstruction} \label{sec:reconstruction} Given an image $\ensuremath{\Image_k}\xspace$ we aim to find a code $\ensuremath{\CodeK^\text{rec}}\xspace$ so that $\ensuremath{G}\xspace(\ensuremath{\CodeK^\text{rec}}\xspace)$ reconstructs the image $\ensuremath{\Image_k}\xspace$, where $\ensuremath{G}\xspace$ is the StyleGAN2\xspace image synthesis network. Our approach to finding a reconstruction code $\ensuremath{\CodeK^\text{rec}}\xspace$ is to initialize it using II2S~\cite{zhu2020improved}, which finds a latent code $\WPCode_k^\text{rec}$ in the $W+$ latent-space of StyleGAN2\xspace. The challenge of any reconstruction algorithm is to find a meaningful trade-off between reconstruction quality and suitability for editing or image compositing. % {\color{darkblue} The $W$ latent space of StyleGAN2\xspace{} has only 512 components. While it is expressive enough to capture generic details, such as wrinkles, it is not possible to encode specific details of a particular face (such as the precise locations of moles, wrinkles, or eyelashes). The use of $W+$ space and II2S improves the expressiveness of the latent space, but it is still not sufficient for a faithful reconstruction. } One possible approach is noise embedding that leads to embedded images with almost perfect reconstruction, but leads to strong overfitting which manifests itself in image artifacts in downstream editing and compositing tasks. Our idea is to embed into a new latent space, called $FS$ space, that provides better control than $W+$ space without the problems of noise embedding. Similarly to $W+$ embedding, we need to carefully design our compositing operation, so that image artifacts do not manifest themselves. The difference between reconstruction in $W+$ vs $FS$ space is shown in Fig.~\ref{fig:reconstruction}, illustrating that key identifying features of a person (such as a facial mole) or important characteristics of a subject's expression (hairstyle, furrows in the brow) are captured in the new latent space. \begin{figure} \centering \includegraphics[width=0.99\linewidth]{Figures/reconstruction2.png} \caption{Reconstruction results on different spaces; (top row) in $W+$ space, structure of the subject's curly hair on the left of the image is lost, and a wisp of hair on her forehead as well as her necklace is removed, but they are preserved in $FS$ space; (middle row) the hair and brow furrows details are important to the expression of the subject, they are not preserved in $W+$ space but they are in $FS$ space; (bottom row) the ground-truth image has freckles, without noise optimization this is not captured in $W+$ space but it is preserved in $FS$ space. } \label{fig:reconstruction} \end{figure} We capture specific facial details by using a spatially correlated signal as part of our latent code. We use the output of one of the style-blocks of the generator as a spatially-correlated \textit{structure-tensor} $\ensuremath{\mathbf{F}}\xspace$, which replaces the corresponding blocks of the $W+$ latent. The choice of a particular style block is a design decision, however each choice results in a different-sized latent code and in order to keep the exposition concise our discussion will use style-block eight. The resulting latent code has more capacity than the $W+$ latent-codes, and we use gradient descent initialized by a $W+$ latent-code in order to reconstruct each reference image. We form an initial structure tensor $\ensuremath{\StructureTensorK^\text{init}}\xspace=\ensuremath{G}\xspace_\ensuremath{m}\xspace(\ensuremath{\WPCodeK^\text{rec}}\xspace)$, and the remaining \ensuremath{(18-m)}\xspace blocks of $\WPCode_k^\text{rec}$ are used to initialize the appearance code $\ensuremath{\mathbf{S}}\xspace^\text{init}_k$. Then we set $\ensuremath{\CodeK^\text{rec}}\xspace$ to the nearest local minimum of \begin{align} \ensuremath{\CodeK^\text{rec}}\xspace &=\arg\min_\ensuremath{\mathbf{C}}\xspace L_\text{PIPS}\xspace(\ensuremath{\mathbf{C}}\xspace) + L_\StructureTensor .\label{eq:loss-rec}\\ \intertext{where} L_\StructureTensor &= \|\ensuremath{\mathbf{F}}\xspace-\ensuremath{\mathbf{F}}\xspace^{\text{init}}_k\|^2 \label{eq:l-f} \end{align} The term $L_\StructureTensor$ in the loss function~\eqref{eq:l-f} encourages solutions in which $\ensuremath{\mathbf{F}}\xspace$ remains similar to the activations of a $W+$ code so that the result remains close to the valid region of the StyleGAN2\xspace latent space. \subsubsection{Alignment} We now have each reference image $\ensuremath{\Image_k}\xspace$ encoded as a latent code $\ensuremath{\CodeK^\text{rec}}\xspace$ consisting of a tensor $\ensuremath{\StructureTensorK^\text{rec}}\xspace$ and appearance code $\ensuremath{\AppearanceCodeK}\xspace$. While $\ensuremath{\CodeK^\text{rec}}\xspace$ captures the appearance of the reference image $\ensuremath{\Image_k}\xspace$, the details will not be aligned to the target segmentation. Therefore, we find latent codes $\ensuremath{\CodeK^\text{align}}\xspace$ that match the target segmentation, and which are nearby $\ensuremath{\CodeK^\text{rec}}\xspace$ {\color{darkblue} in latent space}. % % We find that directly optimizing $\ensuremath{\CodeK^\text{align}}\xspace$ is challenging because the details of $\ensuremath{\StructureTensorK^\text{rec}}\xspace$ are spatially correlated. Instead we first search for a $W+$ latent code, $\ensuremath{\WPCode^\text{align}}\xspace$ for the aligned image and then we transfer details from $\ensuremath{\StructureTensorK^\text{rec}}\xspace$ into $\ensuremath{\StructureTensorK^\text{align}}\xspace$ where it is safe to do so. {\color{darkblue}\xspace Results of aligning images to the target mask are shown in Fig.~\ref{fig:method-overview} and Fig.~\ref{fig:qualitative-ablation-study}.} {\color{darkblue} Our approach for finding a latent code is to compose the generator $\ensuremath{G}\xspace$ with a semantic segmentation network $\ensuremath{\textsc{Segment}}\xspace$ to construct the differentiable function $\ensuremath{\textsc{Segment}}\xspace\circ\ensuremath{G}\xspace$, which is a differentiable generator of semantic segmentations. Using GAN inversion (e.g. II2S) on this new generator to minimize an appropriate loss such as cross-entropy, it is possible to find a latent code $\ensuremath{\WPCode^\text{align}}\xspace$, so that $\ensuremath{G}\xspace(\ensuremath{\WPCode^\text{align}}\xspace)$ is an image whose segmentation matches the target segmentation. However, GAN inversion is ill-posed for segmentation masks, as many images could produce the same semantic segmentation. We also aim to find an image that is also as similar as possible to the original latent code of a reference image. We therefore experimented with a combination of $L_2$, $L_1$, and style losses to preserve the content of the reference images and found that only using the style loss, produces the best results.} In order to preserve the style between an aligned image $G(\ensuremath{\WPCode^\text{align}}\xspace)$ and the original image $\ensuremath{\Image_k}\xspace$, we use a masked style-loss. The masked loss described in LOHO~\cite{saha2021loho} uses a static mask in order to compute the gram matrix of feature activations only within a specific region, whereas each step of gradient descent in our method produces a new latent code, and leads to a new generated image and segmentation. Therefore the mask used at each step is dynamic. Following~\cite{saha2021loho}, we base the loss on the gram matrix \begin{align} \mathbf{K}_{\ell}(\ensuremath{\mathbf{I}}\xspace) = \gamma_{\ell}^T \gamma_{\ell}^{}, \label{eq:gramm-of-layer} \end{align} where $\gamma_\ell^{}\in\mathcal{R}^{H_\ell \ensuremath{W}\xspace_\ell\times C_\ell}$ is a matrix formed by the activations of layer $\ell$ of the VGG network. In addition, we define a region mask for region $k$ of an image $\ensuremath{\mathbf{I}}\xspace$ as \begin{align} \rho_k(\ensuremath{\mathbf{I}}\xspace)=1\{\textsc{Segment}(\ensuremath{\mathbf{I}}\xspace)=k\}, \end{align} where $1\{\cdot\}$ is the indicator function, so $\rho_k$ is an indicator for the region of an image that is of semantic category $k$. Then the style loss is the magnitude of the difference between the gram matrices of the images generated by a latent code $\WPCode$ and the target image $\ensuremath{\Image_k}\xspace$, and it is evaluated only within semantic region $k$ of each image \begin{align} L_s &= \sum_{\ell} \|\mathbf{K}_{\ell}(\rho_k(\ensuremath{G}\xspace(\WPCode))\odot \ensuremath{G}\xspace(\WPCode))-\mathbf{K}_{\ell}(\rho_k(\ensuremath{\Image_k}\xspace)\odot \ensuremath{\Image_k}\xspace))\|^2, \end{align} where the summation is over layers $relu1\_2$, $relu2\_2$, $relu3\_3$, and $relu4\_3$ of VGG-16, as was done in LOHO~\cite{saha2021loho}. The formulation $\rho_k(\ensuremath{\Image_k}\xspace)\odot \ensuremath{\Image_k}\xspace$ describes the masking of an image by setting all pixels outside the semantic region $k$ to 0. In order to find an aligned latent code, we use gradient descent to minimize a loss function which combines the cross-entropy of the segmented image, and the style loss \begin{align} L_\text{align}(W) = \textsc{XEnt}(\ensuremath{\mathbf{M}}\xspace, \textsc{Segment}(G(W))) + \lambda_s L_s, \label{eq:l-align} \end{align} where $\textsc{XEnt}$ is the multi-class cross-entropy function. {\color{darkblue} We optimize only the portion of $W+$ space that corresponds to $\ensuremath{\mathbf{F}}\xspace$ during alignment because the goal is to construct $\ensuremath{\mathbf{F}}\xspace^\text{align}$.} We rely on early-stopping to keep the $\ensuremath{\WPCode^\text{align}}\xspace$ latent code nearby the initial reconstruction code $\ensuremath{\WPCode^\text{rec}}\xspace,$ and $\lambda_s$ is set to the value recommended by~\cite{saha2021loho}. {\color{darkblue}\xspace We stop at 100 iterations, but find that between 50 and 200 iterations produce qualitatively similar results.} \subsubsection{{\color{darkblue}\xspace Structure Transfer}} {\color{darkblue}\xspace Alignment using $\ensuremath{\WPCode^\text{align}}\xspace$ produces plausible images but some details are changed as shown in Fig. \ref{fig:method-overview}(e) vs Fig. \ref{fig:method-overview}(f). In cropped portrait images, regions which overlap are often spatially aligned, and so we transfer the structure of the reconstructed images within those regions.} {\color{darkblue} Note that the target mask is not always perfectly aligned to regions in the reference images, due to inpainting or, as shown in Fig.\ref{fig:hair-gallery}, if the hair shape comes from a third reference image. } In order to transfer the structure and appearance from image $\ensuremath{\Image_k}\xspace$ into $\ensuremath{\StructureTensor_k}\xspace$, we use binary masks to define safe regions to copy details, \begin{align} \alpha_k(x,y) & =1\{\ensuremath{\mathbf{M}}\xspace(x,y)=k\}, \label{eq:alpha_k} \\ \beta_k(x,y) & =1\{\ensuremath{\mathbf{M}_k}\xspace(x,y)=k\}, \label{eq:beta_k} \end{align} where $1\{\cdot\}$ is the indicator function. {\color{dartmouthgreen} Let $\alpha_{k,\ell}$ denote $\alpha_k$ downsampled using bicubic-resampling to match the dimensions of the activations in layer $\ell$, noting that the resampled mask is no longer binary. The mask $\beta_{k, \ell}$ is similarly defined. At layer $m$,} the mask $\alpha_{k,\ensuremath{m}\xspace}\cdot\beta_{k,\ensuremath{m}\xspace}$ is a {\color{darkblue}\xspace soft} region {\color{darkblue}\xspace with membership values in the range $[0,1]$ }where it is safe to copy structure from the code $\ensuremath{\StructureTensorK^\text{rec}}\xspace$ because the semantic classes of the target and reference image are the same. The mask $(1-\alpha_{k,\ensuremath{m}\xspace}\cdot\beta_{k,\ensuremath{m}\xspace})$ is a {\color{darkblue}\xspace soft} region where we must fall-back to $\ensuremath{\WPCodeK^\text{align}}\xspace$, which has less capacity to reconstruct detailed features. {\color{darkblue}\xspace These values are not restricted to binary values because they are the result of bicubic downsampling.} We use the structure-tensor \begin{align} \ensuremath{\StructureTensorK^\text{align}}\xspace &= \alpha_{k,\ensuremath{m}\xspace}\cdot\beta_{k,\ensuremath{m}\xspace}\cdot \ensuremath{\StructureTensorK^\text{rec}}\xspace + (1-\alpha_{k,\ensuremath{m}\xspace}\cdot\beta_{k,\ensuremath{m}\xspace})\cdot \ensuremath{G}\xspace_\ensuremath{m}\xspace(\ensuremath{\WPCodeK^\text{align}}\xspace), \label{eq:f-align} \end{align} where $\ensuremath{G}\xspace_\ensuremath{m}\xspace(\ensuremath{\WPCodeK^\text{align}}\xspace)$ is the output of style-block \ensuremath{m}\xspace of the generator applied to input $\ensuremath{\WPCodeK^\text{align}}\xspace$. We now have an aligned latent representation $\ensuremath{\CodeK^\text{align}}\xspace$ for each reference image $k$. Next we can composite the final image by blending the structure tensors $\ensuremath{\StructureTensorK^\text{align}}\xspace$ and appearance codes $\ensuremath{\AppearanceCodeK}\xspace$ as described in the next two subsections. \subsection{Structure Blending:} In order to create a blended image, we combine the structure tensor elements of $\ensuremath{\CodeK^\text{align}}\xspace$ using weights $\alpha_{k,\ensuremath{m}\xspace}$ to mix the structure tensors, so \begin{align} \ensuremath{\StructureTensor^\text{blend}}\xspace &=\sum_{k=1}^K \alpha_{k,\ensuremath{m}\xspace} \odot \ensuremath{\StructureTensorK^\text{align}}\xspace. \end{align} The coarse structure of each reference image can be composited simply by combining the regions of each structure tensor, however mixing the appearance codes requires more care. \subsection{Appearance Blending} Our approach to image blending is to find a single style code $\ensuremath{\AppearanceCode^\text{blend}}\xspace$, which is a mixture of the $K$ different reference codes $\ensuremath{\AppearanceCode_k}\xspace, k=1..K$. To find $\ensuremath{\AppearanceCode^\text{blend}}\xspace$ we optimize a \textit{masked} version of the LPIPS distance function as a loss. % Following {\color{darkblue}\xspace the notation of}~\cite{Zhang2018}, we will describe a \textit{masked} version of LPIPS that will be used to solve for $\ensuremath{\AppearanceCode^\text{blend}}\xspace$. {\color{darkblue} A complete motivation of LPIPS is beyond the scope of this work, we refer the reader to~\cite{Zhang2018} and the \textit{lin} version of $L_\text{PIPS}\xspace$ for details. The focus of this section is to explain our modification, which extends it to be used to compare $K$ different masked-images. First, we include the formula for the original $L_\text{PIPS}\xspace$ function for comparison. Let $\VGGActivations{\ell}$ indicate the activations of layer $\ell$ of convnet (VGG) normalized across the channel-dimension as described in~\cite{Zhang2018}. The shape of that tensor is $\ensuremath{W}\xspace_\ell, \ensuremath{H}\xspace_\ell,$ and it has $\ensuremath{C}\xspace_\ell$ channels. To compare an image $\ensuremath{\mathbf{I}}\xspace$ to another image $\ensuremath{\mathbf{I}}\xspace_o$ \begin{align} L_\text{PIPS}\xspace &= \sum_{\ell} \frac{1}{\ensuremath{H}\xspace_\ell \ensuremath{W}\xspace_\ell} \sum_{i,j}\!\| \PerChannelWeightsOf{\ell} \odot \Delta^{\ell}_{i,j}(\ensuremath{\mathbf{I}}\xspace, \ensuremath{\mathbf{I}}\xspace_o)\|^2 \end{align} {where} \begin{align} \Delta^{\ell}_{i,j}(\ensuremath{\mathbf{I}}\xspace, \ensuremath{\mathbf{I}}\xspace_o)&=\VGGActivations{\ell}_{i,j}(\ensuremath{\mathbf{I}}\xspace) -\VGGActivations{\ell}_{i,j}(\ensuremath{\mathbf{I}}\xspace_o)) \end{align} and the vector $\PerChannelWeightsOf{\ell}$ is a learned vector of per-channel weights associated with layer $\ell$. Similar to~\cite{Zhang2018}, we do not use every layer of VGG and instead set $\ell$ to only the three layers (\texttt{conv1}-\texttt{conv3}) of VGG. A \textit{masked} version of the loss uses the masks $\alpha_{k,\ell}$ to compare a region $k$ of an arbitrary image $\ensuremath{\mathbf{I}}\xspace$ with each of the $k$ corresponding aligned images $\ensuremath{\hat{\Image}_k}\xspace=\ensuremath{G}\xspace(\ensuremath{\CodeK^\text{align}}\xspace)$, so \begin{align} L_\text{mask}\xspace\!&=\!\sum_{\ell} \frac{1}{\ensuremath{H}\xspace_\ell\ensuremath{W}\xspace_\ell}\! \sum_{kij} (\alpha_{k\ell})_{ij} \|\PerChannelWeightsOf{\ell} \odot \Delta^{\ell}_{i,j}(\ensuremath{\mathbf{I}}\xspace, \ensuremath{\hat{\Image}_k}\xspace) \|^2, \label{eq:l-masked} \end{align} where $\Delta$ is defined as above and $\alpha_{k, \ell}$ is a mask which has been resampled {\color{darkblue}\xspace(bicubic)} to match the dimensions of each layer. When solving for $\ensuremath{\AppearanceCode^\text{blend}}\xspace$, we want to constrain the latent-code so that it stays within a region of latent space that contains the aligned reference codes ($\ensuremath{\AppearanceCodeK}\xspace$). Due to the ill-conditioned nature of GAN inversion, an unconstrained solution will tend to overfit the loss and find an appearance code that is arbitrarily far from any of the inputs. A constrained solution restricts the set of possible latent-codes to a small portion of the embedding space. Our approach is to find a set of $k$ different blending weights $U = \{\vb{u}_k\}$ so that each $\vb{u}_k$ is a vector in $\mathcal{R}^{\ensuremath{(18-m)}\xspace\times512}$. The blended code $\ensuremath{\AppearanceCode^\text{blend}}\xspace$ satisfies \begin{align} \ensuremath{\AppearanceCode^\text{blend}}\xspace &= \sum_k \vb{u}_k \odot \ensuremath{\AppearanceCodeK}\xspace \label{eq:s-blend} \end{align} and the weights satisfy the constraints \begin{align} \sum_k \vb{u}_k &= \vb{1}, & \vb{u}_k &\geq 0 \label{eq:convexity} \end{align} so that each element of $\ensuremath{\AppearanceCode^\text{blend}}\xspace$ is a convex combination of the corresponding elements in reference codes $\ensuremath{\AppearanceCodeK}\xspace$. We find $\ensuremath{\Code^\text{blend}}\xspace$ using projected gradient descent~\cite{landweber1951iteration} to minimize $L_\text{mask}\xspace$ with $I=G(\ensuremath{\Code^\text{blend}}\xspace)$, and \ensuremath{\Code^\text{blend}}\xspace itself is a function {\color{dartmouthgreen} of $U$} in equation \eqref{eq:s-blend}. We initialize $U$ so that the blended image would be a copy of one of the reference images and solve for the values that minimize $L_\text{mask}\xspace$ subject to the constraints \eqref{eq:convexity}. } \subsection{Mixing Shape, Structure, And Appearance}\label{sec:mixing-shape-structure-and-apperance} We have presented an approach to create composite images using a set of reference images $\ensuremath{\Image_k}\xspace$ in which we transfer the shape of a region, the structure tensor information $\ensuremath{\StructureTensor_k}\xspace$, and also the appearance information $\ensuremath{\AppearanceCode_k}\xspace$. The LOHO~\cite{saha2021loho} approach demonstrated that different reference images can be used for each attribute (shape, structure, and appearance) and our approach is capable of doing the same. We simply use an additional set of images $\ensuremath{\RefImageK^{\text{app}}}\xspace$ for the appearance information, and we set $\ensuremath{\AppearanceCode_k}\xspace$ using the last \ensuremath{(18-m)}\xspace blocks of the $W+$ code that reconstructs $\ensuremath{\RefImageK^{\text{app}}}\xspace$ instead of using the latent code that reconstructs $\ensuremath{\Image_k}\xspace$. The additional images $\ensuremath{\RefImageK^{\text{app}}}\xspace$ do not need to be aligned to the target mask. We show example of mixing shape, structure, and appearance in Fig.~\ref{fig:teaser}(g,h). The larger structures of the hair (locks of hair, curls) are transferred from the structure reference, and the hair color and micro textures are transferred from the appearance image. \begin{figure*} \centering \includegraphics[width=0.99\linewidth]{Figures/gallery.pdf} \caption{Hair style gallery showing different hairstyles applied to a person by varying the hair structure and appearance. Reference images for the hair appearance are shown at the top of each column, Reference images for the hair structure and the target segmentation masks are shown to the left of each row. Also note that in the last two rows, the hair shape is different from the hair shape of the structure reference images.} \label{fig:hair-gallery} \end{figure*} \begin{figure*} \centering \includegraphics[width=0.99\linewidth]{Figures/face_swapping.png} \caption{Face swapping results achieved by our method. Each example shows smaller insets: a target segmentation mask (top left) with the source regions indicated using cyan and magenta, an 'identity' image (center left), corresponding to the cyan region which includes all regions except the ones being transferred, a structure reference image (bottom left) and an appearance image (bottom right) each used to transfer the structure or appearance of the magenta regions. The first row shows examples of eye and eyebrow transfer by varying the appearance reference images; the second row shows examples of eye, eyebrows, nose, and mouth transfer; the third row shows examples transferring the entire facial region including skin.} \label{fig:face-swapping} \end{figure*} \section{Results}\label{sec:results} In this section, we will show a quantitative and qualitative evaluation of our method. We implemented our algorithm using PyTorch and a single NVIDIA TITAN Xp graphics card. The process of finding an II2S embedding takes 2 minutes per image on average, the optimization in \eqref{eq:loss-rec} takes 1 minute per image. The resulting codes are saved and reused when creating composite images. For each composite image, we solve equation \eqref{eq:l-align} and then \eqref{eq:l-masked} to generate a composite image in an average time of two minutes. \subsection{Dataset} We use a set of 120 high resolution ($1024\times 1024$) images from~\cite{zhu2020improved}. From these images, 198 pairs of images were selected for the hairstyle transfer experiments based on the variety of appearances and hair shape. Images are segmented and the \textit{target} segmentation masks are generated automatically. \subsection{Competing methods}\label{sec:competing} We evaluate our method by comparing the following three algorithms: MichiGAN~\cite{Tan_2020}, LOHO~\cite{saha2021loho}, and our proposed method. The authors of LOHO and MichiGAN provide public implementations, which we used in our comparison. However, MichiGAN uses a proprietary inpainting module that the authors could not share. The authors supported our comparison by providing some inpainting results for selected images on request. LOHO also uses a pretrained inpainting network. Based on our analysis, both methods can be improved by using different inpainting networks as proposed in the initial papers. We therefore replaced both inpainting networks by the current state of the art CoModGAN~\cite{zhao2021comodgan} trained on the same dataset as LOHO. All hyperparameters and configuration options were kept at their default values. Our approach was used to reconstruct images using a fixed number of gradient descent iterations for each step. To solve for $\ensuremath{\CodeK^\text{rec}}\xspace$ in equation \eqref{eq:loss-rec} we used 400 iterations, to solve for $\ensuremath{\mathbf{C}}\xspace_k^\text{align}$ using \eqref{eq:l-align} we stopped after 100 iterations, and to solve for the blending weights $u$ using \eqref{eq:l-masked} we stopped after 600 iterations. \textbf{\color{darkblue}\xspace Source code for our method will be made public after an eventual publication of the paper at \url{https://authorname.github.io/Barbershop}\xspace.} \subsection{Comparison} \subsubsection{User Study}\label{sec:user-study} We conducted a user study using Amazon's Mechanical Turk to evaluate the hairstyle transfer task. For this task we use the 19-category segmentation from CelebAMask-HQ. A \textit{hairstyle} image was used as the reference for the the corresponding category in CelebAMask-HQ, and an \textit{Identity} image was used for all other semantic categories. We generated composite images using our complete approach and compared the results to LOHO~\cite{saha2021loho} and to MichiGAN~\cite{Tan_2020}. {\color{darkblue} Examples of the images generated using these methods are shown in Fig.~\ref{fig:comparison}.} Users were presented with each image in a random order (ours on the left and the other method on the right, or with ours on the right and the other method on the left). The reference images were also shown at 10\% the size of the synthesized images. The user interface allowed participants to zoom in and inspect details of the image, and our instructions encouraged them to do so. Each user was asked to indicate which image combined the face of one image and the hair of another with the highest quality, and fewest artifacts. On average, users spent 90 seconds comparing images before making a selection. We asked 396 participants to compare ours to LOHO, and our approach was selected 378 times (95\%) and LOHO was selected 18 times (5\%). We asked another 396 participants to compare against MichiGAN, and the results were 381 (96\%) ours vs 14 (4\%) MichiGAN. The results in both case are statistically significant. \begin{figure*}[htbp] \centering \includegraphics[width=0.95\linewidth]{Figures/SOTA} \caption{Comparison of our framework with two state of the art methods: LOHO and MichiGAN. Our results show improved transitions between hair and other regions, fewer disocclusion artifacts, and a better consistent handling of global aspects such as lighting. } \label{fig:comparison} \end{figure*} \subsubsection{Reconstruction Quality} \label{sec:reconstruction} In this work, we measure the reconstruction quality of an embedding using various established metrics: RMSE, PSNR, SSIM, VGG perceptual similarity~\cite{simonyan2014very}, LPIPS perceptual similarity, and the FID~\cite{heusel2017gans} score between the input and embedded images. The results are shown in Table~\ref{tab:reconstruction-comparison}. \begin{table} \caption{A comparison of our method to different algorithms using established metrics. Our method achieves the best scores in all metrics.} \centering \begin{tabularx}{\columnwidth}{X|c@{\hspace{6pt}}c@{\hspace{6pt}}c@{\hspace{6pt}}c@{\hspace{6pt}}c@{\hspace{6pt}}c} & RMSE$\downarrow$ & PSNR$\uparrow$ & SSIM$\uparrow$ & VGG$\downarrow$ & LPIPS$\downarrow$ & FID$\downarrow$ \\ Baseline & 0.07 & 23.53 & 0.83 & 0.76 & 0.20 & 43.99 \\ LOHO & 0.10 & 22.28 & 0.83 & 0.71 & 0.18 & 56.31 \\ MichiGAN & 0.06 & 26.51 & 0.88 & 0.48 & 0.12 & 26.82 \\ Ours & \textbf{0.03} & \textbf{29.91} & \textbf{0.90} & \textbf{0.38} & \textbf{0.06} & \textbf{21.21} \\ \end{tabularx} \label{tab:reconstruction-comparison} \end{table} \subsection{Ablation Study}\label{sec:ablation-study} \begin{figure}[htb] \centering \includegraphics[width=1.0\columnwidth]{Figures/qual-study.png} \caption{{\color{darkblue} A qualitative ablation study. We compare a baseline version that blends latent codes without image alignment and using $\ensuremath{\StructureTensorK^\text{init}}\xspace$, e.g. it uses a $W+$ code (first column), a version that uses fully optimized $FS$ codes, e.g. $\ensuremath{\StructureTensorK^\text{rec}}\xspace$, but no alignment (second column), $W+$ latent codes with the alignment step (third column), and our complete approach which uses both alignment and the $FS$ code. The reference images for the face, hairstyle, and the target mask are shown top-to-bottom on the left of each row. This figure shows that alignment ensures that each location has the same semantic meaning (e.g. background), so that inpainting is unnecessary.}} \label{fig:qualitative-ablation-study} \end{figure} {\color{dartmouthgreen} We present a qualitative ablation study of the proposed approach for hairstyle transfer. Fig.~\ref{fig:qualitative-ablation-study} provides a visual comparison of the results of hairstyle transfer. A \textit{baseline} version of our approach does not include the $FS$ latent space and does not do image alignment and is shown in Fig.~\ref{fig:qualitative-ablation-study} and is labeled `$W+$ w/o Align'. It does solve for interpolated blending weights to minimize the masked loss function from equation~\eqref{eq:l-masked}, however a mixture of unaligned latent codes does not always result in a plausible image. This is apparent when {\color{darkblue} we} compare the references image to the synthesized images. Without alignment, disoccluded regions where the hair region shrinks are not handled properly, and artifacts are visible near the boundary of the hair region. The second column uses $\ensuremath{\StructureTensorK^\text{rec}}\xspace$ rather than $\ensuremath{\StructureTensorK^\text{align}}\xspace$ when blending and so it captures more detail from the original images, however issues caused by lack of semantic alignment remain. The third column of Fig.~\ref{fig:qualitative-ablation-study} includes alignment, but it does not use $FS$ space. Without the additional capacity, the reconstructed images are biased towards a generic face and hair images, with more symmetry and less expression, character, and identifying details than the reference images.} Overall, the qualitative examples show that each successive modification to the proposed approach resulted in higher quality composite images. \subsection{Qualitative Results} In this subsection, we discuss various qualitative results that can be achieved using our method. {\color{dartmouthgreen} In Fig.~\ref{fig:hair-gallery} we show many examples of hair style transfer where the structure, shape, and appearance of hair each come from different sources; every row has the same shape and structure, every column has the same appearance. This demonstrates} that our framework can generate a large variety of edits. Starting from an initial photograph, a user can manipulate a semantic segmentation mask manually to change semantic regions, copy segmented regions from reference images, copy structure information for semantic regions from reference images, and copy appearance information from reference images. In the figure, we show many results where the shape of the hair, the structure of the hair, and the appearance of the hair is copied from three difference reference images. Together with the source image, that means that information from up to four images contributes to one final blended result image. In Fig.~\ref{fig:face-swapping} we demonstrate that our framework can handle edits to other semantic regions different from the hair. We show how individual facial features such as eyes and eyebrows can be transferred from other reference images, how all facial regions can be copied, and how all facial regions as well as the appearance can be transferred from other source images. We can also attain high quality results for such edits. We would like to remark that these edits are generally easier to perform than hair transfer. In Fig.~\ref{fig:comparison} we show selected examples to illustrate why our method is strongly preferred compared to the state of the art by users in the user study. While previous methods give good results to this very challenging problem, we can still achieve significant improvements in multiple aspects. First, one can carefully investigate the transition regions between hair and either the background and the face to see that previous work often creates hard transitions, too similar to copy and pasting regions directly. Our method is able to better make use of the knowledge encoded in GAN latent space to find semantic transitions between images. Second, other methods can easily create artifacts, due to misalignment in reference images. This manifests itself for example in features, e.g. hair structure, being cut off unnaturally at the hair boundary. Third, our method achieves a better overall integration of global aspects such as lighting. The mismatch in lighting also contributes to lower quality transitions between hair regions and other regions in other methods. By contrast, other methods also have some advantages over our method. Previous work is better in preserving some background pixels by design. However, this inherently lowers the quality of the transition regions. We only focus on hair editing for the comparison, because it seems to be by far the most challenging task. This is due to the possible disocclusion of background and face regions, the more challenging semantic blending of boundaries, and the consistency with global aspects such as lighting. Overall, we believe that we propose a significant improvement to the state of the art, as supported by our user study. We also submit all images used in the user study as supplementary materials to enable {\color{darkblue} readers} to inspect the quality of our results. \subsection{Limitations} Our method also has multiple limitations. Even though we increased the capacity of the latent space, it is difficult to reconstruct underrepresented features from the latent space such as jewelry indicated in~Fig.\ref{fig:limitations}(2,4). Second, issues such as occlusion can produce confusing results. For example, thin wisps of hair which also partially reveal the underlying face are difficult to capture in Fig.~\ref{fig:limitations}(3,5). Many details such as the hair structure in Fig.~\ref{fig:limitations}(7) are difficult to preserve when aligning embeddings, and when the reference and target segmentation masks do not overlap perfectly the method may fall back to a smoother structure. Finally, while our method is tolerant of some errors in the segmentation mask input, large geometric distortions cannot be compensated. In Fig.~\ref{fig:limitations}(2,7) we show two such examples. These limitations could be addressed in future work by filtering-out unmatched segmentation as was done by LOHO~\cite{saha2021loho}, or by geometrically aligning the segmentation masks \textit{before} attempting to transfer the hair shape using regularization to keep the segmentation masks plausible and avoid issues such as Fig.~\ref{fig:limitations}(1,7). The details of the structure tensor could be warped to match the target segmentation to avoid issues such as Fig.~\ref{fig:limitations}(6). Issues of thin or transparent occlusions are more challenging and may require more capacity or less regularization when finding embeddings. \begin{figure} \centering \includegraphics[width=\linewidth]{Figures/failures.pdf} \caption{Failure modes of our approach; (1) misaligned segmentation masks lead to implausible images; (2, 4) the GAN fails to reconstruct the face, replacing lips with teeth or removing jewelry ; (3,5) overlapping translucent or thin wisps of hair and face pose a challenge; (6) a region of the target mask that is not covered by $\beta_k$ in the hair image is synthesized with a different structure; (7) combining images taken from different perspectives can produce anatomically unlikely results, the original shape of the head is indicated in yellow. } \label{fig:limitations} \end{figure} \section{Conclusions} We introduced Barbershop, a novel framework for GAN-based image editing. A user of our framework can interact with images by manipulating segmentation masks and copying content from different reference images. We presented several important novel components. First, we proposed a new latent space that combines the commonly used $W+$ style code with a structure tensor. The use of the structure tensor makes the latent code more spatially aware and enables us to preserve more facial details during editing. Second, we proposed a new GAN-embedding algorithm for aligned embedding. Similar to previous work, the algorithm can embed an image to be similar to an input image. In addition, the image can be slightly modified to conform to a new segmentation mask. Third, we propose a novel image compositing algorithm that can blend multiple images encoded in our new latent space to yield a high quality result. Our results show significant improvements over the current state of the art. In a user study, our results are preferred over 95 percent of the time. \begin{acks} We would also like to thank the anonymous reviewers for their insightful comments and constructive remarks. This work was supported by the KAUST Office of Sponsored Research (OSR) and the KAUST Visual Computing Center (VCC). \end{acks} \bibliographystyle{ACM-Reference-Format} \section{Appendices} \subsection{Inpainting Masks} The segmentation masks of a pair of reference images will not always completely cover the entire target segmentation mask. In this case, there are some uncovered regions, indicated in white in Fig.~\ref{fig:inpaint_mask}(a), that need to be in-painted in order to create a complete target mask. In addition, the hair region is complicated in that some portions of the hair belong \textit{behind} the figure, and some portions of hair should occlude the figure. An example of our approach both \textit{without} and \textit{with} inpainting is shown in Fig.~\ref{fig:Supp_translation} - note that without inpainting we labeled uncovered pixels as \textit{background} which could cause the background to show through the hair where it should not (middle row). It is interesting to us that the alignment process, which uses the StyleGAN W+ space as a prior, does not seem to have the capacity to match the erroneous background regions in the target masks near the subject's forehead. When dealing with hair transfer, it is useful to relabel the segmentation masks using three labels of \textit{hair}, \textit{background}, and \textit{other}, where the last label includes the skin, eyes, nose, clothing, etc. We create the following masks: $\ensuremath{\mathbf{M}}\xspace_\text{hair}^\text{behind}$ is a mask labeled as \textit{background} wherever both references were background, and labeled as \textit{hair} wherever the reference image for the hair was labeled as \textit{hair}. The remaining pixels of $\ensuremath{\mathbf{M}}\xspace_\text{hair}^\text{behind}$ are unknown, and they may be portions of hair that pass behind the subject. Therefore, we inpaint $\ensuremath{\mathbf{M}}\xspace_\text{hair}^\text{behind}$ using the fast-marching method of \cite{telea2004image}, which is implemented by OpenCV. Next, we create a mask $\ensuremath{\mathbf{M}}\xspace_\text{other}^\text{middle}$ using the segmentation regions of the \textit{other} reference image, except that its original \textit{hair} region is inpainted using the same exact approach. Finally, we construct a mask $\ensuremath{\mathbf{M}}\xspace$ in three layers: we first initialize the mask with $\ensuremath{\mathbf{M}}\xspace_\text{hair}^\text{behind},$ and then we transfer the labels \textit{other} than background from $\ensuremath{\mathbf{M}}\xspace_\text{other}^\text{middle}$, and finally we set any pixel that was hair in the original reference image for hair to also have the label \textit{hair} in $\ensuremath{\mathbf{M}}\xspace$ so that we retain the bangs, or locks of hair which pass in front of the face or shoulders. The heuristic approach we used is not capable of generating segmentation masks for completely occluded features (such as eyes or ears) that were covered by hair, however GAN-based inpainting approaches for the masks themselves are a subject of future work. \subsection{Sensitivity to Pose and Spatial Alignment} The proposed approach works for cropped portrait images -- these images are always somewhat aligned, with a single dominant face in the center and a frontal or three-quarters vies of a face. This is both due to a preference for this by photographers, but also that the datasets are collected by automatically cropping the images using a facial alignment net such as DLIB or FAN~\cite{bulat2017far}. The use of face and pose detection networks could allow one to filter out incompatible reference-images and thus mitigate issues with spatial alignment. We did not do this filtering in our user study, so errors caused by misalignment were included in our evaluations. It is therefore useful to understand how sensitive the proposed approach is to changes in the spatial alignments of reference images. In order to demonstrate the qualitative effect of our approach to misalignment of the mask, we translated the hair region in Fig.~\ref{fig:Supp_translation} when generating the target mask. \subsection{Manually Editing Masks} The main focus of this paper is on completely automated hair transfer, however it is possible to overcome many of the challenges and limitations of an automatic approach if user edits are allowed. For example, by allowing a very limited set of user interactions (dragging, scaling, and flipping) of the hair region we can achieve results shown in Fig.~\ref{fig:Supp_manual}. \subsection{Comparison to Concurrent Work} Concurrently with our work, StyleMapGan~\cite{kim2021stylemapgan} is also capable of doing face transfer. We compare against prior work on this task in Fig.~7 We illustrate the differences between our results and StyleMapGan qualitatively in Fig.~\ref{fig:compare_with_StylemapGAN}, which demonstrates the results of eyes and eyebrows (top row) and entire faced (bottom row). We observe that our proposed solution is capable of preserving the details of the composited parts. \begin{figure}[thpb] \centering \includegraphics[width=\linewidth]{Figures/Inpaint_mask.pdf} \caption{Mask inpainting. {\color{darkblue} The semantic segmentations of two reference images for \textit{hair} and \textit{other} are shown on the first row. The second row shows (a) a composite mask without inpainting and disoccluded pixels shown in white; (b) the hair region before inpainting, (c) the result of inpainting the hair mask; (d) the result of filling-in disoccluded regions of (a) using the mask from (c). } } \label{fig:inpaint_mask} \end{figure} \begin{figure*}[thpb] \centering \includegraphics[width=\linewidth]{Figures/compare_with_StylemapGAN} \caption{Comparison with StyleMapGAN~\cite{kim2021stylemapgan}. First row: examples of eye and eyebrow transfer; second row: examples of face swapping. Note that ours successfully edits the portrait locally, while StyleMapGAN provides a completely different person.} \label{fig:compare_with_StylemapGAN} \end{figure*} \begin{figure*}[thpb] \centering \includegraphics[width=\linewidth]{Figures/Supp_translation.png} \caption{Misalgin the target segmentation mask by shifting. First row: translate the target hair region without preprocessing the segmentation mask; Second row: use the segmentation mask preprocessing step. Please note the artifacts between the hair and neck.} \label{fig:Supp_translation} \end{figure*} \begin{figure*}[thpb] \centering \includegraphics[width=\linewidth]{Figures/Supp_manual.png} \caption{The second row shows the results of manually editing the target segmentation mask. The left portion of the figure shows an example where the hair and the face could be aligned by flipping the hair segmentation mask. The right portion shows an example in which the regions could be better aligned by translating them} \label{fig:Supp_manual} \end{figure*}
{'timestamp': '2021-10-19T02:14:04', 'yymm': '2106', 'arxiv_id': '2106.01505', 'language': 'en', 'url': 'https://arxiv.org/abs/2106.01505'}
arxiv
\section{Introduction} ACM's consolidated article template, introduced in 2017, provides a consistent \LaTeX\ style for use across ACM publications, and incorporates accessibility and metadata-extraction functionality necessary for future Digital Library endeavors. Numerous ACM and SIG-specific \LaTeX\ templates have been examined, and their unique features incorporated into this single new template. If you are new to publishing with ACM, this document is a valuable guide to the process of preparing your work for publication. If you have published with ACM before, this document provides insight and instruction into more recent changes to the article template. The ``\verb|acmart|'' document class can be used to prepare articles for any ACM publication --- conference or journal, and for any stage of publication, from review to final ``camera-ready'' copy, to the author's own version, with {\itshape very} few changes to the source. \section{Template Overview} As noted in the introduction, the ``\verb|acmart|'' document class can be used to prepare many different kinds of documentation --- a double-blind initial submission of a full-length technical paper, a two-page SIGGRAPH Emerging Technologies abstract, a ``camera-ready'' journal article, a SIGCHI Extended Abstract, and more --- all by selecting the appropriate {\itshape template style} and {\itshape template parameters}. This document will explain the major features of the document class. For further information, the {\itshape \LaTeX\ User's Guide} is available from \url{https://www.acm.org/publications/proceedings-template}. \subsection{Template Styles} The primary parameter given to the ``\verb|acmart|'' document class is the {\itshape template style} which corresponds to the kind of publication or SIG publishing the work. This parameter is enclosed in square brackets and is a part of the {\verb|documentclass|} command: \begin{verbatim} \documentclass[STYLE]{acmart} \end{verbatim} Journals use one of three template styles. All but three ACM journals use the {\verb|acmsmall|} template style: \begin{itemize} \item {\verb|acmsmall|}: The default journal template style. \item {\verb|acmlarge|}: Used by JOCCH and TAP. \item {\verb|acmtog|}: Used by TOG. \end{itemize} The majority of conference proceedings documentation will use the {\verb|acmconf|} template style. \begin{itemize} \item {\verb|acmconf|}: The default proceedings template style. \item{\verb|sigchi|}: Used for SIGCHI conference articles. \item{\verb|sigchi-a|}: Used for SIGCHI ``Extended Abstract'' articles. \item{\verb|sigplan|}: Used for SIGPLAN conference articles. \end{itemize} \subsection{Template Parameters} In addition to specifying the {\itshape template style} to be used in formatting your work, there are a number of {\itshape template parameters} which modify some part of the applied template style. A complete list of these parameters can be found in the {\itshape \LaTeX\ User's Guide.} Frequently-used parameters, or combinations of parameters, include: \begin{itemize} \item {\verb|anonymous,review|}: Suitable for a ``double-blind'' conference submission. Anonymizes the work and includes line numbers. Use with the \verb|\acmSubmissionID| command to print the submission's unique ID on each page of the work. \item{\verb|authorversion|}: Produces a version of the work suitable for posting by the author. \item{\verb|screen|}: Produces colored hyperlinks. \end{itemize} This document uses the following string as the first command in the source file: \begin{verbatim} \documentclass[sigconf]{acmart} \end{verbatim} \section{Modifications} Modifying the template --- including but not limited to: adjusting margins, typeface sizes, line spacing, paragraph and list definitions, and the use of the \verb|\vspace| command to manually adjust the vertical spacing between elements of your work --- is not allowed. {\bfseries Your document will be returned to you for revision if modifications are discovered.} \section{Typefaces} The ``\verb|acmart|'' document class requires the use of the ``Libertine'' typeface family. Your \TeX\ installation should include this set of packages. Please do not substitute other typefaces. The ``\verb|lmodern|'' and ``\verb|ltimes|'' packages should not be used, as they will override the built-in typeface families. \section{Title Information} The title of your work should use capital letters appropriately - \url{https://capitalizemytitle.com/} has useful rules for capitalization. Use the {\verb|title|} command to define the title of your work. If your work has a subtitle, define it with the {\verb|subtitle|} command. Do not insert line breaks in your title. If your title is lengthy, you must define a short version to be used in the page headers, to prevent overlapping text. The \verb|title| command has a ``short title'' parameter: \begin{verbatim} \title[short title]{full title} \end{verbatim} \section{Authors and Affiliations} Each author must be defined separately for accurate metadata identification. Multiple authors may share one affiliation. Authors' names should not be abbreviated; use full first names wherever possible. Include authors' e-mail addresses whenever possible. Grouping authors' names or e-mail addresses, or providing an ``e-mail alias,'' as shown below, is not acceptable: \begin{verbatim} \author{Brooke Aster, David Mehldau} \email{dave,judy,[email protected]} \email{[email protected]} \end{verbatim} The \verb|authornote| and \verb|authornotemark| commands allow a note to apply to multiple authors --- for example, if the first two authors of an article contributed equally to the work. If your author list is lengthy, you must define a shortened version of the list of authors to be used in the page headers, to prevent overlapping text. The following command should be placed just after the last \verb|\author{}| definition: \begin{verbatim} \renewcommand{\shortauthors}{McCartney, et al.} \end{verbatim} Omitting this command will force the use of a concatenated list of all of the authors' names, which may result in overlapping text in the page headers. The article template's documentation, available at \url{https://www.acm.org/publications/proceedings-template}, has a complete explanation of these commands and tips for their effective use. Note that authors' addresses are mandatory for journal articles. \section{Rights Information} Authors of any work published by ACM will need to complete a rights form. Depending on the kind of work, and the rights management choice made by the author, this may be copyright transfer, permission, license, or an OA (open access) agreement. Regardless of the rights management choice, the author will receive a copy of the completed rights form once it has been submitted. This form contains \LaTeX\ commands that must be copied into the source document. When the document source is compiled, these commands and their parameters add formatted text to several areas of the final document: \begin{itemize} \item the ``ACM Reference Format'' text on the first page. \item the ``rights management'' text on the first page. \item the conference information in the page header(s). \end{itemize} Rights information is unique to the work; if you are preparing several works for an event, make sure to use the correct set of commands with each of the works. The ACM Reference Format text is required for all articles over one page in length, and is optional for one-page articles (abstracts). \section{CCS Concepts and User-Defined Keywords} Two elements of the ``acmart'' document class provide powerful taxonomic tools for you to help readers find your work in an online search. The ACM Computing Classification System --- \url{https://www.acm.org/publications/class-2012} --- is a set of classifiers and concepts that describe the computing discipline. Authors can select entries from this classification system, via \url{https://dl.acm.org/ccs/ccs.cfm}, and generate the commands to be included in the \LaTeX\ source. User-defined keywords are a comma-separated list of words and phrases of the authors' choosing, providing a more flexible way of describing the research being presented. CCS concepts and user-defined keywords are required for for all articles over two pages in length, and are optional for one- and two-page articles (or abstracts). \section{Sectioning Commands} Your work should use standard \LaTeX\ sectioning commands: \verb|section|, \verb|subsection|, \verb|subsubsection|, and \verb|paragraph|. They should be numbered; do not remove the numbering from the commands. Simulating a sectioning command by setting the first word or words of a paragraph in boldface or italicized text is {\bfseries not allowed.} \section{Tables} The ``\verb|acmart|'' document class includes the ``\verb|booktabs|'' package --- \url{https://ctan.org/pkg/booktabs} --- for preparing high-quality tables. Table captions are placed {\itshape above} the table. Because tables cannot be split across pages, the best placement for them is typically the top of the page nearest their initial cite. To ensure this proper ``floating'' placement of tables, use the environment \textbf{table} to enclose the table's contents and the table caption. The contents of the table itself must go in the \textbf{tabular} environment, to be aligned properly in rows and columns, with the desired horizontal and vertical rules. Again, detailed instructions on \textbf{tabular} material are found in the \textit{\LaTeX\ User's Guide}. Immediately following this sentence is the point at which Table~\ref{tab:freq} is included in the input file; compare the placement of the table here with the table in the printed output of this document. \begin{table} \caption{Frequency of Special Characters} \label{tab:freq} \begin{tabular}{ccl} \toprule Non-English or Math&Frequency&Comments\\ \midrule \O & 1 in 1,000& For Swedish names\\ $\pi$ & 1 in 5& Common in math\\ \$ & 4 in 5 & Used in business\\ $\Psi^2_1$ & 1 in 40,000& Unexplained usage\\ \bottomrule \end{tabular} \end{table} To set a wider table, which takes up the whole width of the page's live area, use the environment \textbf{table*} to enclose the table's contents and the table caption. As with a single-column table, this wide table will ``float'' to a location deemed more desirable. Immediately following this sentence is the point at which Table~\ref{tab:commands} is included in the input file; again, it is instructive to compare the placement of the table here with the table in the printed output of this document. \begin{table*} \caption{Some Typical Commands} \label{tab:commands} \begin{tabular}{ccl} \toprule Command &A Number & Comments\\ \midrule \texttt{{\char'134}author} & 100& Author \\ \texttt{{\char'134}table}& 300 & For tables\\ \texttt{{\char'134}table*}& 400& For wider tables\\ \bottomrule \end{tabular} \end{table*} Always use midrule to separate table header rows from data rows, and use it only for this purpose. This enables assistive technologies to recognise table headers and support their users in navigating tables more easily. \section{Math Equations} You may want to display math equations in three distinct styles: inline, numbered or non-numbered display. Each of the three are discussed in the next sections. \subsection{Inline (In-text) Equations} A formula that appears in the running text is called an inline or in-text formula. It is produced by the \textbf{math} environment, which can be invoked with the usual \texttt{{\char'134}begin\,\ldots{\char'134}end} construction or with the short form \texttt{\$\,\ldots\$}. You can use any of the symbols and structures, from $\alpha$ to $\omega$, available in \LaTeX~\cite{Lamport:LaTeX}; this section will simply show a few examples of in-text equations in context. Notice how this equation: \begin{math} \lim_{n\rightarrow \infty}x=0 \end{math}, set here in in-line math style, looks slightly different when set in display style. (See next section). \subsection{Display Equations} A numbered display equation---one set off by vertical space from the text and centered horizontally---is produced by the \textbf{equation} environment. An unnumbered display equation is produced by the \textbf{displaymath} environment. Again, in either environment, you can use any of the symbols and structures available in \LaTeX\@; this section will just give a couple of examples of display equations in context. First, consider the equation, shown as an inline equation above: \begin{equation} \lim_{n\rightarrow \infty}x=0 \end{equation} Notice how it is formatted somewhat differently in the \textbf{displaymath} environment. Now, we'll enter an unnumbered equation: \begin{displaymath} \sum_{i=0}^{\infty} x + 1 \end{displaymath} and follow it with another numbered equation: \begin{equation} \sum_{i=0}^{\infty}x_i=\int_{0}^{\pi+2} f \end{equation} just to demonstrate \LaTeX's able handling of numbering. \section{Figures} The ``\verb|figure|'' environment should be used for figures. One or more images can be placed within a figure. If your figure contains third-party material, you must clearly identify it as such, as shown in the example below. \begin{figure}[h] \centering \includegraphics[width=\linewidth]{sample-franklin} \caption{1907 Franklin Model D roadster. Photograph by Harris \& Ewing, Inc. [Public domain], via Wikimedia Commons. (\url{https://goo.gl/VLCRBB}).} \Description{A woman and a girl in white dresses sit in an open car.} \end{figure} Your figures should contain a caption which describes the figure to the reader. Figure captions are placed {\itshape below} the figure. Every figure should also have a figure description unless it is purely decorative. These descriptions convey what’s in the image to someone who cannot see it. They are also used by search engine crawlers for indexing images, and when images cannot be loaded. A figure description must be unformatted plain text less than 2000 characters long (including spaces). {\bfseries Figure descriptions should not repeat the figure caption – their purpose is to capture important information that is not already provided in the caption or the main text of the paper.} For figures that convey important and complex new information, a short text description may not be adequate. More complex alternative descriptions can be placed in an appendix and referenced in a short figure description. For example, provide a data table capturing the information in a bar chart, or a structured list representing a graph. For additional information regarding how best to write figure descriptions and why doing this is so important, please see \url{https://www.acm.org/publications/taps/describing-figures/}. \subsection{The ``Teaser Figure''} A ``teaser figure'' is an image, or set of images in one figure, that are placed after all author and affiliation information, and before the body of the article, spanning the page. If you wish to have such a figure in your article, place the command immediately before the \verb|\maketitle| command: \begin{verbatim} \begin{teaserfigure} \includegraphics[width=\textwidth]{sampleteaser} \caption{figure caption} \Description{figure description} \end{teaserfigure} \end{verbatim} \section{Citations and Bibliographies} The use of \BibTeX\ for the preparation and formatting of one's references is strongly recommended. Authors' names should be complete --- use full first names (``Donald E. Knuth'') not initials (``D. E. Knuth'') --- and the salient identifying features of a reference should be included: title, year, volume, number, pages, article DOI, etc. The bibliography is included in your source document with these two commands, placed just before the \verb|\end{document}| command: \begin{verbatim} \bibliographystyle{ACM-Reference-Format} \section{Introduction} ACM's consolidated article template, introduced in 2017, provides a consistent \LaTeX\ style for use across ACM publications, and incorporates accessibility and metadata-extraction functionality necessary for future Digital Library endeavors. Numerous ACM and SIG-specific \LaTeX\ templates have been examined, and their unique features incorporated into this single new template. If you are new to publishing with ACM, this document is a valuable guide to the process of preparing your work for publication. If you have published with ACM before, this document provides insight and instruction into more recent changes to the article template. The ``\verb|acmart|'' document class can be used to prepare articles for any ACM publication --- conference or journal, and for any stage of publication, from review to final ``camera-ready'' copy, to the author's own version, with {\itshape very} few changes to the source. \section{Template Overview} As noted in the introduction, the ``\verb|acmart|'' document class can be used to prepare many different kinds of documentation --- a double-blind initial submission of a full-length technical paper, a two-page SIGGRAPH Emerging Technologies abstract, a ``camera-ready'' journal article, a SIGCHI Extended Abstract, and more --- all by selecting the appropriate {\itshape template style} and {\itshape template parameters}. This document will explain the major features of the document class. For further information, the {\itshape \LaTeX\ User's Guide} is available from \url{https://www.acm.org/publications/proceedings-template}. \subsection{Template Styles} The primary parameter given to the ``\verb|acmart|'' document class is the {\itshape template style} which corresponds to the kind of publication or SIG publishing the work. This parameter is enclosed in square brackets and is a part of the {\verb|documentclass|} command: \begin{verbatim} \documentclass[STYLE]{acmart} \end{verbatim} Journals use one of three template styles. All but three ACM journals use the {\verb|acmsmall|} template style: \begin{itemize} \item {\verb|acmsmall|}: The default journal template style. \item {\verb|acmlarge|}: Used by JOCCH and TAP. \item {\verb|acmtog|}: Used by TOG. \end{itemize} The majority of conference proceedings documentation will use the {\verb|acmconf|} template style. \begin{itemize} \item {\verb|acmconf|}: The default proceedings template style. \item{\verb|sigchi|}: Used for SIGCHI conference articles. \item{\verb|sigchi-a|}: Used for SIGCHI ``Extended Abstract'' articles. \item{\verb|sigplan|}: Used for SIGPLAN conference articles. \end{itemize} \subsection{Template Parameters} In addition to specifying the {\itshape template style} to be used in formatting your work, there are a number of {\itshape template parameters} which modify some part of the applied template style. A complete list of these parameters can be found in the {\itshape \LaTeX\ User's Guide.} Frequently-used parameters, or combinations of parameters, include: \begin{itemize} \item {\verb|anonymous,review|}: Suitable for a ``double-blind'' conference submission. Anonymizes the work and includes line numbers. Use with the \verb|\acmSubmissionID| command to print the submission's unique ID on each page of the work. \item{\verb|authorversion|}: Produces a version of the work suitable for posting by the author. \item{\verb|screen|}: Produces colored hyperlinks. \end{itemize} This document uses the following string as the first command in the source file: \begin{verbatim} \documentclass[acmsmall]{acmart} \end{verbatim} \section{Modifications} Modifying the template --- including but not limited to: adjusting margins, typeface sizes, line spacing, paragraph and list definitions, and the use of the \verb|\vspace| command to manually adjust the vertical spacing between elements of your work --- is not allowed. {\bfseries Your document will be returned to you for revision if modifications are discovered.} \section{Typefaces} The ``\verb|acmart|'' document class requires the use of the ``Libertine'' typeface family. Your \TeX\ installation should include this set of packages. Please do not substitute other typefaces. The ``\verb|lmodern|'' and ``\verb|ltimes|'' packages should not be used, as they will override the built-in typeface families. \section{Title Information} The title of your work should use capital letters appropriately - \url{https://capitalizemytitle.com/} has useful rules for capitalization. Use the {\verb|title|} command to define the title of your work. If your work has a subtitle, define it with the {\verb|subtitle|} command. Do not insert line breaks in your title. If your title is lengthy, you must define a short version to be used in the page headers, to prevent overlapping text. The \verb|title| command has a ``short title'' parameter: \begin{verbatim} \title[short title]{full title} \end{verbatim} \section{Authors and Affiliations} Each author must be defined separately for accurate metadata identification. Multiple authors may share one affiliation. Authors' names should not be abbreviated; use full first names wherever possible. Include authors' e-mail addresses whenever possible. Grouping authors' names or e-mail addresses, or providing an ``e-mail alias,'' as shown below, is not acceptable: \begin{verbatim} \author{Brooke Aster, David Mehldau} \email{dave,judy,[email protected]} \email{[email protected]} \end{verbatim} The \verb|authornote| and \verb|authornotemark| commands allow a note to apply to multiple authors --- for example, if the first two authors of an article contributed equally to the work. If your author list is lengthy, you must define a shortened version of the list of authors to be used in the page headers, to prevent overlapping text. The following command should be placed just after the last \verb|\author{}| definition: \begin{verbatim} \renewcommand{\shortauthors}{McCartney, et al.} \end{verbatim} Omitting this command will force the use of a concatenated list of all of the authors' names, which may result in overlapping text in the page headers. The article template's documentation, available at \url{https://www.acm.org/publications/proceedings-template}, has a complete explanation of these commands and tips for their effective use. Note that authors' addresses are mandatory for journal articles. \section{Rights Information} Authors of any work published by ACM will need to complete a rights form. Depending on the kind of work, and the rights management choice made by the author, this may be copyright transfer, permission, license, or an OA (open access) agreement. Regardless of the rights management choice, the author will receive a copy of the completed rights form once it has been submitted. This form contains \LaTeX\ commands that must be copied into the source document. When the document source is compiled, these commands and their parameters add formatted text to several areas of the final document: \begin{itemize} \item the ``ACM Reference Format'' text on the first page. \item the ``rights management'' text on the first page. \item the conference information in the page header(s). \end{itemize} Rights information is unique to the work; if you are preparing several works for an event, make sure to use the correct set of commands with each of the works. The ACM Reference Format text is required for all articles over one page in length, and is optional for one-page articles (abstracts). \section{CCS Concepts and User-Defined Keywords} Two elements of the ``acmart'' document class provide powerful taxonomic tools for you to help readers find your work in an online search. The ACM Computing Classification System --- \url{https://www.acm.org/publications/class-2012} --- is a set of classifiers and concepts that describe the computing discipline. Authors can select entries from this classification system, via \url{https://dl.acm.org/ccs/ccs.cfm}, and generate the commands to be included in the \LaTeX\ source. User-defined keywords are a comma-separated list of words and phrases of the authors' choosing, providing a more flexible way of describing the research being presented. CCS concepts and user-defined keywords are required for for all articles over two pages in length, and are optional for one- and two-page articles (or abstracts). \section{Sectioning Commands} Your work should use standard \LaTeX\ sectioning commands: \verb|section|, \verb|subsection|, \verb|subsubsection|, and \verb|paragraph|. They should be numbered; do not remove the numbering from the commands. Simulating a sectioning command by setting the first word or words of a paragraph in boldface or italicized text is {\bfseries not allowed.} \section{Tables} The ``\verb|acmart|'' document class includes the ``\verb|booktabs|'' package --- \url{https://ctan.org/pkg/booktabs} --- for preparing high-quality tables. Table captions are placed {\itshape above} the table. Because tables cannot be split across pages, the best placement for them is typically the top of the page nearest their initial cite. To ensure this proper ``floating'' placement of tables, use the environment \textbf{table} to enclose the table's contents and the table caption. The contents of the table itself must go in the \textbf{tabular} environment, to be aligned properly in rows and columns, with the desired horizontal and vertical rules. Again, detailed instructions on \textbf{tabular} material are found in the \textit{\LaTeX\ User's Guide}. Immediately following this sentence is the point at which Table~\ref{tab:freq} is included in the input file; compare the placement of the table here with the table in the printed output of this document. \begin{table} \caption{Frequency of Special Characters} \label{tab:freq} \begin{tabular}{ccl} \toprule Non-English or Math&Frequency&Comments\\ \midrule \O & 1 in 1,000& For Swedish names\\ $\pi$ & 1 in 5& Common in math\\ \$ & 4 in 5 & Used in business\\ $\Psi^2_1$ & 1 in 40,000& Unexplained usage\\ \bottomrule \end{tabular} \end{table} To set a wider table, which takes up the whole width of the page's live area, use the environment \textbf{table*} to enclose the table's contents and the table caption. As with a single-column table, this wide table will ``float'' to a location deemed more desirable. Immediately following this sentence is the point at which Table~\ref{tab:commands} is included in the input file; again, it is instructive to compare the placement of the table here with the table in the printed output of this document. \begin{table*} \caption{Some Typical Commands} \label{tab:commands} \begin{tabular}{ccl} \toprule Command &A Number & Comments\\ \midrule \texttt{{\char'134}author} & 100& Author \\ \texttt{{\char'134}table}& 300 & For tables\\ \texttt{{\char'134}table*}& 400& For wider tables\\ \bottomrule \end{tabular} \end{table*} Always use midrule to separate table header rows from data rows, and use it only for this purpose. This enables assistive technologies to recognise table headers and support their users in navigating tables more easily. \section{Math Equations} You may want to display math equations in three distinct styles: inline, numbered or non-numbered display. Each of the three are discussed in the next sections. \subsection{Inline (In-text) Equations} A formula that appears in the running text is called an inline or in-text formula. It is produced by the \textbf{math} environment, which can be invoked with the usual \texttt{{\char'134}begin\,\ldots{\char'134}end} construction or with the short form \texttt{\$\,\ldots\$}. You can use any of the symbols and structures, from $\alpha$ to $\omega$, available in \LaTeX~\cite{Lamport:LaTeX}; this section will simply show a few examples of in-text equations in context. Notice how this equation: \begin{math} \lim_{n\rightarrow \infty}x=0 \end{math}, set here in in-line math style, looks slightly different when set in display style. (See next section). \subsection{Display Equations} A numbered display equation---one set off by vertical space from the text and centered horizontally---is produced by the \textbf{equation} environment. An unnumbered display equation is produced by the \textbf{displaymath} environment. Again, in either environment, you can use any of the symbols and structures available in \LaTeX\@; this section will just give a couple of examples of display equations in context. First, consider the equation, shown as an inline equation above: \begin{equation} \lim_{n\rightarrow \infty}x=0 \end{equation} Notice how it is formatted somewhat differently in the \textbf{displaymath} environment. Now, we'll enter an unnumbered equation: \begin{displaymath} \sum_{i=0}^{\infty} x + 1 \end{displaymath} and follow it with another numbered equation: \begin{equation} \sum_{i=0}^{\infty}x_i=\int_{0}^{\pi+2} f \end{equation} just to demonstrate \LaTeX's able handling of numbering. \section{Figures} The ``\verb|figure|'' environment should be used for figures. One or more images can be placed within a figure. If your figure contains third-party material, you must clearly identify it as such, as shown in the example below. \begin{figure}[h] \centering \includegraphics[width=\linewidth]{sample-franklin} \caption{1907 Franklin Model D roadster. Photograph by Harris \& Ewing, Inc. [Public domain], via Wikimedia Commons. (\url{https://goo.gl/VLCRBB}).} \Description{A woman and a girl in white dresses sit in an open car.} \end{figure} Your figures should contain a caption which describes the figure to the reader. Figure captions are placed {\itshape below} the figure. Every figure should also have a figure description unless it is purely decorative. These descriptions convey what’s in the image to someone who cannot see it. They are also used by search engine crawlers for indexing images, and when images cannot be loaded. A figure description must be unformatted plain text less than 2000 characters long (including spaces). {\bfseries Figure descriptions should not repeat the figure caption – their purpose is to capture important information that is not already provided in the caption or the main text of the paper.} For figures that convey important and complex new information, a short text description may not be adequate. More complex alternative descriptions can be placed in an appendix and referenced in a short figure description. For example, provide a data table capturing the information in a bar chart, or a structured list representing a graph. For additional information regarding how best to write figure descriptions and why doing this is so important, please see \url{https://www.acm.org/publications/taps/describing-figures/}. \subsection{The ``Teaser Figure''} A ``teaser figure'' is an image, or set of images in one figure, that are placed after all author and affiliation information, and before the body of the article, spanning the page. If you wish to have such a figure in your article, place the command immediately before the \verb|\maketitle| command: \begin{verbatim} \begin{teaserfigure} \includegraphics[width=\textwidth]{sampleteaser} \caption{figure caption} \Description{figure description} \end{teaserfigure} \end{verbatim} \section{Citations and Bibliographies} The use of \BibTeX\ for the preparation and formatting of one's references is strongly recommended. Authors' names should be complete --- use full first names (``Donald E. Knuth'') not initials (``D. E. Knuth'') --- and the salient identifying features of a reference should be included: title, year, volume, number, pages, article DOI, etc. The bibliography is included in your source document with these two commands, placed just before the \verb|\end{document}| command: \begin{verbatim} \bibliographystyle{ACM-Reference-Format} \section{Introduction} ACM's consolidated article template, introduced in 2017, provides a consistent \LaTeX\ style for use across ACM publications, and incorporates accessibility and metadata-extraction functionality necessary for future Digital Library endeavors. Numerous ACM and SIG-specific \LaTeX\ templates have been examined, and their unique features incorporated into this single new template. If you are new to publishing with ACM, this document is a valuable guide to the process of preparing your work for publication. If you have published with ACM before, this document provides insight and instruction into more recent changes to the article template. The ``\verb|acmart|'' document class can be used to prepare articles for any ACM publication --- conference or journal, and for any stage of publication, from review to final ``camera-ready'' copy, to the author's own version, with {\itshape very} few changes to the source. \section{Template Overview} As noted in the introduction, the ``\verb|acmart|'' document class can be used to prepare many different kinds of documentation --- a double-blind initial submission of a full-length technical paper, a two-page SIGGRAPH Emerging Technologies abstract, a ``camera-ready'' journal article, a SIGCHI Extended Abstract, and more --- all by selecting the appropriate {\itshape template style} and {\itshape template parameters}. This document will explain the major features of the document class. For further information, the {\itshape \LaTeX\ User's Guide} is available from \url{https://www.acm.org/publications/proceedings-template}. \subsection{Template Styles} The primary parameter given to the ``\verb|acmart|'' document class is the {\itshape template style} which corresponds to the kind of publication or SIG publishing the work. This parameter is enclosed in square brackets and is a part of the {\verb|documentclass|} command: \begin{verbatim} \documentclass[STYLE]{acmart} \end{verbatim} Journals use one of three template styles. All but three ACM journals use the {\verb|acmsmall|} template style: \begin{itemize} \item {\verb|acmsmall|}: The default journal template style. \item {\verb|acmlarge|}: Used by JOCCH and TAP. \item {\verb|acmtog|}: Used by TOG. \end{itemize} The majority of conference proceedings documentation will use the {\verb|acmconf|} template style. \begin{itemize} \item {\verb|acmconf|}: The default proceedings template style. \item{\verb|sigchi|}: Used for SIGCHI conference articles. \item{\verb|sigchi-a|}: Used for SIGCHI ``Extended Abstract'' articles. \item{\verb|sigplan|}: Used for SIGPLAN conference articles. \end{itemize} \subsection{Template Parameters} In addition to specifying the {\itshape template style} to be used in formatting your work, there are a number of {\itshape template parameters} which modify some part of the applied template style. A complete list of these parameters can be found in the {\itshape \LaTeX\ User's Guide.} Frequently-used parameters, or combinations of parameters, include: \begin{itemize} \item {\verb|anonymous,review|}: Suitable for a ``double-blind'' conference submission. Anonymizes the work and includes line numbers. Use with the \verb|\acmSubmissionID| command to print the submission's unique ID on each page of the work. \item{\verb|authorversion|}: Produces a version of the work suitable for posting by the author. \item{\verb|screen|}: Produces colored hyperlinks. \end{itemize} This document uses the following string as the first command in the source file: \begin{verbatim} \documentclass[sigconf,authordraft]{acmart} \end{verbatim} \section{Modifications} Modifying the template --- including but not limited to: adjusting margins, typeface sizes, line spacing, paragraph and list definitions, and the use of the \verb|\vspace| command to manually adjust the vertical spacing between elements of your work --- is not allowed. {\bfseries Your document will be returned to you for revision if modifications are discovered.} \section{Typefaces} The ``\verb|acmart|'' document class requires the use of the ``Libertine'' typeface family. Your \TeX\ installation should include this set of packages. Please do not substitute other typefaces. The ``\verb|lmodern|'' and ``\verb|ltimes|'' packages should not be used, as they will override the built-in typeface families. \section{Title Information} The title of your work should use capital letters appropriately - \url{https://capitalizemytitle.com/} has useful rules for capitalization. Use the {\verb|title|} command to define the title of your work. If your work has a subtitle, define it with the {\verb|subtitle|} command. Do not insert line breaks in your title. If your title is lengthy, you must define a short version to be used in the page headers, to prevent overlapping text. The \verb|title| command has a ``short title'' parameter: \begin{verbatim} \title[short title]{full title} \end{verbatim} \section{Authors and Affiliations} Each author must be defined separately for accurate metadata identification. Multiple authors may share one affiliation. Authors' names should not be abbreviated; use full first names wherever possible. Include authors' e-mail addresses whenever possible. Grouping authors' names or e-mail addresses, or providing an ``e-mail alias,'' as shown below, is not acceptable: \begin{verbatim} \author{Brooke Aster, David Mehldau} \email{dave,judy,[email protected]} \email{[email protected]} \end{verbatim} The \verb|authornote| and \verb|authornotemark| commands allow a note to apply to multiple authors --- for example, if the first two authors of an article contributed equally to the work. If your author list is lengthy, you must define a shortened version of the list of authors to be used in the page headers, to prevent overlapping text. The following command should be placed just after the last \verb|\author{}| definition: \begin{verbatim} \renewcommand{\shortauthors}{McCartney, et al.} \end{verbatim} Omitting this command will force the use of a concatenated list of all of the authors' names, which may result in overlapping text in the page headers. The article template's documentation, available at \url{https://www.acm.org/publications/proceedings-template}, has a complete explanation of these commands and tips for their effective use. Note that authors' addresses are mandatory for journal articles. \section{Rights Information} Authors of any work published by ACM will need to complete a rights form. Depending on the kind of work, and the rights management choice made by the author, this may be copyright transfer, permission, license, or an OA (open access) agreement. Regardless of the rights management choice, the author will receive a copy of the completed rights form once it has been submitted. This form contains \LaTeX\ commands that must be copied into the source document. When the document source is compiled, these commands and their parameters add formatted text to several areas of the final document: \begin{itemize} \item the ``ACM Reference Format'' text on the first page. \item the ``rights management'' text on the first page. \item the conference information in the page header(s). \end{itemize} Rights information is unique to the work; if you are preparing several works for an event, make sure to use the correct set of commands with each of the works. The ACM Reference Format text is required for all articles over one page in length, and is optional for one-page articles (abstracts). \section{CCS Concepts and User-Defined Keywords} Two elements of the ``acmart'' document class provide powerful taxonomic tools for you to help readers find your work in an online search. The ACM Computing Classification System --- \url{https://www.acm.org/publications/class-2012} --- is a set of classifiers and concepts that describe the computing discipline. Authors can select entries from this classification system, via \url{https://dl.acm.org/ccs/ccs.cfm}, and generate the commands to be included in the \LaTeX\ source. User-defined keywords are a comma-separated list of words and phrases of the authors' choosing, providing a more flexible way of describing the research being presented. CCS concepts and user-defined keywords are required for for all articles over two pages in length, and are optional for one- and two-page articles (or abstracts). \section{Sectioning Commands} Your work should use standard \LaTeX\ sectioning commands: \verb|section|, \verb|subsection|, \verb|subsubsection|, and \verb|paragraph|. They should be numbered; do not remove the numbering from the commands. Simulating a sectioning command by setting the first word or words of a paragraph in boldface or italicized text is {\bfseries not allowed.} \section{Tables} The ``\verb|acmart|'' document class includes the ``\verb|booktabs|'' package --- \url{https://ctan.org/pkg/booktabs} --- for preparing high-quality tables. Table captions are placed {\itshape above} the table. Because tables cannot be split across pages, the best placement for them is typically the top of the page nearest their initial cite. To ensure this proper ``floating'' placement of tables, use the environment \textbf{table} to enclose the table's contents and the table caption. The contents of the table itself must go in the \textbf{tabular} environment, to be aligned properly in rows and columns, with the desired horizontal and vertical rules. Again, detailed instructions on \textbf{tabular} material are found in the \textit{\LaTeX\ User's Guide}. Immediately following this sentence is the point at which Table~\ref{tab:freq} is included in the input file; compare the placement of the table here with the table in the printed output of this document. \begin{table} \caption{Frequency of Special Characters} \label{tab:freq} \begin{tabular}{ccl} \toprule Non-English or Math&Frequency&Comments\\ \midrule \O & 1 in 1,000& For Swedish names\\ $\pi$ & 1 in 5& Common in math\\ \$ & 4 in 5 & Used in business\\ $\Psi^2_1$ & 1 in 40,000& Unexplained usage\\ \bottomrule \end{tabular} \end{table} To set a wider table, which takes up the whole width of the page's live area, use the environment \textbf{table*} to enclose the table's contents and the table caption. As with a single-column table, this wide table will ``float'' to a location deemed more desirable. Immediately following this sentence is the point at which Table~\ref{tab:commands} is included in the input file; again, it is instructive to compare the placement of the table here with the table in the printed output of this document. \begin{table*} \caption{Some Typical Commands} \label{tab:commands} \begin{tabular}{ccl} \toprule Command &A Number & Comments\\ \midrule \texttt{{\char'134}author} & 100& Author \\ \texttt{{\char'134}table}& 300 & For tables\\ \texttt{{\char'134}table*}& 400& For wider tables\\ \bottomrule \end{tabular} \end{table*} Always use midrule to separate table header rows from data rows, and use it only for this purpose. This enables assistive technologies to recognise table headers and support their users in navigating tables more easily. \section{Math Equations} You may want to display math equations in three distinct styles: inline, numbered or non-numbered display. Each of the three are discussed in the next sections. \subsection{Inline (In-text) Equations} A formula that appears in the running text is called an inline or in-text formula. It is produced by the \textbf{math} environment, which can be invoked with the usual \texttt{{\char'134}begin\,\ldots{\char'134}end} construction or with the short form \texttt{\$\,\ldots\$}. You can use any of the symbols and structures, from $\alpha$ to $\omega$, available in \LaTeX~\cite{Lamport:LaTeX}; this section will simply show a few examples of in-text equations in context. Notice how this equation: \begin{math} \lim_{n\rightarrow \infty}x=0 \end{math}, set here in in-line math style, looks slightly different when set in display style. (See next section). \subsection{Display Equations} A numbered display equation---one set off by vertical space from the text and centered horizontally---is produced by the \textbf{equation} environment. An unnumbered display equation is produced by the \textbf{displaymath} environment. Again, in either environment, you can use any of the symbols and structures available in \LaTeX\@; this section will just give a couple of examples of display equations in context. First, consider the equation, shown as an inline equation above: \begin{equation} \lim_{n\rightarrow \infty}x=0 \end{equation} Notice how it is formatted somewhat differently in the \textbf{displaymath} environment. Now, we'll enter an unnumbered equation: \begin{displaymath} \sum_{i=0}^{\infty} x + 1 \end{displaymath} and follow it with another numbered equation: \begin{equation} \sum_{i=0}^{\infty}x_i=\int_{0}^{\pi+2} f \end{equation} just to demonstrate \LaTeX's able handling of numbering. \section{Figures} The ``\verb|figure|'' environment should be used for figures. One or more images can be placed within a figure. If your figure contains third-party material, you must clearly identify it as such, as shown in the example below. \begin{figure}[h] \centering \includegraphics[width=\linewidth]{sample-franklin} \caption{1907 Franklin Model D roadster. Photograph by Harris \& Ewing, Inc. [Public domain], via Wikimedia Commons. (\url{https://goo.gl/VLCRBB}).} \Description{A woman and a girl in white dresses sit in an open car.} \end{figure} Your figures should contain a caption which describes the figure to the reader. Figure captions are placed {\itshape below} the figure. Every figure should also have a figure description unless it is purely decorative. These descriptions convey what’s in the image to someone who cannot see it. They are also used by search engine crawlers for indexing images, and when images cannot be loaded. A figure description must be unformatted plain text less than 2000 characters long (including spaces). {\bfseries Figure descriptions should not repeat the figure caption – their purpose is to capture important information that is not already provided in the caption or the main text of the paper.} For figures that convey important and complex new information, a short text description may not be adequate. More complex alternative descriptions can be placed in an appendix and referenced in a short figure description. For example, provide a data table capturing the information in a bar chart, or a structured list representing a graph. For additional information regarding how best to write figure descriptions and why doing this is so important, please see \url{https://www.acm.org/publications/taps/describing-figures/}. \subsection{The ``Teaser Figure''} A ``teaser figure'' is an image, or set of images in one figure, that are placed after all author and affiliation information, and before the body of the article, spanning the page. If you wish to have such a figure in your article, place the command immediately before the \verb|\maketitle| command: \begin{verbatim} \begin{teaserfigure} \includegraphics[width=\textwidth]{sampleteaser} \caption{figure caption} \Description{figure description} \end{teaserfigure} \end{verbatim} \section{Citations and Bibliographies} The use of \BibTeX\ for the preparation and formatting of one's references is strongly recommended. Authors' names should be complete --- use full first names (``Donald E. Knuth'') not initials (``D. E. Knuth'') --- and the salient identifying features of a reference should be included: title, year, volume, number, pages, article DOI, etc. The bibliography is included in your source document with these two commands, placed just before the \verb|\end{document}| command: \begin{verbatim} \bibliographystyle{ACM-Reference-Format} \section{Introduction} ACM's consolidated article template, introduced in 2017, provides a consistent \LaTeX\ style for use across ACM publications, and incorporates accessibility and metadata-extraction functionality necessary for future Digital Library endeavors. Numerous ACM and SIG-specific \LaTeX\ templates have been examined, and their unique features incorporated into this single new template. If you are new to publishing with ACM, this document is a valuable guide to the process of preparing your work for publication. If you have published with ACM before, this document provides insight and instruction into more recent changes to the article template. The ``\verb|acmart|'' document class can be used to prepare articles for any ACM publication --- conference or journal, and for any stage of publication, from review to final ``camera-ready'' copy, to the author's own version, with {\itshape very} few changes to the source. \section{Template Overview} As noted in the introduction, the ``\verb|acmart|'' document class can be used to prepare many different kinds of documentation --- a double-blind initial submission of a full-length technical paper, a two-page SIGGRAPH Emerging Technologies abstract, a ``camera-ready'' journal article, a SIGCHI Extended Abstract, and more --- all by selecting the appropriate {\itshape template style} and {\itshape template parameters}. This document will explain the major features of the document class. For further information, the {\itshape \LaTeX\ User's Guide} is available from \url{https://www.acm.org/publications/proceedings-template}. \subsection{Template Styles} The primary parameter given to the ``\verb|acmart|'' document class is the {\itshape template style} which corresponds to the kind of publication or SIG publishing the work. This parameter is enclosed in square brackets and is a part of the {\verb|documentclass|} command: \begin{verbatim} \documentclass[STYLE]{acmart} \end{verbatim} Journals use one of three template styles. All but three ACM journals use the {\verb|acmsmall|} template style: \begin{itemize} \item {\verb|acmsmall|}: The default journal template style. \item {\verb|acmlarge|}: Used by JOCCH and TAP. \item {\verb|acmtog|}: Used by TOG. \end{itemize} The majority of conference proceedings documentation will use the {\verb|acmconf|} template style. \begin{itemize} \item {\verb|acmconf|}: The default proceedings template style. \item{\verb|sigchi|}: Used for SIGCHI conference articles. \item{\verb|sigchi-a|}: Used for SIGCHI ``Extended Abstract'' articles. \item{\verb|sigplan|}: Used for SIGPLAN conference articles. \end{itemize} \subsection{Template Parameters} In addition to specifying the {\itshape template style} to be used in formatting your work, there are a number of {\itshape template parameters} which modify some part of the applied template style. A complete list of these parameters can be found in the {\itshape \LaTeX\ User's Guide.} Frequently-used parameters, or combinations of parameters, include: \begin{itemize} \item {\verb|anonymous,review|}: Suitable for a ``double-blind'' conference submission. Anonymizes the work and includes line numbers. Use with the \verb|\acmSubmissionID| command to print the submission's unique ID on each page of the work. \item{\verb|authorversion|}: Produces a version of the work suitable for posting by the author. \item{\verb|screen|}: Produces colored hyperlinks. \end{itemize} This document uses the following string as the first command in the source file: \begin{verbatim} \documentclass[acmlarge]{acmart} \end{verbatim} \section{Modifications} Modifying the template --- including but not limited to: adjusting margins, typeface sizes, line spacing, paragraph and list definitions, and the use of the \verb|\vspace| command to manually adjust the vertical spacing between elements of your work --- is not allowed. {\bfseries Your document will be returned to you for revision if modifications are discovered.} \section{Typefaces} The ``\verb|acmart|'' document class requires the use of the ``Libertine'' typeface family. Your \TeX\ installation should include this set of packages. Please do not substitute other typefaces. The ``\verb|lmodern|'' and ``\verb|ltimes|'' packages should not be used, as they will override the built-in typeface families. \section{Title Information} The title of your work should use capital letters appropriately - \url{https://capitalizemytitle.com/} has useful rules for capitalization. Use the {\verb|title|} command to define the title of your work. If your work has a subtitle, define it with the {\verb|subtitle|} command. Do not insert line breaks in your title. If your title is lengthy, you must define a short version to be used in the page headers, to prevent overlapping text. The \verb|title| command has a ``short title'' parameter: \begin{verbatim} \title[short title]{full title} \end{verbatim} \section{Authors and Affiliations} Each author must be defined separately for accurate metadata identification. Multiple authors may share one affiliation. Authors' names should not be abbreviated; use full first names wherever possible. Include authors' e-mail addresses whenever possible. Grouping authors' names or e-mail addresses, or providing an ``e-mail alias,'' as shown below, is not acceptable: \begin{verbatim} \author{Brooke Aster, David Mehldau} \email{dave,judy,[email protected]} \email{[email protected]} \end{verbatim} The \verb|authornote| and \verb|authornotemark| commands allow a note to apply to multiple authors --- for example, if the first two authors of an article contributed equally to the work. If your author list is lengthy, you must define a shortened version of the list of authors to be used in the page headers, to prevent overlapping text. The following command should be placed just after the last \verb|\author{}| definition: \begin{verbatim} \renewcommand{\shortauthors}{McCartney, et al.} \end{verbatim} Omitting this command will force the use of a concatenated list of all of the authors' names, which may result in overlapping text in the page headers. The article template's documentation, available at \url{https://www.acm.org/publications/proceedings-template}, has a complete explanation of these commands and tips for their effective use. Note that authors' addresses are mandatory for journal articles. \section{Rights Information} Authors of any work published by ACM will need to complete a rights form. Depending on the kind of work, and the rights management choice made by the author, this may be copyright transfer, permission, license, or an OA (open access) agreement. Regardless of the rights management choice, the author will receive a copy of the completed rights form once it has been submitted. This form contains \LaTeX\ commands that must be copied into the source document. When the document source is compiled, these commands and their parameters add formatted text to several areas of the final document: \begin{itemize} \item the ``ACM Reference Format'' text on the first page. \item the ``rights management'' text on the first page. \item the conference information in the page header(s). \end{itemize} Rights information is unique to the work; if you are preparing several works for an event, make sure to use the correct set of commands with each of the works. The ACM Reference Format text is required for all articles over one page in length, and is optional for one-page articles (abstracts). \section{CCS Concepts and User-Defined Keywords} Two elements of the ``acmart'' document class provide powerful taxonomic tools for you to help readers find your work in an online search. The ACM Computing Classification System --- \url{https://www.acm.org/publications/class-2012} --- is a set of classifiers and concepts that describe the computing discipline. Authors can select entries from this classification system, via \url{https://dl.acm.org/ccs/ccs.cfm}, and generate the commands to be included in the \LaTeX\ source. User-defined keywords are a comma-separated list of words and phrases of the authors' choosing, providing a more flexible way of describing the research being presented. CCS concepts and user-defined keywords are required for for all articles over two pages in length, and are optional for one- and two-page articles (or abstracts). \section{Sectioning Commands} Your work should use standard \LaTeX\ sectioning commands: \verb|section|, \verb|subsection|, \verb|subsubsection|, and \verb|paragraph|. They should be numbered; do not remove the numbering from the commands. Simulating a sectioning command by setting the first word or words of a paragraph in boldface or italicized text is {\bfseries not allowed.} \section{Tables} The ``\verb|acmart|'' document class includes the ``\verb|booktabs|'' package --- \url{https://ctan.org/pkg/booktabs} --- for preparing high-quality tables. Table captions are placed {\itshape above} the table. Because tables cannot be split across pages, the best placement for them is typically the top of the page nearest their initial cite. To ensure this proper ``floating'' placement of tables, use the environment \textbf{table} to enclose the table's contents and the table caption. The contents of the table itself must go in the \textbf{tabular} environment, to be aligned properly in rows and columns, with the desired horizontal and vertical rules. Again, detailed instructions on \textbf{tabular} material are found in the \textit{\LaTeX\ User's Guide}. Immediately following this sentence is the point at which Table~\ref{tab:freq} is included in the input file; compare the placement of the table here with the table in the printed output of this document. \begin{table} \caption{Frequency of Special Characters} \label{tab:freq} \begin{tabular}{ccl} \toprule Non-English or Math&Frequency&Comments\\ \midrule \O & 1 in 1,000& For Swedish names\\ $\pi$ & 1 in 5& Common in math\\ \$ & 4 in 5 & Used in business\\ $\Psi^2_1$ & 1 in 40,000& Unexplained usage\\ \bottomrule \end{tabular} \end{table} To set a wider table, which takes up the whole width of the page's live area, use the environment \textbf{table*} to enclose the table's contents and the table caption. As with a single-column table, this wide table will ``float'' to a location deemed more desirable. Immediately following this sentence is the point at which Table~\ref{tab:commands} is included in the input file; again, it is instructive to compare the placement of the table here with the table in the printed output of this document. \begin{table*} \caption{Some Typical Commands} \label{tab:commands} \begin{tabular}{ccl} \toprule Command &A Number & Comments\\ \midrule \texttt{{\char'134}author} & 100& Author \\ \texttt{{\char'134}table}& 300 & For tables\\ \texttt{{\char'134}table*}& 400& For wider tables\\ \bottomrule \end{tabular} \end{table*} Always use midrule to separate table header rows from data rows, and use it only for this purpose. This enables assistive technologies to recognise table headers and support their users in navigating tables more easily. \section{Math Equations} You may want to display math equations in three distinct styles: inline, numbered or non-numbered display. Each of the three are discussed in the next sections. \subsection{Inline (In-text) Equations} A formula that appears in the running text is called an inline or in-text formula. It is produced by the \textbf{math} environment, which can be invoked with the usual \texttt{{\char'134}begin\,\ldots{\char'134}end} construction or with the short form \texttt{\$\,\ldots\$}. You can use any of the symbols and structures, from $\alpha$ to $\omega$, available in \LaTeX~\cite{Lamport:LaTeX}; this section will simply show a few examples of in-text equations in context. Notice how this equation: \begin{math} \lim_{n\rightarrow \infty}x=0 \end{math}, set here in in-line math style, looks slightly different when set in display style. (See next section). \subsection{Display Equations} A numbered display equation---one set off by vertical space from the text and centered horizontally---is produced by the \textbf{equation} environment. An unnumbered display equation is produced by the \textbf{displaymath} environment. Again, in either environment, you can use any of the symbols and structures available in \LaTeX\@; this section will just give a couple of examples of display equations in context. First, consider the equation, shown as an inline equation above: \begin{equation} \lim_{n\rightarrow \infty}x=0 \end{equation} Notice how it is formatted somewhat differently in the \textbf{displaymath} environment. Now, we'll enter an unnumbered equation: \begin{displaymath} \sum_{i=0}^{\infty} x + 1 \end{displaymath} and follow it with another numbered equation: \begin{equation} \sum_{i=0}^{\infty}x_i=\int_{0}^{\pi+2} f \end{equation} just to demonstrate \LaTeX's able handling of numbering. \section{Figures} The ``\verb|figure|'' environment should be used for figures. One or more images can be placed within a figure. If your figure contains third-party material, you must clearly identify it as such, as shown in the example below. \begin{figure}[h] \centering \includegraphics[width=\linewidth]{sample-franklin} \caption{1907 Franklin Model D roadster. Photograph by Harris \& Ewing, Inc. [Public domain], via Wikimedia Commons. (\url{https://goo.gl/VLCRBB}).} \Description{A woman and a girl in white dresses sit in an open car.} \end{figure} Your figures should contain a caption which describes the figure to the reader. Figure captions are placed {\itshape below} the figure. Every figure should also have a figure description unless it is purely decorative. These descriptions convey what’s in the image to someone who cannot see it. They are also used by search engine crawlers for indexing images, and when images cannot be loaded. A figure description must be unformatted plain text less than 2000 characters long (including spaces). {\bfseries Figure descriptions should not repeat the figure caption – their purpose is to capture important information that is not already provided in the caption or the main text of the paper.} For figures that convey important and complex new information, a short text description may not be adequate. More complex alternative descriptions can be placed in an appendix and referenced in a short figure description. For example, provide a data table capturing the information in a bar chart, or a structured list representing a graph. For additional information regarding how best to write figure descriptions and why doing this is so important, please see \url{https://www.acm.org/publications/taps/describing-figures/}. \subsection{The ``Teaser Figure''} A ``teaser figure'' is an image, or set of images in one figure, that are placed after all author and affiliation information, and before the body of the article, spanning the page. If you wish to have such a figure in your article, place the command immediately before the \verb|\maketitle| command: \begin{verbatim} \begin{teaserfigure} \includegraphics[width=\textwidth]{sampleteaser} \caption{figure caption} \Description{figure description} \end{teaserfigure} \end{verbatim} \section{Citations and Bibliographies} The use of \BibTeX\ for the preparation and formatting of one's references is strongly recommended. Authors' names should be complete --- use full first names (``Donald E. Knuth'') not initials (``D. E. Knuth'') --- and the salient identifying features of a reference should be included: title, year, volume, number, pages, article DOI, etc. The bibliography is included in your source document with these two commands, placed just before the \verb|\end{document}| command: \begin{verbatim} \bibliographystyle{ACM-Reference-Format} \section{Introduction} ACM's consolidated article template, introduced in 2017, provides a consistent \LaTeX\ style for use across ACM publications, and incorporates accessibility and metadata-extraction functionality necessary for future Digital Library endeavors. Numerous ACM and SIG-specific \LaTeX\ templates have been examined, and their unique features incorporated into this single new template. If you are new to publishing with ACM, this document is a valuable guide to the process of preparing your work for publication. If you have published with ACM before, this document provides insight and instruction into more recent changes to the article template. The ``\verb|acmart|'' document class can be used to prepare articles for any ACM publication --- conference or journal, and for any stage of publication, from review to final ``camera-ready'' copy, to the author's own version, with {\itshape very} few changes to the source. \section{Template Overview} As noted in the introduction, the ``\verb|acmart|'' document class can be used to prepare many different kinds of documentation --- a double-blind initial submission of a full-length technical paper, a two-page SIGGRAPH Emerging Technologies abstract, a ``camera-ready'' journal article, a SIGCHI Extended Abstract, and more --- all by selecting the appropriate {\itshape template style} and {\itshape template parameters}. This document will explain the major features of the document class. For further information, the {\itshape \LaTeX\ User's Guide} is available from \url{https://www.acm.org/publications/proceedings-template}. \subsection{Template Styles} The primary parameter given to the ``\verb|acmart|'' document class is the {\itshape template style} which corresponds to the kind of publication or SIG publishing the work. This parameter is enclosed in square brackets and is a part of the {\verb|documentclass|} command: \begin{verbatim} \documentclass[STYLE]{acmart} \end{verbatim} Journals use one of three template styles. All but three ACM journals use the {\verb|acmsmall|} template style: \begin{itemize} \item {\verb|acmsmall|}: The default journal template style. \item {\verb|acmlarge|}: Used by JOCCH and TAP. \item {\verb|acmtog|}: Used by TOG. \end{itemize} The majority of conference proceedings documentation will use the {\verb|acmconf|} template style. \begin{itemize} \item {\verb|acmconf|}: The default proceedings template style. \item{\verb|sigchi|}: Used for SIGCHI conference articles. \item{\verb|sigchi-a|}: Used for SIGCHI ``Extended Abstract'' articles. \item{\verb|sigplan|}: Used for SIGPLAN conference articles. \end{itemize} \subsection{Template Parameters} In addition to specifying the {\itshape template style} to be used in formatting your work, there are a number of {\itshape template parameters} which modify some part of the applied template style. A complete list of these parameters can be found in the {\itshape \LaTeX\ User's Guide.} Frequently-used parameters, or combinations of parameters, include: \begin{itemize} \item {\verb|anonymous,review|}: Suitable for a ``double-blind'' conference submission. Anonymizes the work and includes line numbers. Use with the \verb|\acmSubmissionID| command to print the submission's unique ID on each page of the work. \item{\verb|authorversion|}: Produces a version of the work suitable for posting by the author. \item{\verb|screen|}: Produces colored hyperlinks. \end{itemize} This document uses the following string as the first command in the source file: \begin{verbatim} \documentclass[acmsmall]{acmart} \end{verbatim} \section{Modifications} Modifying the template --- including but not limited to: adjusting margins, typeface sizes, line spacing, paragraph and list definitions, and the use of the \verb|\vspace| command to manually adjust the vertical spacing between elements of your work --- is not allowed. {\bfseries Your document will be returned to you for revision if modifications are discovered.} \section{Typefaces} The ``\verb|acmart|'' document class requires the use of the ``Libertine'' typeface family. Your \TeX\ installation should include this set of packages. Please do not substitute other typefaces. The ``\verb|lmodern|'' and ``\verb|ltimes|'' packages should not be used, as they will override the built-in typeface families. \section{Title Information} The title of your work should use capital letters appropriately - \url{https://capitalizemytitle.com/} has useful rules for capitalization. Use the {\verb|title|} command to define the title of your work. If your work has a subtitle, define it with the {\verb|subtitle|} command. Do not insert line breaks in your title. If your title is lengthy, you must define a short version to be used in the page headers, to prevent overlapping text. The \verb|title| command has a ``short title'' parameter: \begin{verbatim} \title[short title]{full title} \end{verbatim} \section{Authors and Affiliations} Each author must be defined separately for accurate metadata identification. Multiple authors may share one affiliation. Authors' names should not be abbreviated; use full first names wherever possible. Include authors' e-mail addresses whenever possible. Grouping authors' names or e-mail addresses, or providing an ``e-mail alias,'' as shown below, is not acceptable: \begin{verbatim} \author{Brooke Aster, David Mehldau} \email{dave,judy,[email protected]} \email{[email protected]} \end{verbatim} The \verb|authornote| and \verb|authornotemark| commands allow a note to apply to multiple authors --- for example, if the first two authors of an article contributed equally to the work. If your author list is lengthy, you must define a shortened version of the list of authors to be used in the page headers, to prevent overlapping text. The following command should be placed just after the last \verb|\author{}| definition: \begin{verbatim} \renewcommand{\shortauthors}{McCartney, et al.} \end{verbatim} Omitting this command will force the use of a concatenated list of all of the authors' names, which may result in overlapping text in the page headers. The article template's documentation, available at \url{https://www.acm.org/publications/proceedings-template}, has a complete explanation of these commands and tips for their effective use. Note that authors' addresses are mandatory for journal articles. \section{Rights Information} Authors of any work published by ACM will need to complete a rights form. Depending on the kind of work, and the rights management choice made by the author, this may be copyright transfer, permission, license, or an OA (open access) agreement. Regardless of the rights management choice, the author will receive a copy of the completed rights form once it has been submitted. This form contains \LaTeX\ commands that must be copied into the source document. When the document source is compiled, these commands and their parameters add formatted text to several areas of the final document: \begin{itemize} \item the ``ACM Reference Format'' text on the first page. \item the ``rights management'' text on the first page. \item the conference information in the page header(s). \end{itemize} Rights information is unique to the work; if you are preparing several works for an event, make sure to use the correct set of commands with each of the works. The ACM Reference Format text is required for all articles over one page in length, and is optional for one-page articles (abstracts). \section{CCS Concepts and User-Defined Keywords} Two elements of the ``acmart'' document class provide powerful taxonomic tools for you to help readers find your work in an online search. The ACM Computing Classification System --- \url{https://www.acm.org/publications/class-2012} --- is a set of classifiers and concepts that describe the computing discipline. Authors can select entries from this classification system, via \url{https://dl.acm.org/ccs/ccs.cfm}, and generate the commands to be included in the \LaTeX\ source. User-defined keywords are a comma-separated list of words and phrases of the authors' choosing, providing a more flexible way of describing the research being presented. CCS concepts and user-defined keywords are required for for all articles over two pages in length, and are optional for one- and two-page articles (or abstracts). \section{Sectioning Commands} Your work should use standard \LaTeX\ sectioning commands: \verb|section|, \verb|subsection|, \verb|subsubsection|, and \verb|paragraph|. They should be numbered; do not remove the numbering from the commands. Simulating a sectioning command by setting the first word or words of a paragraph in boldface or italicized text is {\bfseries not allowed.} \section{Tables} The ``\verb|acmart|'' document class includes the ``\verb|booktabs|'' package --- \url{https://ctan.org/pkg/booktabs} --- for preparing high-quality tables. Table captions are placed {\itshape above} the table. Because tables cannot be split across pages, the best placement for them is typically the top of the page nearest their initial cite. To ensure this proper ``floating'' placement of tables, use the environment \textbf{table} to enclose the table's contents and the table caption. The contents of the table itself must go in the \textbf{tabular} environment, to be aligned properly in rows and columns, with the desired horizontal and vertical rules. Again, detailed instructions on \textbf{tabular} material are found in the \textit{\LaTeX\ User's Guide}. Immediately following this sentence is the point at which Table~\ref{tab:freq} is included in the input file; compare the placement of the table here with the table in the printed output of this document. \begin{table} \caption{Frequency of Special Characters} \label{tab:freq} \begin{tabular}{ccl} \toprule Non-English or Math&Frequency&Comments\\ \midrule \O & 1 in 1,000& For Swedish names\\ $\pi$ & 1 in 5& Common in math\\ \$ & 4 in 5 & Used in business\\ $\Psi^2_1$ & 1 in 40,000& Unexplained usage\\ \bottomrule \end{tabular} \end{table} To set a wider table, which takes up the whole width of the page's live area, use the environment \textbf{table*} to enclose the table's contents and the table caption. As with a single-column table, this wide table will ``float'' to a location deemed more desirable. Immediately following this sentence is the point at which Table~\ref{tab:commands} is included in the input file; again, it is instructive to compare the placement of the table here with the table in the printed output of this document. \begin{table*} \caption{Some Typical Commands} \label{tab:commands} \begin{tabular}{ccl} \toprule Command &A Number & Comments\\ \midrule \texttt{{\char'134}author} & 100& Author \\ \texttt{{\char'134}table}& 300 & For tables\\ \texttt{{\char'134}table*}& 400& For wider tables\\ \bottomrule \end{tabular} \end{table*} Always use midrule to separate table header rows from data rows, and use it only for this purpose. This enables assistive technologies to recognise table headers and support their users in navigating tables more easily. \section{Math Equations} You may want to display math equations in three distinct styles: inline, numbered or non-numbered display. Each of the three are discussed in the next sections. \subsection{Inline (In-text) Equations} A formula that appears in the running text is called an inline or in-text formula. It is produced by the \textbf{math} environment, which can be invoked with the usual \texttt{{\char'134}begin\,\ldots{\char'134}end} construction or with the short form \texttt{\$\,\ldots\$}. You can use any of the symbols and structures, from $\alpha$ to $\omega$, available in \LaTeX~\cite{Lamport:LaTeX}; this section will simply show a few examples of in-text equations in context. Notice how this equation: \begin{math} \lim_{n\rightarrow \infty}x=0 \end{math}, set here in in-line math style, looks slightly different when set in display style. (See next section). \subsection{Display Equations} A numbered display equation---one set off by vertical space from the text and centered horizontally---is produced by the \textbf{equation} environment. An unnumbered display equation is produced by the \textbf{displaymath} environment. Again, in either environment, you can use any of the symbols and structures available in \LaTeX\@; this section will just give a couple of examples of display equations in context. First, consider the equation, shown as an inline equation above: \begin{equation} \lim_{n\rightarrow \infty}x=0 \end{equation} Notice how it is formatted somewhat differently in the \textbf{displaymath} environment. Now, we'll enter an unnumbered equation: \begin{displaymath} \sum_{i=0}^{\infty} x + 1 \end{displaymath} and follow it with another numbered equation: \begin{equation} \sum_{i=0}^{\infty}x_i=\int_{0}^{\pi+2} f \end{equation} just to demonstrate \LaTeX's able handling of numbering. \section{Figures} The ``\verb|figure|'' environment should be used for figures. One or more images can be placed within a figure. If your figure contains third-party material, you must clearly identify it as such, as shown in the example below. \begin{figure}[h] \centering \includegraphics[width=\linewidth]{sample-franklin} \caption{1907 Franklin Model D roadster. Photograph by Harris \& Ewing, Inc. [Public domain], via Wikimedia Commons. (\url{https://goo.gl/VLCRBB}).} \Description{A woman and a girl in white dresses sit in an open car.} \end{figure} Your figures should contain a caption which describes the figure to the reader. Figure captions are placed {\itshape below} the figure. Every figure should also have a figure description unless it is purely decorative. These descriptions convey what’s in the image to someone who cannot see it. They are also used by search engine crawlers for indexing images, and when images cannot be loaded. A figure description must be unformatted plain text less than 2000 characters long (including spaces). {\bfseries Figure descriptions should not repeat the figure caption – their purpose is to capture important information that is not already provided in the caption or the main text of the paper.} For figures that convey important and complex new information, a short text description may not be adequate. More complex alternative descriptions can be placed in an appendix and referenced in a short figure description. For example, provide a data table capturing the information in a bar chart, or a structured list representing a graph. For additional information regarding how best to write figure descriptions and why doing this is so important, please see \url{https://www.acm.org/publications/taps/describing-figures/}. \subsection{The ``Teaser Figure''} A ``teaser figure'' is an image, or set of images in one figure, that are placed after all author and affiliation information, and before the body of the article, spanning the page. If you wish to have such a figure in your article, place the command immediately before the \verb|\maketitle| command: \begin{verbatim} \begin{teaserfigure} \includegraphics[width=\textwidth]{sampleteaser} \caption{figure caption} \Description{figure description} \end{teaserfigure} \end{verbatim} \section{Citations and Bibliographies} The use of \BibTeX\ for the preparation and formatting of one's references is strongly recommended. Authors' names should be complete --- use full first names (``Donald E. Knuth'') not initials (``D. E. Knuth'') --- and the salient identifying features of a reference should be included: title, year, volume, number, pages, article DOI, etc. The bibliography is included in your source document with these two commands, placed just before the \verb|\end{document}| command: \begin{verbatim} \bibliographystyle{ACM-Reference-Format} \section{Introduction} ACM's consolidated article template, introduced in 2017, provides a consistent \LaTeX\ style for use across ACM publications, and incorporates accessibility and metadata-extraction functionality necessary for future Digital Library endeavors. Numerous ACM and SIG-specific \LaTeX\ templates have been examined, and their unique features incorporated into this single new template. If you are new to publishing with ACM, this document is a valuable guide to the process of preparing your work for publication. If you have published with ACM before, this document provides insight and instruction into more recent changes to the article template. The ``\verb|acmart|'' document class can be used to prepare articles for any ACM publication --- conference or journal, and for any stage of publication, from review to final ``camera-ready'' copy, to the author's own version, with {\itshape very} few changes to the source. \section{Template Overview} As noted in the introduction, the ``\verb|acmart|'' document class can be used to prepare many different kinds of documentation --- a double-blind initial submission of a full-length technical paper, a two-page SIGGRAPH Emerging Technologies abstract, a ``camera-ready'' journal article, a SIGCHI Extended Abstract, and more --- all by selecting the appropriate {\itshape template style} and {\itshape template parameters}. This document will explain the major features of the document class. For further information, the {\itshape \LaTeX\ User's Guide} is available from \url{https://www.acm.org/publications/proceedings-template}. \subsection{Template Styles} The primary parameter given to the ``\verb|acmart|'' document class is the {\itshape template style} which corresponds to the kind of publication or SIG publishing the work. This parameter is enclosed in square brackets and is a part of the {\verb|documentclass|} command: \begin{verbatim} \documentclass[STYLE]{acmart} \end{verbatim} Journals use one of three template styles. All but three ACM journals use the {\verb|acmsmall|} template style: \begin{itemize} \item {\verb|acmsmall|}: The default journal template style. \item {\verb|acmlarge|}: Used by JOCCH and TAP. \item {\verb|acmtog|}: Used by TOG. \end{itemize} The majority of conference proceedings documentation will use the {\verb|acmconf|} template style. \begin{itemize} \item {\verb|acmconf|}: The default proceedings template style. \item{\verb|sigchi|}: Used for SIGCHI conference articles. \item{\verb|sigchi-a|}: Used for SIGCHI ``Extended Abstract'' articles. \item{\verb|sigplan|}: Used for SIGPLAN conference articles. \end{itemize} \subsection{Template Parameters} In addition to specifying the {\itshape template style} to be used in formatting your work, there are a number of {\itshape template parameters} which modify some part of the applied template style. A complete list of these parameters can be found in the {\itshape \LaTeX\ User's Guide.} Frequently-used parameters, or combinations of parameters, include: \begin{itemize} \item {\verb|anonymous,review|}: Suitable for a ``double-blind'' conference submission. Anonymizes the work and includes line numbers. Use with the \verb|\acmSubmissionID| command to print the submission's unique ID on each page of the work. \item{\verb|authorversion|}: Produces a version of the work suitable for posting by the author. \item{\verb|screen|}: Produces colored hyperlinks. \end{itemize} This document uses the following string as the first command in the source file: \begin{verbatim} \documentclass[acmsmall,screen,review]{acmart} \end{verbatim} \section{Modifications} Modifying the template --- including but not limited to: adjusting margins, typeface sizes, line spacing, paragraph and list definitions, and the use of the \verb|\vspace| command to manually adjust the vertical spacing between elements of your work --- is not allowed. {\bfseries Your document will be returned to you for revision if modifications are discovered.} \section{Typefaces} The ``\verb|acmart|'' document class requires the use of the ``Libertine'' typeface family. Your \TeX\ installation should include this set of packages. Please do not substitute other typefaces. The ``\verb|lmodern|'' and ``\verb|ltimes|'' packages should not be used, as they will override the built-in typeface families. \section{Title Information} The title of your work should use capital letters appropriately - \url{https://capitalizemytitle.com/} has useful rules for capitalization. Use the {\verb|title|} command to define the title of your work. If your work has a subtitle, define it with the {\verb|subtitle|} command. Do not insert line breaks in your title. If your title is lengthy, you must define a short version to be used in the page headers, to prevent overlapping text. The \verb|title| command has a ``short title'' parameter: \begin{verbatim} \title[short title]{full title} \end{verbatim} \section{Authors and Affiliations} Each author must be defined separately for accurate metadata identification. Multiple authors may share one affiliation. Authors' names should not be abbreviated; use full first names wherever possible. Include authors' e-mail addresses whenever possible. Grouping authors' names or e-mail addresses, or providing an ``e-mail alias,'' as shown below, is not acceptable: \begin{verbatim} \author{Brooke Aster, David Mehldau} \email{dave,judy,[email protected]} \email{[email protected]} \end{verbatim} The \verb|authornote| and \verb|authornotemark| commands allow a note to apply to multiple authors --- for example, if the first two authors of an article contributed equally to the work. If your author list is lengthy, you must define a shortened version of the list of authors to be used in the page headers, to prevent overlapping text. The following command should be placed just after the last \verb|\author{}| definition: \begin{verbatim} \renewcommand{\shortauthors}{McCartney, et al.} \end{verbatim} Omitting this command will force the use of a concatenated list of all of the authors' names, which may result in overlapping text in the page headers. The article template's documentation, available at \url{https://www.acm.org/publications/proceedings-template}, has a complete explanation of these commands and tips for their effective use. Note that authors' addresses are mandatory for journal articles. \section{Rights Information} Authors of any work published by ACM will need to complete a rights form. Depending on the kind of work, and the rights management choice made by the author, this may be copyright transfer, permission, license, or an OA (open access) agreement. Regardless of the rights management choice, the author will receive a copy of the completed rights form once it has been submitted. This form contains \LaTeX\ commands that must be copied into the source document. When the document source is compiled, these commands and their parameters add formatted text to several areas of the final document: \begin{itemize} \item the ``ACM Reference Format'' text on the first page. \item the ``rights management'' text on the first page. \item the conference information in the page header(s). \end{itemize} Rights information is unique to the work; if you are preparing several works for an event, make sure to use the correct set of commands with each of the works. The ACM Reference Format text is required for all articles over one page in length, and is optional for one-page articles (abstracts). \section{CCS Concepts and User-Defined Keywords} Two elements of the ``acmart'' document class provide powerful taxonomic tools for you to help readers find your work in an online search. The ACM Computing Classification System --- \url{https://www.acm.org/publications/class-2012} --- is a set of classifiers and concepts that describe the computing discipline. Authors can select entries from this classification system, via \url{https://dl.acm.org/ccs/ccs.cfm}, and generate the commands to be included in the \LaTeX\ source. User-defined keywords are a comma-separated list of words and phrases of the authors' choosing, providing a more flexible way of describing the research being presented. CCS concepts and user-defined keywords are required for for all articles over two pages in length, and are optional for one- and two-page articles (or abstracts). \section{Sectioning Commands} Your work should use standard \LaTeX\ sectioning commands: \verb|section|, \verb|subsection|, \verb|subsubsection|, and \verb|paragraph|. They should be numbered; do not remove the numbering from the commands. Simulating a sectioning command by setting the first word or words of a paragraph in boldface or italicized text is {\bfseries not allowed.} \section{Tables} The ``\verb|acmart|'' document class includes the ``\verb|booktabs|'' package --- \url{https://ctan.org/pkg/booktabs} --- for preparing high-quality tables. Table captions are placed {\itshape above} the table. Because tables cannot be split across pages, the best placement for them is typically the top of the page nearest their initial cite. To ensure this proper ``floating'' placement of tables, use the environment \textbf{table} to enclose the table's contents and the table caption. The contents of the table itself must go in the \textbf{tabular} environment, to be aligned properly in rows and columns, with the desired horizontal and vertical rules. Again, detailed instructions on \textbf{tabular} material are found in the \textit{\LaTeX\ User's Guide}. Immediately following this sentence is the point at which Table~\ref{tab:freq} is included in the input file; compare the placement of the table here with the table in the printed output of this document. \begin{table} \caption{Frequency of Special Characters} \label{tab:freq} \begin{tabular}{ccl} \toprule Non-English or Math&Frequency&Comments\\ \midrule \O & 1 in 1,000& For Swedish names\\ $\pi$ & 1 in 5& Common in math\\ \$ & 4 in 5 & Used in business\\ $\Psi^2_1$ & 1 in 40,000& Unexplained usage\\ \bottomrule \end{tabular} \end{table} To set a wider table, which takes up the whole width of the page's live area, use the environment \textbf{table*} to enclose the table's contents and the table caption. As with a single-column table, this wide table will ``float'' to a location deemed more desirable. Immediately following this sentence is the point at which Table~\ref{tab:commands} is included in the input file; again, it is instructive to compare the placement of the table here with the table in the printed output of this document. \begin{table*} \caption{Some Typical Commands} \label{tab:commands} \begin{tabular}{ccl} \toprule Command &A Number & Comments\\ \midrule \texttt{{\char'134}author} & 100& Author \\ \texttt{{\char'134}table}& 300 & For tables\\ \texttt{{\char'134}table*}& 400& For wider tables\\ \bottomrule \end{tabular} \end{table*} Always use midrule to separate table header rows from data rows, and use it only for this purpose. This enables assistive technologies to recognise table headers and support their users in navigating tables more easily. \section{Math Equations} You may want to display math equations in three distinct styles: inline, numbered or non-numbered display. Each of the three are discussed in the next sections. \subsection{Inline (In-text) Equations} A formula that appears in the running text is called an inline or in-text formula. It is produced by the \textbf{math} environment, which can be invoked with the usual \texttt{{\char'134}begin\,\ldots{\char'134}end} construction or with the short form \texttt{\$\,\ldots\$}. You can use any of the symbols and structures, from $\alpha$ to $\omega$, available in \LaTeX~\cite{Lamport:LaTeX}; this section will simply show a few examples of in-text equations in context. Notice how this equation: \begin{math} \lim_{n\rightarrow \infty}x=0 \end{math}, set here in in-line math style, looks slightly different when set in display style. (See next section). \subsection{Display Equations} A numbered display equation---one set off by vertical space from the text and centered horizontally---is produced by the \textbf{equation} environment. An unnumbered display equation is produced by the \textbf{displaymath} environment. Again, in either environment, you can use any of the symbols and structures available in \LaTeX\@; this section will just give a couple of examples of display equations in context. First, consider the equation, shown as an inline equation above: \begin{equation} \lim_{n\rightarrow \infty}x=0 \end{equation} Notice how it is formatted somewhat differently in the \textbf{displaymath} environment. Now, we'll enter an unnumbered equation: \begin{displaymath} \sum_{i=0}^{\infty} x + 1 \end{displaymath} and follow it with another numbered equation: \begin{equation} \sum_{i=0}^{\infty}x_i=\int_{0}^{\pi+2} f \end{equation} just to demonstrate \LaTeX's able handling of numbering. \section{Figures} The ``\verb|figure|'' environment should be used for figures. One or more images can be placed within a figure. If your figure contains third-party material, you must clearly identify it as such, as shown in the example below. \begin{figure}[h] \centering \includegraphics[width=\linewidth]{sample-franklin} \caption{1907 Franklin Model D roadster. Photograph by Harris \& Ewing, Inc. [Public domain], via Wikimedia Commons. (\url{https://goo.gl/VLCRBB}).} \Description{A woman and a girl in white dresses sit in an open car.} \end{figure} Your figures should contain a caption which describes the figure to the reader. Figure captions are placed {\itshape below} the figure. Every figure should also have a figure description unless it is purely decorative. These descriptions convey what’s in the image to someone who cannot see it. They are also used by search engine crawlers for indexing images, and when images cannot be loaded. A figure description must be unformatted plain text less than 2000 characters long (including spaces). {\bfseries Figure descriptions should not repeat the figure caption – their purpose is to capture important information that is not already provided in the caption or the main text of the paper.} For figures that convey important and complex new information, a short text description may not be adequate. More complex alternative descriptions can be placed in an appendix and referenced in a short figure description. For example, provide a data table capturing the information in a bar chart, or a structured list representing a graph. For additional information regarding how best to write figure descriptions and why doing this is so important, please see \url{https://www.acm.org/publications/taps/describing-figures/}. \subsection{The ``Teaser Figure''} A ``teaser figure'' is an image, or set of images in one figure, that are placed after all author and affiliation information, and before the body of the article, spanning the page. If you wish to have such a figure in your article, place the command immediately before the \verb|\maketitle| command: \begin{verbatim} \begin{teaserfigure} \includegraphics[width=\textwidth]{sampleteaser} \caption{figure caption} \Description{figure description} \end{teaserfigure} \end{verbatim} \section{Citations and Bibliographies} The use of \BibTeX\ for the preparation and formatting of one's references is strongly recommended. Authors' names should be complete --- use full first names (``Donald E. Knuth'') not initials (``D. E. Knuth'') --- and the salient identifying features of a reference should be included: title, year, volume, number, pages, article DOI, etc. The bibliography is included in your source document with these two commands, placed just before the \verb|\end{document}| command: \begin{verbatim} \bibliographystyle{ACM-Reference-Format} \section{Introduction} ACM's consolidated article template, introduced in 2017, provides a consistent \LaTeX\ style for use across ACM publications, and incorporates accessibility and metadata-extraction functionality necessary for future Digital Library endeavors. Numerous ACM and SIG-specific \LaTeX\ templates have been examined, and their unique features incorporated into this single new template. If you are new to publishing with ACM, this document is a valuable guide to the process of preparing your work for publication. If you have published with ACM before, this document provides insight and instruction into more recent changes to the article template. The ``\verb|acmart|'' document class can be used to prepare articles for any ACM publication --- conference or journal, and for any stage of publication, from review to final ``camera-ready'' copy, to the author's own version, with {\itshape very} few changes to the source. \section{Template Overview} As noted in the introduction, the ``\verb|acmart|'' document class can be used to prepare many different kinds of documentation --- a double-blind initial submission of a full-length technical paper, a two-page SIGGRAPH Emerging Technologies abstract, a ``camera-ready'' journal article, a SIGCHI Extended Abstract, and more --- all by selecting the appropriate {\itshape template style} and {\itshape template parameters}. This document will explain the major features of the document class. For further information, the {\itshape \LaTeX\ User's Guide} is available from \url{https://www.acm.org/publications/proceedings-template}. \subsection{Template Styles} The primary parameter given to the ``\verb|acmart|'' document class is the {\itshape template style} which corresponds to the kind of publication or SIG publishing the work. This parameter is enclosed in square brackets and is a part of the {\verb|documentclass|} command: \begin{verbatim} \documentclass[STYLE]{acmart} \end{verbatim} Journals use one of three template styles. All but three ACM journals use the {\verb|acmsmall|} template style: \begin{itemize} \item {\verb|acmsmall|}: The default journal template style. \item {\verb|acmlarge|}: Used by JOCCH and TAP. \item {\verb|acmtog|}: Used by TOG. \end{itemize} The majority of conference proceedings documentation will use the {\verb|acmconf|} template style. \begin{itemize} \item {\verb|acmconf|}: The default proceedings template style. \item{\verb|sigchi|}: Used for SIGCHI conference articles. \item{\verb|sigchi-a|}: Used for SIGCHI ``Extended Abstract'' articles. \item{\verb|sigplan|}: Used for SIGPLAN conference articles. \end{itemize} \subsection{Template Parameters} In addition to specifying the {\itshape template style} to be used in formatting your work, there are a number of {\itshape template parameters} which modify some part of the applied template style. A complete list of these parameters can be found in the {\itshape \LaTeX\ User's Guide.} Frequently-used parameters, or combinations of parameters, include: \begin{itemize} \item {\verb|anonymous,review|}: Suitable for a ``double-blind'' conference submission. Anonymizes the work and includes line numbers. Use with the \verb|\acmSubmissionID| command to print the submission's unique ID on each page of the work. \item{\verb|authorversion|}: Produces a version of the work suitable for posting by the author. \item{\verb|screen|}: Produces colored hyperlinks. \end{itemize} This document uses the following string as the first command in the source file: \begin{verbatim} \documentclass[manuscript,screen,review]{acmart} \end{verbatim} \section{Modifications} Modifying the template --- including but not limited to: adjusting margins, typeface sizes, line spacing, paragraph and list definitions, and the use of the \verb|\vspace| command to manually adjust the vertical spacing between elements of your work --- is not allowed. {\bfseries Your document will be returned to you for revision if modifications are discovered.} \section{Typefaces} The ``\verb|acmart|'' document class requires the use of the ``Libertine'' typeface family. Your \TeX\ installation should include this set of packages. Please do not substitute other typefaces. The ``\verb|lmodern|'' and ``\verb|ltimes|'' packages should not be used, as they will override the built-in typeface families. \section{Title Information} The title of your work should use capital letters appropriately - \url{https://capitalizemytitle.com/} has useful rules for capitalization. Use the {\verb|title|} command to define the title of your work. If your work has a subtitle, define it with the {\verb|subtitle|} command. Do not insert line breaks in your title. If your title is lengthy, you must define a short version to be used in the page headers, to prevent overlapping text. The \verb|title| command has a ``short title'' parameter: \begin{verbatim} \title[short title]{full title} \end{verbatim} \section{Authors and Affiliations} Each author must be defined separately for accurate metadata identification. Multiple authors may share one affiliation. Authors' names should not be abbreviated; use full first names wherever possible. Include authors' e-mail addresses whenever possible. Grouping authors' names or e-mail addresses, or providing an ``e-mail alias,'' as shown below, is not acceptable: \begin{verbatim} \author{Brooke Aster, David Mehldau} \email{dave,judy,[email protected]} \email{[email protected]} \end{verbatim} The \verb|authornote| and \verb|authornotemark| commands allow a note to apply to multiple authors --- for example, if the first two authors of an article contributed equally to the work. If your author list is lengthy, you must define a shortened version of the list of authors to be used in the page headers, to prevent overlapping text. The following command should be placed just after the last \verb|\author{}| definition: \begin{verbatim} \renewcommand{\shortauthors}{McCartney, et al.} \end{verbatim} Omitting this command will force the use of a concatenated list of all of the authors' names, which may result in overlapping text in the page headers. The article template's documentation, available at \url{https://www.acm.org/publications/proceedings-template}, has a complete explanation of these commands and tips for their effective use. Note that authors' addresses are mandatory for journal articles. \section{Rights Information} Authors of any work published by ACM will need to complete a rights form. Depending on the kind of work, and the rights management choice made by the author, this may be copyright transfer, permission, license, or an OA (open access) agreement. Regardless of the rights management choice, the author will receive a copy of the completed rights form once it has been submitted. This form contains \LaTeX\ commands that must be copied into the source document. When the document source is compiled, these commands and their parameters add formatted text to several areas of the final document: \begin{itemize} \item the ``ACM Reference Format'' text on the first page. \item the ``rights management'' text on the first page. \item the conference information in the page header(s). \end{itemize} Rights information is unique to the work; if you are preparing several works for an event, make sure to use the correct set of commands with each of the works. The ACM Reference Format text is required for all articles over one page in length, and is optional for one-page articles (abstracts). \section{CCS Concepts and User-Defined Keywords} Two elements of the ``acmart'' document class provide powerful taxonomic tools for you to help readers find your work in an online search. The ACM Computing Classification System --- \url{https://www.acm.org/publications/class-2012} --- is a set of classifiers and concepts that describe the computing discipline. Authors can select entries from this classification system, via \url{https://dl.acm.org/ccs/ccs.cfm}, and generate the commands to be included in the \LaTeX\ source. User-defined keywords are a comma-separated list of words and phrases of the authors' choosing, providing a more flexible way of describing the research being presented. CCS concepts and user-defined keywords are required for for all articles over two pages in length, and are optional for one- and two-page articles (or abstracts). \section{Sectioning Commands} Your work should use standard \LaTeX\ sectioning commands: \verb|section|, \verb|subsection|, \verb|subsubsection|, and \verb|paragraph|. They should be numbered; do not remove the numbering from the commands. Simulating a sectioning command by setting the first word or words of a paragraph in boldface or italicized text is {\bfseries not allowed.} \section{Tables} The ``\verb|acmart|'' document class includes the ``\verb|booktabs|'' package --- \url{https://ctan.org/pkg/booktabs} --- for preparing high-quality tables. Table captions are placed {\itshape above} the table. Because tables cannot be split across pages, the best placement for them is typically the top of the page nearest their initial cite. To ensure this proper ``floating'' placement of tables, use the environment \textbf{table} to enclose the table's contents and the table caption. The contents of the table itself must go in the \textbf{tabular} environment, to be aligned properly in rows and columns, with the desired horizontal and vertical rules. Again, detailed instructions on \textbf{tabular} material are found in the \textit{\LaTeX\ User's Guide}. Immediately following this sentence is the point at which Table~\ref{tab:freq} is included in the input file; compare the placement of the table here with the table in the printed output of this document. \begin{table} \caption{Frequency of Special Characters} \label{tab:freq} \begin{tabular}{ccl} \toprule Non-English or Math&Frequency&Comments\\ \midrule \O & 1 in 1,000& For Swedish names\\ $\pi$ & 1 in 5& Common in math\\ \$ & 4 in 5 & Used in business\\ $\Psi^2_1$ & 1 in 40,000& Unexplained usage\\ \bottomrule \end{tabular} \end{table} To set a wider table, which takes up the whole width of the page's live area, use the environment \textbf{table*} to enclose the table's contents and the table caption. As with a single-column table, this wide table will ``float'' to a location deemed more desirable. Immediately following this sentence is the point at which Table~\ref{tab:commands} is included in the input file; again, it is instructive to compare the placement of the table here with the table in the printed output of this document. \begin{table*} \caption{Some Typical Commands} \label{tab:commands} \begin{tabular}{ccl} \toprule Command &A Number & Comments\\ \midrule \texttt{{\char'134}author} & 100& Author \\ \texttt{{\char'134}table}& 300 & For tables\\ \texttt{{\char'134}table*}& 400& For wider tables\\ \bottomrule \end{tabular} \end{table*} Always use midrule to separate table header rows from data rows, and use it only for this purpose. This enables assistive technologies to recognise table headers and support their users in navigating tables more easily. \section{Math Equations} You may want to display math equations in three distinct styles: inline, numbered or non-numbered display. Each of the three are discussed in the next sections. \subsection{Inline (In-text) Equations} A formula that appears in the running text is called an inline or in-text formula. It is produced by the \textbf{math} environment, which can be invoked with the usual \texttt{{\char'134}begin\,\ldots{\char'134}end} construction or with the short form \texttt{\$\,\ldots\$}. You can use any of the symbols and structures, from $\alpha$ to $\omega$, available in \LaTeX~\cite{Lamport:LaTeX}; this section will simply show a few examples of in-text equations in context. Notice how this equation: \begin{math} \lim_{n\rightarrow \infty}x=0 \end{math}, set here in in-line math style, looks slightly different when set in display style. (See next section). \subsection{Display Equations} A numbered display equation---one set off by vertical space from the text and centered horizontally---is produced by the \textbf{equation} environment. An unnumbered display equation is produced by the \textbf{displaymath} environment. Again, in either environment, you can use any of the symbols and structures available in \LaTeX\@; this section will just give a couple of examples of display equations in context. First, consider the equation, shown as an inline equation above: \begin{equation} \lim_{n\rightarrow \infty}x=0 \end{equation} Notice how it is formatted somewhat differently in the \textbf{displaymath} environment. Now, we'll enter an unnumbered equation: \begin{displaymath} \sum_{i=0}^{\infty} x + 1 \end{displaymath} and follow it with another numbered equation: \begin{equation} \sum_{i=0}^{\infty}x_i=\int_{0}^{\pi+2} f \end{equation} just to demonstrate \LaTeX's able handling of numbering. \section{Figures} The ``\verb|figure|'' environment should be used for figures. One or more images can be placed within a figure. If your figure contains third-party material, you must clearly identify it as such, as shown in the example below. \begin{figure}[h] \centering \includegraphics[width=\linewidth]{sample-franklin} \caption{1907 Franklin Model D roadster. Photograph by Harris \& Ewing, Inc. [Public domain], via Wikimedia Commons. (\url{https://goo.gl/VLCRBB}).} \Description{A woman and a girl in white dresses sit in an open car.} \end{figure} Your figures should contain a caption which describes the figure to the reader. Figure captions are placed {\itshape below} the figure. Every figure should also have a figure description unless it is purely decorative. These descriptions convey what’s in the image to someone who cannot see it. They are also used by search engine crawlers for indexing images, and when images cannot be loaded. A figure description must be unformatted plain text less than 2000 characters long (including spaces). {\bfseries Figure descriptions should not repeat the figure caption – their purpose is to capture important information that is not already provided in the caption or the main text of the paper.} For figures that convey important and complex new information, a short text description may not be adequate. More complex alternative descriptions can be placed in an appendix and referenced in a short figure description. For example, provide a data table capturing the information in a bar chart, or a structured list representing a graph. For additional information regarding how best to write figure descriptions and why doing this is so important, please see \url{https://www.acm.org/publications/taps/describing-figures/}. \subsection{The ``Teaser Figure''} A ``teaser figure'' is an image, or set of images in one figure, that are placed after all author and affiliation information, and before the body of the article, spanning the page. If you wish to have such a figure in your article, place the command immediately before the \verb|\maketitle| command: \begin{verbatim} \begin{teaserfigure} \includegraphics[width=\textwidth]{sampleteaser} \caption{figure caption} \Description{figure description} \end{teaserfigure} \end{verbatim} \section{Citations and Bibliographies} The use of \BibTeX\ for the preparation and formatting of one's references is strongly recommended. Authors' names should be complete --- use full first names (``Donald E. Knuth'') not initials (``D. E. Knuth'') --- and the salient identifying features of a reference should be included: title, year, volume, number, pages, article DOI, etc. The bibliography is included in your source document with these two commands, placed just before the \verb|\end{document}| command: \begin{verbatim} \bibliographystyle{ACM-Reference-Format} \section{Introduction} ACM's consolidated article template, introduced in 2017, provides a consistent \LaTeX\ style for use across ACM publications, and incorporates accessibility and metadata-extraction functionality necessary for future Digital Library endeavors. Numerous ACM and SIG-specific \LaTeX\ templates have been examined, and their unique features incorporated into this single new template. If you are new to publishing with ACM, this document is a valuable guide to the process of preparing your work for publication. If you have published with ACM before, this document provides insight and instruction into more recent changes to the article template. The ``\verb|acmart|'' document class can be used to prepare articles for any ACM publication --- conference or journal, and for any stage of publication, from review to final ``camera-ready'' copy, to the author's own version, with {\itshape very} few changes to the source. \section{Template Overview} As noted in the introduction, the ``\verb|acmart|'' document class can be used to prepare many different kinds of documentation --- a double-blind initial submission of a full-length technical paper, a two-page SIGGRAPH Emerging Technologies abstract, a ``camera-ready'' journal article, a SIGCHI Extended Abstract, and more --- all by selecting the appropriate {\itshape template style} and {\itshape template parameters}. This document will explain the major features of the document class. For further information, the {\itshape \LaTeX\ User's Guide} is available from \url{https://www.acm.org/publications/proceedings-template}. \subsection{Template Styles} The primary parameter given to the ``\verb|acmart|'' document class is the {\itshape template style} which corresponds to the kind of publication or SIG publishing the work. This parameter is enclosed in square brackets and is a part of the {\verb|documentclass|} command: \begin{verbatim} \documentclass[STYLE]{acmart} \end{verbatim} Journals use one of three template styles. All but three ACM journals use the {\verb|acmsmall|} template style: \begin{itemize} \item {\verb|acmsmall|}: The default journal template style. \item {\verb|acmlarge|}: Used by JOCCH and TAP. \item {\verb|acmtog|}: Used by TOG. \end{itemize} The majority of conference proceedings documentation will use the {\verb|acmconf|} template style. \begin{itemize} \item {\verb|acmconf|}: The default proceedings template style. \item{\verb|sigchi|}: Used for SIGCHI conference articles. \item{\verb|sigchi-a|}: Used for SIGCHI ``Extended Abstract'' articles. \item{\verb|sigplan|}: Used for SIGPLAN conference articles. \end{itemize} \subsection{Template Parameters} In addition to specifying the {\itshape template style} to be used in formatting your work, there are a number of {\itshape template parameters} which modify some part of the applied template style. A complete list of these parameters can be found in the {\itshape \LaTeX\ User's Guide.} Frequently-used parameters, or combinations of parameters, include: \begin{itemize} \item {\verb|anonymous,review|}: Suitable for a ``double-blind'' conference submission. Anonymizes the work and includes line numbers. Use with the \verb|\acmSubmissionID| command to print the submission's unique ID on each page of the work. \item{\verb|authorversion|}: Produces a version of the work suitable for posting by the author. \item{\verb|screen|}: Produces colored hyperlinks. \end{itemize} This document uses the following string as the first command in the source file: \begin{verbatim} \documentclass[sigplan,screen]{acmart} \end{verbatim} \section{Modifications} Modifying the template --- including but not limited to: adjusting margins, typeface sizes, line spacing, paragraph and list definitions, and the use of the \verb|\vspace| command to manually adjust the vertical spacing between elements of your work --- is not allowed. {\bfseries Your document will be returned to you for revision if modifications are discovered.} \section{Typefaces} The ``\verb|acmart|'' document class requires the use of the ``Libertine'' typeface family. Your \TeX\ installation should include this set of packages. Please do not substitute other typefaces. The ``\verb|lmodern|'' and ``\verb|ltimes|'' packages should not be used, as they will override the built-in typeface families. \section{Title Information} The title of your work should use capital letters appropriately - \url{https://capitalizemytitle.com/} has useful rules for capitalization. Use the {\verb|title|} command to define the title of your work. If your work has a subtitle, define it with the {\verb|subtitle|} command. Do not insert line breaks in your title. If your title is lengthy, you must define a short version to be used in the page headers, to prevent overlapping text. The \verb|title| command has a ``short title'' parameter: \begin{verbatim} \title[short title]{full title} \end{verbatim} \section{Authors and Affiliations} Each author must be defined separately for accurate metadata identification. Multiple authors may share one affiliation. Authors' names should not be abbreviated; use full first names wherever possible. Include authors' e-mail addresses whenever possible. Grouping authors' names or e-mail addresses, or providing an ``e-mail alias,'' as shown below, is not acceptable: \begin{verbatim} \author{Brooke Aster, David Mehldau} \email{dave,judy,[email protected]} \email{[email protected]} \end{verbatim} The \verb|authornote| and \verb|authornotemark| commands allow a note to apply to multiple authors --- for example, if the first two authors of an article contributed equally to the work. If your author list is lengthy, you must define a shortened version of the list of authors to be used in the page headers, to prevent overlapping text. The following command should be placed just after the last \verb|\author{}| definition: \begin{verbatim} \renewcommand{\shortauthors}{McCartney, et al.} \end{verbatim} Omitting this command will force the use of a concatenated list of all of the authors' names, which may result in overlapping text in the page headers. The article template's documentation, available at \url{https://www.acm.org/publications/proceedings-template}, has a complete explanation of these commands and tips for their effective use. Note that authors' addresses are mandatory for journal articles. \section{Rights Information} Authors of any work published by ACM will need to complete a rights form. Depending on the kind of work, and the rights management choice made by the author, this may be copyright transfer, permission, license, or an OA (open access) agreement. Regardless of the rights management choice, the author will receive a copy of the completed rights form once it has been submitted. This form contains \LaTeX\ commands that must be copied into the source document. When the document source is compiled, these commands and their parameters add formatted text to several areas of the final document: \begin{itemize} \item the ``ACM Reference Format'' text on the first page. \item the ``rights management'' text on the first page. \item the conference information in the page header(s). \end{itemize} Rights information is unique to the work; if you are preparing several works for an event, make sure to use the correct set of commands with each of the works. The ACM Reference Format text is required for all articles over one page in length, and is optional for one-page articles (abstracts). \section{CCS Concepts and User-Defined Keywords} Two elements of the ``acmart'' document class provide powerful taxonomic tools for you to help readers find your work in an online search. The ACM Computing Classification System --- \url{https://www.acm.org/publications/class-2012} --- is a set of classifiers and concepts that describe the computing discipline. Authors can select entries from this classification system, via \url{https://dl.acm.org/ccs/ccs.cfm}, and generate the commands to be included in the \LaTeX\ source. User-defined keywords are a comma-separated list of words and phrases of the authors' choosing, providing a more flexible way of describing the research being presented. CCS concepts and user-defined keywords are required for for all articles over two pages in length, and are optional for one- and two-page articles (or abstracts). \section{Sectioning Commands} Your work should use standard \LaTeX\ sectioning commands: \verb|section|, \verb|subsection|, \verb|subsubsection|, and \verb|paragraph|. They should be numbered; do not remove the numbering from the commands. Simulating a sectioning command by setting the first word or words of a paragraph in boldface or italicized text is {\bfseries not allowed.} \section{Tables} The ``\verb|acmart|'' document class includes the ``\verb|booktabs|'' package --- \url{https://ctan.org/pkg/booktabs} --- for preparing high-quality tables. Table captions are placed {\itshape above} the table. Because tables cannot be split across pages, the best placement for them is typically the top of the page nearest their initial cite. To ensure this proper ``floating'' placement of tables, use the environment \textbf{table} to enclose the table's contents and the table caption. The contents of the table itself must go in the \textbf{tabular} environment, to be aligned properly in rows and columns, with the desired horizontal and vertical rules. Again, detailed instructions on \textbf{tabular} material are found in the \textit{\LaTeX\ User's Guide}. Immediately following this sentence is the point at which Table~\ref{tab:freq} is included in the input file; compare the placement of the table here with the table in the printed output of this document. \begin{table} \caption{Frequency of Special Characters} \label{tab:freq} \begin{tabular}{ccl} \toprule Non-English or Math&Frequency&Comments\\ \midrule \O & 1 in 1,000& For Swedish names\\ $\pi$ & 1 in 5& Common in math\\ \$ & 4 in 5 & Used in business\\ $\Psi^2_1$ & 1 in 40,000& Unexplained usage\\ \bottomrule \end{tabular} \end{table} To set a wider table, which takes up the whole width of the page's live area, use the environment \textbf{table*} to enclose the table's contents and the table caption. As with a single-column table, this wide table will ``float'' to a location deemed more desirable. Immediately following this sentence is the point at which Table~\ref{tab:commands} is included in the input file; again, it is instructive to compare the placement of the table here with the table in the printed output of this document. \begin{table*} \caption{Some Typical Commands} \label{tab:commands} \begin{tabular}{ccl} \toprule Command &A Number & Comments\\ \midrule \texttt{{\char'134}author} & 100& Author \\ \texttt{{\char'134}table}& 300 & For tables\\ \texttt{{\char'134}table*}& 400& For wider tables\\ \bottomrule \end{tabular} \end{table*} Always use midrule to separate table header rows from data rows, and use it only for this purpose. This enables assistive technologies to recognise table headers and support their users in navigating tables more easily. \section{Math Equations} You may want to display math equations in three distinct styles: inline, numbered or non-numbered display. Each of the three are discussed in the next sections. \subsection{Inline (In-text) Equations} A formula that appears in the running text is called an inline or in-text formula. It is produced by the \textbf{math} environment, which can be invoked with the usual \texttt{{\char'134}begin\,\ldots{\char'134}end} construction or with the short form \texttt{\$\,\ldots\$}. You can use any of the symbols and structures, from $\alpha$ to $\omega$, available in \LaTeX~\cite{Lamport:LaTeX}; this section will simply show a few examples of in-text equations in context. Notice how this equation: \begin{math} \lim_{n\rightarrow \infty}x=0 \end{math}, set here in in-line math style, looks slightly different when set in display style. (See next section). \subsection{Display Equations} A numbered display equation---one set off by vertical space from the text and centered horizontally---is produced by the \textbf{equation} environment. An unnumbered display equation is produced by the \textbf{displaymath} environment. Again, in either environment, you can use any of the symbols and structures available in \LaTeX\@; this section will just give a couple of examples of display equations in context. First, consider the equation, shown as an inline equation above: \begin{equation} \lim_{n\rightarrow \infty}x=0 \end{equation} Notice how it is formatted somewhat differently in the \textbf{displaymath} environment. Now, we'll enter an unnumbered equation: \begin{displaymath} \sum_{i=0}^{\infty} x + 1 \end{displaymath} and follow it with another numbered equation: \begin{equation} \sum_{i=0}^{\infty}x_i=\int_{0}^{\pi+2} f \end{equation} just to demonstrate \LaTeX's able handling of numbering. \section{Figures} The ``\verb|figure|'' environment should be used for figures. One or more images can be placed within a figure. If your figure contains third-party material, you must clearly identify it as such, as shown in the example below. \begin{figure}[h] \centering \includegraphics[width=\linewidth]{sample-franklin} \caption{1907 Franklin Model D roadster. Photograph by Harris \& Ewing, Inc. [Public domain], via Wikimedia Commons. (\url{https://goo.gl/VLCRBB}).} \Description{A woman and a girl in white dresses sit in an open car.} \end{figure} Your figures should contain a caption which describes the figure to the reader. Figure captions are placed {\itshape below} the figure. Every figure should also have a figure description unless it is purely decorative. These descriptions convey what’s in the image to someone who cannot see it. They are also used by search engine crawlers for indexing images, and when images cannot be loaded. A figure description must be unformatted plain text less than 2000 characters long (including spaces). {\bfseries Figure descriptions should not repeat the figure caption – their purpose is to capture important information that is not already provided in the caption or the main text of the paper.} For figures that convey important and complex new information, a short text description may not be adequate. More complex alternative descriptions can be placed in an appendix and referenced in a short figure description. For example, provide a data table capturing the information in a bar chart, or a structured list representing a graph. For additional information regarding how best to write figure descriptions and why doing this is so important, please see \url{https://www.acm.org/publications/taps/describing-figures/}. \subsection{The ``Teaser Figure''} A ``teaser figure'' is an image, or set of images in one figure, that are placed after all author and affiliation information, and before the body of the article, spanning the page. If you wish to have such a figure in your article, place the command immediately before the \verb|\maketitle| command: \begin{verbatim} \begin{teaserfigure} \includegraphics[width=\textwidth]{sampleteaser} \caption{figure caption} \Description{figure description} \end{teaserfigure} \end{verbatim} \section{Citations and Bibliographies} The use of \BibTeX\ for the preparation and formatting of one's references is strongly recommended. Authors' names should be complete --- use full first names (``Donald E. Knuth'') not initials (``D. E. Knuth'') --- and the salient identifying features of a reference should be included: title, year, volume, number, pages, article DOI, etc. The bibliography is included in your source document with these two commands, placed just before the \verb|\end{document}| command: \begin{verbatim} \bibliographystyle{ACM-Reference-Format} \section{Introduction} ACM's consolidated article template, introduced in 2017, provides a consistent \LaTeX\ style for use across ACM publications, and incorporates accessibility and metadata-extraction functionality necessary for future Digital Library endeavors. Numerous ACM and SIG-specific \LaTeX\ templates have been examined, and their unique features incorporated into this single new template. If you are new to publishing with ACM, this document is a valuable guide to the process of preparing your work for publication. If you have published with ACM before, this document provides insight and instruction into more recent changes to the article template. The ``\verb|acmart|'' document class can be used to prepare articles for any ACM publication --- conference or journal, and for any stage of publication, from review to final ``camera-ready'' copy, to the author's own version, with {\itshape very} few changes to the source. \section{Template Overview} As noted in the introduction, the ``\verb|acmart|'' document class can be used to prepare many different kinds of documentation --- a double-blind initial submission of a full-length technical paper, a two-page SIGGRAPH Emerging Technologies abstract, a ``camera-ready'' journal article, a SIGCHI Extended Abstract, and more --- all by selecting the appropriate {\itshape template style} and {\itshape template parameters}. This document will explain the major features of the document class. For further information, the {\itshape \LaTeX\ User's Guide} is available from \url{https://www.acm.org/publications/proceedings-template}. \subsection{Template Styles} The primary parameter given to the ``\verb|acmart|'' document class is the {\itshape template style} which corresponds to the kind of publication or SIG publishing the work. This parameter is enclosed in square brackets and is a part of the {\verb|documentclass|} command: \begin{verbatim} \documentclass[STYLE]{acmart} \end{verbatim} Journals use one of three template styles. All but three ACM journals use the {\verb|acmsmall|} template style: \begin{itemize} \item {\verb|acmsmall|}: The default journal template style. \item {\verb|acmlarge|}: Used by JOCCH and TAP. \item {\verb|acmtog|}: Used by TOG. \end{itemize} The majority of conference proceedings documentation will use the {\verb|acmconf|} template style. \begin{itemize} \item {\verb|acmconf|}: The default proceedings template style. \item{\verb|sigchi|}: Used for SIGCHI conference articles. \item{\verb|sigchi-a|}: Used for SIGCHI ``Extended Abstract'' articles. \item{\verb|sigplan|}: Used for SIGPLAN conference articles. \end{itemize} \subsection{Template Parameters} In addition to specifying the {\itshape template style} to be used in formatting your work, there are a number of {\itshape template parameters} which modify some part of the applied template style. A complete list of these parameters can be found in the {\itshape \LaTeX\ User's Guide.} Frequently-used parameters, or combinations of parameters, include: \begin{itemize} \item {\verb|anonymous,review|}: Suitable for a ``double-blind'' conference submission. Anonymizes the work and includes line numbers. Use with the \verb|\acmSubmissionID| command to print the submission's unique ID on each page of the work. \item{\verb|authorversion|}: Produces a version of the work suitable for posting by the author. \item{\verb|screen|}: Produces colored hyperlinks. \end{itemize} This document uses the following string as the first command in the source file: \begin{verbatim} \documentclass[sigconf]{acmart} \end{verbatim} \section{Modifications} Modifying the template --- including but not limited to: adjusting margins, typeface sizes, line spacing, paragraph and list definitions, and the use of the \verb|\vspace| command to manually adjust the vertical spacing between elements of your work --- is not allowed. {\bfseries Your document will be returned to you for revision if modifications are discovered.} \section{Typefaces} The ``\verb|acmart|'' document class requires the use of the ``Libertine'' typeface family. Your \TeX\ installation should include this set of packages. Please do not substitute other typefaces. The ``\verb|lmodern|'' and ``\verb|ltimes|'' packages should not be used, as they will override the built-in typeface families. \section{Title Information} The title of your work should use capital letters appropriately - \url{https://capitalizemytitle.com/} has useful rules for capitalization. Use the {\verb|title|} command to define the title of your work. If your work has a subtitle, define it with the {\verb|subtitle|} command. Do not insert line breaks in your title. If your title is lengthy, you must define a short version to be used in the page headers, to prevent overlapping text. The \verb|title| command has a ``short title'' parameter: \begin{verbatim} \title[short title]{full title} \end{verbatim} \section{Authors and Affiliations} Each author must be defined separately for accurate metadata identification. Multiple authors may share one affiliation. Authors' names should not be abbreviated; use full first names wherever possible. Include authors' e-mail addresses whenever possible. Grouping authors' names or e-mail addresses, or providing an ``e-mail alias,'' as shown below, is not acceptable: \begin{verbatim} \author{Brooke Aster, David Mehldau} \email{dave,judy,[email protected]} \email{[email protected]} \end{verbatim} The \verb|authornote| and \verb|authornotemark| commands allow a note to apply to multiple authors --- for example, if the first two authors of an article contributed equally to the work. If your author list is lengthy, you must define a shortened version of the list of authors to be used in the page headers, to prevent overlapping text. The following command should be placed just after the last \verb|\author{}| definition: \begin{verbatim} \renewcommand{\shortauthors}{McCartney, et al.} \end{verbatim} Omitting this command will force the use of a concatenated list of all of the authors' names, which may result in overlapping text in the page headers. The article template's documentation, available at \url{https://www.acm.org/publications/proceedings-template}, has a complete explanation of these commands and tips for their effective use. Note that authors' addresses are mandatory for journal articles. \section{Rights Information} Authors of any work published by ACM will need to complete a rights form. Depending on the kind of work, and the rights management choice made by the author, this may be copyright transfer, permission, license, or an OA (open access) agreement. Regardless of the rights management choice, the author will receive a copy of the completed rights form once it has been submitted. This form contains \LaTeX\ commands that must be copied into the source document. When the document source is compiled, these commands and their parameters add formatted text to several areas of the final document: \begin{itemize} \item the ``ACM Reference Format'' text on the first page. \item the ``rights management'' text on the first page. \item the conference information in the page header(s). \end{itemize} Rights information is unique to the work; if you are preparing several works for an event, make sure to use the correct set of commands with each of the works. The ACM Reference Format text is required for all articles over one page in length, and is optional for one-page articles (abstracts). \section{CCS Concepts and User-Defined Keywords} Two elements of the ``acmart'' document class provide powerful taxonomic tools for you to help readers find your work in an online search. The ACM Computing Classification System --- \url{https://www.acm.org/publications/class-2012} --- is a set of classifiers and concepts that describe the computing discipline. Authors can select entries from this classification system, via \url{https://dl.acm.org/ccs/ccs.cfm}, and generate the commands to be included in the \LaTeX\ source. User-defined keywords are a comma-separated list of words and phrases of the authors' choosing, providing a more flexible way of describing the research being presented. CCS concepts and user-defined keywords are required for for all articles over two pages in length, and are optional for one- and two-page articles (or abstracts). \section{Sectioning Commands} Your work should use standard \LaTeX\ sectioning commands: \verb|section|, \verb|subsection|, \verb|subsubsection|, and \verb|paragraph|. They should be numbered; do not remove the numbering from the commands. Simulating a sectioning command by setting the first word or words of a paragraph in boldface or italicized text is {\bfseries not allowed.} \section{Tables} The ``\verb|acmart|'' document class includes the ``\verb|booktabs|'' package --- \url{https://ctan.org/pkg/booktabs} --- for preparing high-quality tables. Table captions are placed {\itshape above} the table. Because tables cannot be split across pages, the best placement for them is typically the top of the page nearest their initial cite. To ensure this proper ``floating'' placement of tables, use the environment \textbf{table} to enclose the table's contents and the table caption. The contents of the table itself must go in the \textbf{tabular} environment, to be aligned properly in rows and columns, with the desired horizontal and vertical rules. Again, detailed instructions on \textbf{tabular} material are found in the \textit{\LaTeX\ User's Guide}. Immediately following this sentence is the point at which Table~\ref{tab:freq} is included in the input file; compare the placement of the table here with the table in the printed output of this document. \begin{table} \caption{Frequency of Special Characters} \label{tab:freq} \begin{tabular}{ccl} \toprule Non-English or Math&Frequency&Comments\\ \midrule \O & 1 in 1,000& For Swedish names\\ $\pi$ & 1 in 5& Common in math\\ \$ & 4 in 5 & Used in business\\ $\Psi^2_1$ & 1 in 40,000& Unexplained usage\\ \bottomrule \end{tabular} \end{table} To set a wider table, which takes up the whole width of the page's live area, use the environment \textbf{table*} to enclose the table's contents and the table caption. As with a single-column table, this wide table will ``float'' to a location deemed more desirable. Immediately following this sentence is the point at which Table~\ref{tab:commands} is included in the input file; again, it is instructive to compare the placement of the table here with the table in the printed output of this document. \begin{table*} \caption{Some Typical Commands} \label{tab:commands} \begin{tabular}{ccl} \toprule Command &A Number & Comments\\ \midrule \texttt{{\char'134}author} & 100& Author \\ \texttt{{\char'134}table}& 300 & For tables\\ \texttt{{\char'134}table*}& 400& For wider tables\\ \bottomrule \end{tabular} \end{table*} Always use midrule to separate table header rows from data rows, and use it only for this purpose. This enables assistive technologies to recognise table headers and support their users in navigating tables more easily. \section{Math Equations} You may want to display math equations in three distinct styles: inline, numbered or non-numbered display. Each of the three are discussed in the next sections. \subsection{Inline (In-text) Equations} A formula that appears in the running text is called an inline or in-text formula. It is produced by the \textbf{math} environment, which can be invoked with the usual \texttt{{\char'134}begin\,\ldots{\char'134}end} construction or with the short form \texttt{\$\,\ldots\$}. You can use any of the symbols and structures, from $\alpha$ to $\omega$, available in \LaTeX~\cite{Lamport:LaTeX}; this section will simply show a few examples of in-text equations in context. Notice how this equation: \begin{math} \lim_{n\rightarrow \infty}x=0 \end{math}, set here in in-line math style, looks slightly different when set in display style. (See next section). \subsection{Display Equations} A numbered display equation---one set off by vertical space from the text and centered horizontally---is produced by the \textbf{equation} environment. An unnumbered display equation is produced by the \textbf{displaymath} environment. Again, in either environment, you can use any of the symbols and structures available in \LaTeX\@; this section will just give a couple of examples of display equations in context. First, consider the equation, shown as an inline equation above: \begin{equation} \lim_{n\rightarrow \infty}x=0 \end{equation} Notice how it is formatted somewhat differently in the \textbf{displaymath} environment. Now, we'll enter an unnumbered equation: \begin{displaymath} \sum_{i=0}^{\infty} x + 1 \end{displaymath} and follow it with another numbered equation: \begin{equation} \sum_{i=0}^{\infty}x_i=\int_{0}^{\pi+2} f \end{equation} just to demonstrate \LaTeX's able handling of numbering. \section{Figures} The ``\verb|figure|'' environment should be used for figures. One or more images can be placed within a figure. If your figure contains third-party material, you must clearly identify it as such, as shown in the example below. \begin{figure}[h] \centering \includegraphics[width=\linewidth]{sample-franklin} \caption{1907 Franklin Model D roadster. Photograph by Harris \& Ewing, Inc. [Public domain], via Wikimedia Commons. (\url{https://goo.gl/VLCRBB}).} \Description{A woman and a girl in white dresses sit in an open car.} \end{figure} Your figures should contain a caption which describes the figure to the reader. Figure captions are placed {\itshape below} the figure. Every figure should also have a figure description unless it is purely decorative. These descriptions convey what’s in the image to someone who cannot see it. They are also used by search engine crawlers for indexing images, and when images cannot be loaded. A figure description must be unformatted plain text less than 2000 characters long (including spaces). {\bfseries Figure descriptions should not repeat the figure caption – their purpose is to capture important information that is not already provided in the caption or the main text of the paper.} For figures that convey important and complex new information, a short text description may not be adequate. More complex alternative descriptions can be placed in an appendix and referenced in a short figure description. For example, provide a data table capturing the information in a bar chart, or a structured list representing a graph. For additional information regarding how best to write figure descriptions and why doing this is so important, please see \url{https://www.acm.org/publications/taps/describing-figures/}. \subsection{The ``Teaser Figure''} A ``teaser figure'' is an image, or set of images in one figure, that are placed after all author and affiliation information, and before the body of the article, spanning the page. If you wish to have such a figure in your article, place the command immediately before the \verb|\maketitle| command: \begin{verbatim} \begin{teaserfigure} \includegraphics[width=\textwidth]{sampleteaser} \caption{figure caption} \Description{figure description} \end{teaserfigure} \end{verbatim} \section{Citations and Bibliographies} The use of \BibTeX\ for the preparation and formatting of one's references is strongly recommended. Authors' names should be complete --- use full first names (``Donald E. Knuth'') not initials (``D. E. Knuth'') --- and the salient identifying features of a reference should be included: title, year, volume, number, pages, article DOI, etc. The bibliography is included in your source document with these two commands, placed just before the \verb|\end{document}| command: \begin{verbatim} \bibliographystyle{ACM-Reference-Format} \section{Introduction} ACM's consolidated article template, introduced in 2017, provides a consistent \LaTeX\ style for use across ACM publications, and incorporates accessibility and metadata-extraction functionality necessary for future Digital Library endeavors. Numerous ACM and SIG-specific \LaTeX\ templates have been examined, and their unique features incorporated into this single new template. If you are new to publishing with ACM, this document is a valuable guide to the process of preparing your work for publication. If you have published with ACM before, this document provides insight and instruction into more recent changes to the article template. The ``\verb|acmart|'' document class can be used to prepare articles for any ACM publication --- conference or journal, and for any stage of publication, from review to final ``camera-ready'' copy, to the author's own version, with {\itshape very} few changes to the source. \section{Template Overview} As noted in the introduction, the ``\verb|acmart|'' document class can be used to prepare many different kinds of documentation --- a double-blind initial submission of a full-length technical paper, a two-page SIGGRAPH Emerging Technologies abstract, a ``camera-ready'' journal article, a SIGCHI Extended Abstract, and more --- all by selecting the appropriate {\itshape template style} and {\itshape template parameters}. This document will explain the major features of the document class. For further information, the {\itshape \LaTeX\ User's Guide} is available from \url{https://www.acm.org/publications/proceedings-template}. \subsection{Template Styles} The primary parameter given to the ``\verb|acmart|'' document class is the {\itshape template style} which corresponds to the kind of publication or SIG publishing the work. This parameter is enclosed in square brackets and is a part of the {\verb|documentclass|} command: \begin{verbatim} \documentclass[STYLE]{acmart} \end{verbatim} Journals use one of three template styles. All but three ACM journals use the {\verb|acmsmall|} template style: \begin{itemize} \item {\verb|acmsmall|}: The default journal template style. \item {\verb|acmlarge|}: Used by JOCCH and TAP. \item {\verb|acmtog|}: Used by TOG. \end{itemize} The majority of conference proceedings documentation will use the {\verb|acmconf|} template style. \begin{itemize} \item {\verb|acmconf|}: The default proceedings template style. \item{\verb|sigchi|}: Used for SIGCHI conference articles. \item{\verb|sigchi-a|}: Used for SIGCHI ``Extended Abstract'' articles. \item{\verb|sigplan|}: Used for SIGPLAN conference articles. \end{itemize} \subsection{Template Parameters} In addition to specifying the {\itshape template style} to be used in formatting your work, there are a number of {\itshape template parameters} which modify some part of the applied template style. A complete list of these parameters can be found in the {\itshape \LaTeX\ User's Guide.} Frequently-used parameters, or combinations of parameters, include: \begin{itemize} \item {\verb|anonymous,review|}: Suitable for a ``double-blind'' conference submission. Anonymizes the work and includes line numbers. Use with the \verb|\acmSubmissionID| command to print the submission's unique ID on each page of the work. \item{\verb|authorversion|}: Produces a version of the work suitable for posting by the author. \item{\verb|screen|}: Produces colored hyperlinks. \end{itemize} This document uses the following string as the first command in the source file: \begin{verbatim} \documentclass[sigconf]{acmart} \end{verbatim} \section{Modifications} Modifying the template --- including but not limited to: adjusting margins, typeface sizes, line spacing, paragraph and list definitions, and the use of the \verb|\vspace| command to manually adjust the vertical spacing between elements of your work --- is not allowed. {\bfseries Your document will be returned to you for revision if modifications are discovered.} \section{Typefaces} The ``\verb|acmart|'' document class requires the use of the ``Libertine'' typeface family. Your \TeX\ installation should include this set of packages. Please do not substitute other typefaces. The ``\verb|lmodern|'' and ``\verb|ltimes|'' packages should not be used, as they will override the built-in typeface families. \section{Title Information} The title of your work should use capital letters appropriately - \url{https://capitalizemytitle.com/} has useful rules for capitalization. Use the {\verb|title|} command to define the title of your work. If your work has a subtitle, define it with the {\verb|subtitle|} command. Do not insert line breaks in your title. If your title is lengthy, you must define a short version to be used in the page headers, to prevent overlapping text. The \verb|title| command has a ``short title'' parameter: \begin{verbatim} \title[short title]{full title} \end{verbatim} \section{Authors and Affiliations} Each author must be defined separately for accurate metadata identification. Multiple authors may share one affiliation. Authors' names should not be abbreviated; use full first names wherever possible. Include authors' e-mail addresses whenever possible. Grouping authors' names or e-mail addresses, or providing an ``e-mail alias,'' as shown below, is not acceptable: \begin{verbatim} \author{Brooke Aster, David Mehldau} \email{dave,judy,[email protected]} \email{[email protected]} \end{verbatim} The \verb|authornote| and \verb|authornotemark| commands allow a note to apply to multiple authors --- for example, if the first two authors of an article contributed equally to the work. If your author list is lengthy, you must define a shortened version of the list of authors to be used in the page headers, to prevent overlapping text. The following command should be placed just after the last \verb|\author{}| definition: \begin{verbatim} \renewcommand{\shortauthors}{McCartney, et al.} \end{verbatim} Omitting this command will force the use of a concatenated list of all of the authors' names, which may result in overlapping text in the page headers. The article template's documentation, available at \url{https://www.acm.org/publications/proceedings-template}, has a complete explanation of these commands and tips for their effective use. Note that authors' addresses are mandatory for journal articles. \section{Rights Information} Authors of any work published by ACM will need to complete a rights form. Depending on the kind of work, and the rights management choice made by the author, this may be copyright transfer, permission, license, or an OA (open access) agreement. Regardless of the rights management choice, the author will receive a copy of the completed rights form once it has been submitted. This form contains \LaTeX\ commands that must be copied into the source document. When the document source is compiled, these commands and their parameters add formatted text to several areas of the final document: \begin{itemize} \item the ``ACM Reference Format'' text on the first page. \item the ``rights management'' text on the first page. \item the conference information in the page header(s). \end{itemize} Rights information is unique to the work; if you are preparing several works for an event, make sure to use the correct set of commands with each of the works. The ACM Reference Format text is required for all articles over one page in length, and is optional for one-page articles (abstracts). \section{CCS Concepts and User-Defined Keywords} Two elements of the ``acmart'' document class provide powerful taxonomic tools for you to help readers find your work in an online search. The ACM Computing Classification System --- \url{https://www.acm.org/publications/class-2012} --- is a set of classifiers and concepts that describe the computing discipline. Authors can select entries from this classification system, via \url{https://dl.acm.org/ccs/ccs.cfm}, and generate the commands to be included in the \LaTeX\ source. User-defined keywords are a comma-separated list of words and phrases of the authors' choosing, providing a more flexible way of describing the research being presented. CCS concepts and user-defined keywords are required for for all articles over two pages in length, and are optional for one- and two-page articles (or abstracts). \section{Sectioning Commands} Your work should use standard \LaTeX\ sectioning commands: \verb|section|, \verb|subsection|, \verb|subsubsection|, and \verb|paragraph|. They should be numbered; do not remove the numbering from the commands. Simulating a sectioning command by setting the first word or words of a paragraph in boldface or italicized text is {\bfseries not allowed.} \section{Tables} The ``\verb|acmart|'' document class includes the ``\verb|booktabs|'' package --- \url{https://ctan.org/pkg/booktabs} --- for preparing high-quality tables. Table captions are placed {\itshape above} the table. Because tables cannot be split across pages, the best placement for them is typically the top of the page nearest their initial cite. To ensure this proper ``floating'' placement of tables, use the environment \textbf{table} to enclose the table's contents and the table caption. The contents of the table itself must go in the \textbf{tabular} environment, to be aligned properly in rows and columns, with the desired horizontal and vertical rules. Again, detailed instructions on \textbf{tabular} material are found in the \textit{\LaTeX\ User's Guide}. Immediately following this sentence is the point at which Table~\ref{tab:freq} is included in the input file; compare the placement of the table here with the table in the printed output of this document. \begin{table} \caption{Frequency of Special Characters} \label{tab:freq} \begin{tabular}{ccl} \toprule Non-English or Math&Frequency&Comments\\ \midrule \O & 1 in 1,000& For Swedish names\\ $\pi$ & 1 in 5& Common in math\\ \$ & 4 in 5 & Used in business\\ $\Psi^2_1$ & 1 in 40,000& Unexplained usage\\ \bottomrule \end{tabular} \end{table} To set a wider table, which takes up the whole width of the page's live area, use the environment \textbf{table*} to enclose the table's contents and the table caption. As with a single-column table, this wide table will ``float'' to a location deemed more desirable. Immediately following this sentence is the point at which Table~\ref{tab:commands} is included in the input file; again, it is instructive to compare the placement of the table here with the table in the printed output of this document. \begin{table*} \caption{Some Typical Commands} \label{tab:commands} \begin{tabular}{ccl} \toprule Command &A Number & Comments\\ \midrule \texttt{{\char'134}author} & 100& Author \\ \texttt{{\char'134}table}& 300 & For tables\\ \texttt{{\char'134}table*}& 400& For wider tables\\ \bottomrule \end{tabular} \end{table*} Always use midrule to separate table header rows from data rows, and use it only for this purpose. This enables assistive technologies to recognise table headers and support their users in navigating tables more easily. \section{Math Equations} You may want to display math equations in three distinct styles: inline, numbered or non-numbered display. Each of the three are discussed in the next sections. \subsection{Inline (In-text) Equations} A formula that appears in the running text is called an inline or in-text formula. It is produced by the \textbf{math} environment, which can be invoked with the usual \texttt{{\char'134}begin\,\ldots{\char'134}end} construction or with the short form \texttt{\$\,\ldots\$}. You can use any of the symbols and structures, from $\alpha$ to $\omega$, available in \LaTeX~\cite{Lamport:LaTeX}; this section will simply show a few examples of in-text equations in context. Notice how this equation: \begin{math} \lim_{n\rightarrow \infty}x=0 \end{math}, set here in in-line math style, looks slightly different when set in display style. (See next section). \subsection{Display Equations} A numbered display equation---one set off by vertical space from the text and centered horizontally---is produced by the \textbf{equation} environment. An unnumbered display equation is produced by the \textbf{displaymath} environment. Again, in either environment, you can use any of the symbols and structures available in \LaTeX\@; this section will just give a couple of examples of display equations in context. First, consider the equation, shown as an inline equation above: \begin{equation} \lim_{n\rightarrow \infty}x=0 \end{equation} Notice how it is formatted somewhat differently in the \textbf{displaymath} environment. Now, we'll enter an unnumbered equation: \begin{displaymath} \sum_{i=0}^{\infty} x + 1 \end{displaymath} and follow it with another numbered equation: \begin{equation} \sum_{i=0}^{\infty}x_i=\int_{0}^{\pi+2} f \end{equation} just to demonstrate \LaTeX's able handling of numbering. \section{Figures} The ``\verb|figure|'' environment should be used for figures. One or more images can be placed within a figure. If your figure contains third-party material, you must clearly identify it as such, as shown in the example below. \begin{figure}[h] \centering \includegraphics[width=\linewidth]{sample-franklin} \caption{1907 Franklin Model D roadster. Photograph by Harris \& Ewing, Inc. [Public domain], via Wikimedia Commons. (\url{https://goo.gl/VLCRBB}).} \Description{A woman and a girl in white dresses sit in an open car.} \end{figure} Your figures should contain a caption which describes the figure to the reader. Figure captions are placed {\itshape below} the figure. Every figure should also have a figure description unless it is purely decorative. These descriptions convey what’s in the image to someone who cannot see it. They are also used by search engine crawlers for indexing images, and when images cannot be loaded. A figure description must be unformatted plain text less than 2000 characters long (including spaces). {\bfseries Figure descriptions should not repeat the figure caption – their purpose is to capture important information that is not already provided in the caption or the main text of the paper.} For figures that convey important and complex new information, a short text description may not be adequate. More complex alternative descriptions can be placed in an appendix and referenced in a short figure description. For example, provide a data table capturing the information in a bar chart, or a structured list representing a graph. For additional information regarding how best to write figure descriptions and why doing this is so important, please see \url{https://www.acm.org/publications/taps/describing-figures/}. \subsection{The ``Teaser Figure''} A ``teaser figure'' is an image, or set of images in one figure, that are placed after all author and affiliation information, and before the body of the article, spanning the page. If you wish to have such a figure in your article, place the command immediately before the \verb|\maketitle| command: \begin{verbatim} \begin{teaserfigure} \includegraphics[width=\textwidth]{sampleteaser} \caption{figure caption} \Description{figure description} \end{teaserfigure} \end{verbatim} \section{Citations and Bibliographies} The use of \BibTeX\ for the preparation and formatting of one's references is strongly recommended. Authors' names should be complete --- use full first names (``Donald E. Knuth'') not initials (``D. E. Knuth'') --- and the salient identifying features of a reference should be included: title, year, volume, number, pages, article DOI, etc. The bibliography is included in your source document with these two commands, placed just before the \verb|\end{document}| command: \begin{verbatim} \bibliographystyle{ACM-Reference-Format} \section{Introduction} ACM's consolidated article template, introduced in 2017, provides a consistent \LaTeX\ style for use across ACM publications, and incorporates accessibility and metadata-extraction functionality necessary for future Digital Library endeavors. Numerous ACM and SIG-specific \LaTeX\ templates have been examined, and their unique features incorporated into this single new template. If you are new to publishing with ACM, this document is a valuable guide to the process of preparing your work for publication. If you have published with ACM before, this document provides insight and instruction into more recent changes to the article template. The ``\verb|acmart|'' document class can be used to prepare articles for any ACM publication --- conference or journal, and for any stage of publication, from review to final ``camera-ready'' copy, to the author's own version, with {\itshape very} few changes to the source. \section{Template Overview} As noted in the introduction, the ``\verb|acmart|'' document class can be used to prepare many different kinds of documentation --- a double-blind initial submission of a full-length technical paper, a two-page SIGGRAPH Emerging Technologies abstract, a ``camera-ready'' journal article, a SIGCHI Extended Abstract, and more --- all by selecting the appropriate {\itshape template style} and {\itshape template parameters}. This document will explain the major features of the document class. For further information, the {\itshape \LaTeX\ User's Guide} is available from \url{https://www.acm.org/publications/proceedings-template}. \subsection{Template Styles} The primary parameter given to the ``\verb|acmart|'' document class is the {\itshape template style} which corresponds to the kind of publication or SIG publishing the work. This parameter is enclosed in square brackets and is a part of the {\verb|documentclass|} command: \begin{verbatim} \documentclass[STYLE]{acmart} \end{verbatim} Journals use one of three template styles. All but three ACM journals use the {\verb|acmsmall|} template style: \begin{itemize} \item {\verb|acmsmall|}: The default journal template style. \item {\verb|acmlarge|}: Used by JOCCH and TAP. \item {\verb|acmtog|}: Used by TOG. \end{itemize} The majority of conference proceedings documentation will use the {\verb|acmconf|} template style. \begin{itemize} \item {\verb|acmconf|}: The default proceedings template style. \item{\verb|sigchi|}: Used for SIGCHI conference articles. \item{\verb|sigchi-a|}: Used for SIGCHI ``Extended Abstract'' articles. \item{\verb|sigplan|}: Used for SIGPLAN conference articles. \end{itemize} \subsection{Template Parameters} In addition to specifying the {\itshape template style} to be used in formatting your work, there are a number of {\itshape template parameters} which modify some part of the applied template style. A complete list of these parameters can be found in the {\itshape \LaTeX\ User's Guide.} Frequently-used parameters, or combinations of parameters, include: \begin{itemize} \item {\verb|anonymous,review|}: Suitable for a ``double-blind'' conference submission. Anonymizes the work and includes line numbers. Use with the \verb|\acmSubmissionID| command to print the submission's unique ID on each page of the work. \item{\verb|authorversion|}: Produces a version of the work suitable for posting by the author. \item{\verb|screen|}: Produces colored hyperlinks. \end{itemize} This document uses the following string as the first command in the source file: \begin{verbatim} \documentclass[acmtog]{acmart} \end{verbatim} \section{Modifications} Modifying the template --- including but not limited to: adjusting margins, typeface sizes, line spacing, paragraph and list definitions, and the use of the \verb|\vspace| command to manually adjust the vertical spacing between elements of your work --- is not allowed. {\bfseries Your document will be returned to you for revision if modifications are discovered.} \section{Typefaces} The ``\verb|acmart|'' document class requires the use of the ``Libertine'' typeface family. Your \TeX\ installation should include this set of packages. Please do not substitute other typefaces. The ``\verb|lmodern|'' and ``\verb|ltimes|'' packages should not be used, as they will override the built-in typeface families. \section{Title Information} The title of your work should use capital letters appropriately - \url{https://capitalizemytitle.com/} has useful rules for capitalization. Use the {\verb|title|} command to define the title of your work. If your work has a subtitle, define it with the {\verb|subtitle|} command. Do not insert line breaks in your title. If your title is lengthy, you must define a short version to be used in the page headers, to prevent overlapping text. The \verb|title| command has a ``short title'' parameter: \begin{verbatim} \title[short title]{full title} \end{verbatim} \section{Authors and Affiliations} Each author must be defined separately for accurate metadata identification. Multiple authors may share one affiliation. Authors' names should not be abbreviated; use full first names wherever possible. Include authors' e-mail addresses whenever possible. Grouping authors' names or e-mail addresses, or providing an ``e-mail alias,'' as shown below, is not acceptable: \begin{verbatim} \author{Brooke Aster, David Mehldau} \email{dave,judy,[email protected]} \email{[email protected]} \end{verbatim} The \verb|authornote| and \verb|authornotemark| commands allow a note to apply to multiple authors --- for example, if the first two authors of an article contributed equally to the work. If your author list is lengthy, you must define a shortened version of the list of authors to be used in the page headers, to prevent overlapping text. The following command should be placed just after the last \verb|\author{}| definition: \begin{verbatim} \renewcommand{\shortauthors}{McCartney, et al.} \end{verbatim} Omitting this command will force the use of a concatenated list of all of the authors' names, which may result in overlapping text in the page headers. The article template's documentation, available at \url{https://www.acm.org/publications/proceedings-template}, has a complete explanation of these commands and tips for their effective use. Note that authors' addresses are mandatory for journal articles. \section{Rights Information} Authors of any work published by ACM will need to complete a rights form. Depending on the kind of work, and the rights management choice made by the author, this may be copyright transfer, permission, license, or an OA (open access) agreement. Regardless of the rights management choice, the author will receive a copy of the completed rights form once it has been submitted. This form contains \LaTeX\ commands that must be copied into the source document. When the document source is compiled, these commands and their parameters add formatted text to several areas of the final document: \begin{itemize} \item the ``ACM Reference Format'' text on the first page. \item the ``rights management'' text on the first page. \item the conference information in the page header(s). \end{itemize} Rights information is unique to the work; if you are preparing several works for an event, make sure to use the correct set of commands with each of the works. The ACM Reference Format text is required for all articles over one page in length, and is optional for one-page articles (abstracts). \section{CCS Concepts and User-Defined Keywords} Two elements of the ``acmart'' document class provide powerful taxonomic tools for you to help readers find your work in an online search. The ACM Computing Classification System --- \url{https://www.acm.org/publications/class-2012} --- is a set of classifiers and concepts that describe the computing discipline. Authors can select entries from this classification system, via \url{https://dl.acm.org/ccs/ccs.cfm}, and generate the commands to be included in the \LaTeX\ source. User-defined keywords are a comma-separated list of words and phrases of the authors' choosing, providing a more flexible way of describing the research being presented. CCS concepts and user-defined keywords are required for for all articles over two pages in length, and are optional for one- and two-page articles (or abstracts). \section{Sectioning Commands} Your work should use standard \LaTeX\ sectioning commands: \verb|section|, \verb|subsection|, \verb|subsubsection|, and \verb|paragraph|. They should be numbered; do not remove the numbering from the commands. Simulating a sectioning command by setting the first word or words of a paragraph in boldface or italicized text is {\bfseries not allowed.} \section{Tables} The ``\verb|acmart|'' document class includes the ``\verb|booktabs|'' package --- \url{https://ctan.org/pkg/booktabs} --- for preparing high-quality tables. Table captions are placed {\itshape above} the table. Because tables cannot be split across pages, the best placement for them is typically the top of the page nearest their initial cite. To ensure this proper ``floating'' placement of tables, use the environment \textbf{table} to enclose the table's contents and the table caption. The contents of the table itself must go in the \textbf{tabular} environment, to be aligned properly in rows and columns, with the desired horizontal and vertical rules. Again, detailed instructions on \textbf{tabular} material are found in the \textit{\LaTeX\ User's Guide}. Immediately following this sentence is the point at which Table~\ref{tab:freq} is included in the input file; compare the placement of the table here with the table in the printed output of this document. \begin{table} \caption{Frequency of Special Characters} \label{tab:freq} \begin{tabular}{ccl} \toprule Non-English or Math&Frequency&Comments\\ \midrule \O & 1 in 1,000& For Swedish names\\ $\pi$ & 1 in 5& Common in math\\ \$ & 4 in 5 & Used in business\\ $\Psi^2_1$ & 1 in 40,000& Unexplained usage\\ \bottomrule \end{tabular} \end{table} To set a wider table, which takes up the whole width of the page's live area, use the environment \textbf{table*} to enclose the table's contents and the table caption. As with a single-column table, this wide table will ``float'' to a location deemed more desirable. Immediately following this sentence is the point at which Table~\ref{tab:commands} is included in the input file; again, it is instructive to compare the placement of the table here with the table in the printed output of this document. \begin{table*} \caption{Some Typical Commands} \label{tab:commands} \begin{tabular}{ccl} \toprule Command &A Number & Comments\\ \midrule \texttt{{\char'134}author} & 100& Author \\ \texttt{{\char'134}table}& 300 & For tables\\ \texttt{{\char'134}table*}& 400& For wider tables\\ \bottomrule \end{tabular} \end{table*} Always use midrule to separate table header rows from data rows, and use it only for this purpose. This enables assistive technologies to recognise table headers and support their users in navigating tables more easily. \section{Math Equations} You may want to display math equations in three distinct styles: inline, numbered or non-numbered display. Each of the three are discussed in the next sections. \subsection{Inline (In-text) Equations} A formula that appears in the running text is called an inline or in-text formula. It is produced by the \textbf{math} environment, which can be invoked with the usual \texttt{{\char'134}begin\,\ldots{\char'134}end} construction or with the short form \texttt{\$\,\ldots\$}. You can use any of the symbols and structures, from $\alpha$ to $\omega$, available in \LaTeX~\cite{Lamport:LaTeX}; this section will simply show a few examples of in-text equations in context. Notice how this equation: \begin{math} \lim_{n\rightarrow \infty}x=0 \end{math}, set here in in-line math style, looks slightly different when set in display style. (See next section). \subsection{Display Equations} A numbered display equation---one set off by vertical space from the text and centered horizontally---is produced by the \textbf{equation} environment. An unnumbered display equation is produced by the \textbf{displaymath} environment. Again, in either environment, you can use any of the symbols and structures available in \LaTeX\@; this section will just give a couple of examples of display equations in context. First, consider the equation, shown as an inline equation above: \begin{equation} \lim_{n\rightarrow \infty}x=0 \end{equation} Notice how it is formatted somewhat differently in the \textbf{displaymath} environment. Now, we'll enter an unnumbered equation: \begin{displaymath} \sum_{i=0}^{\infty} x + 1 \end{displaymath} and follow it with another numbered equation: \begin{equation} \sum_{i=0}^{\infty}x_i=\int_{0}^{\pi+2} f \end{equation} just to demonstrate \LaTeX's able handling of numbering. \section{Figures} The ``\verb|figure|'' environment should be used for figures. One or more images can be placed within a figure. If your figure contains third-party material, you must clearly identify it as such, as shown in the example below. \begin{figure}[h] \centering \includegraphics[width=\linewidth]{sample-franklin} \caption{1907 Franklin Model D roadster. Photograph by Harris \& Ewing, Inc. [Public domain], via Wikimedia Commons. (\url{https://goo.gl/VLCRBB}).} \Description{A woman and a girl in white dresses sit in an open car.} \end{figure} Your figures should contain a caption which describes the figure to the reader. Figure captions are placed {\itshape below} the figure. Every figure should also have a figure description unless it is purely decorative. These descriptions convey what’s in the image to someone who cannot see it. They are also used by search engine crawlers for indexing images, and when images cannot be loaded. A figure description must be unformatted plain text less than 2000 characters long (including spaces). {\bfseries Figure descriptions should not repeat the figure caption – their purpose is to capture important information that is not already provided in the caption or the main text of the paper.} For figures that convey important and complex new information, a short text description may not be adequate. More complex alternative descriptions can be placed in an appendix and referenced in a short figure description. For example, provide a data table capturing the information in a bar chart, or a structured list representing a graph. For additional information regarding how best to write figure descriptions and why doing this is so important, please see \url{https://www.acm.org/publications/taps/describing-figures/}. \subsection{The ``Teaser Figure''} A ``teaser figure'' is an image, or set of images in one figure, that are placed after all author and affiliation information, and before the body of the article, spanning the page. If you wish to have such a figure in your article, place the command immediately before the \verb|\maketitle| command: \begin{verbatim} \begin{teaserfigure} \includegraphics[width=\textwidth]{sampleteaser} \caption{figure caption} \Description{figure description} \end{teaserfigure} \end{verbatim} \section{Citations and Bibliographies} The use of \BibTeX\ for the preparation and formatting of one's references is strongly recommended. Authors' names should be complete --- use full first names (``Donald E. Knuth'') not initials (``D. E. Knuth'') --- and the salient identifying features of a reference should be included: title, year, volume, number, pages, article DOI, etc. The bibliography is included in your source document with these two commands, placed just before the \verb|\end{document}| command: \begin{verbatim} \bibliographystyle{ACM-Reference-Format} \section{Introduction} Graph node representation learning aims to represent nodes from graph structure data into lower dimensional vectors and has received much attention in recent years \cite{perozzi2014deepwalk,grover2016node2vec,rossi2013modeling,trivedi2018dyrep,hamilton2017inductive,kipf2017semi,hamilton2017representation}. Effective methods have been successfully applied to many real-world applications where graphs are large-scale and static \cite{ying2018graph}. However, networks such as social networks \cite{berger2006framework}, knowledge graphs \cite{ji2015knowledge}, and citation networks \cite{clement2019use} are usually time-evolving where edges and nodes are inserted or deleted over time. Computing representations of all vertices over time is prohibitively expensive because only a small subset of nodes may be interesting in a particular application. Therefore, it is important and technical challenging to efficiently learn dynamic embeddings for these large-scale dynamic networks under this typical use case. \begin{figure} \centering \subfloat[Dynamic graph model]{\includegraphics[width=3.3cm]{figs/dynamic-ppe.pdf}}\quad \subfloat[\vspace{-2mm}An application of \textsc{DynamicPPE}]{\includegraphics[width=4.7cm]{figs/embedding-movement-example.pdf}} \caption{ (a) The model of dynamic network in two consecutive snapshots. (b) An application of \textsc{DynamicPPE} to keep track embedding movements of interesting Wikipedia articles (vertices). We learn embeddings of two presidents of the United States on the whole English Wikipedia graph from 2012 monthly, which cumulatively involves 6.2M articles (nodes) and 170M internal links (edges). The \textit{embedding movement} between two time points is defined as $1-\cos(\bm w_v^t, \bm w_v^{t+1})$ where $\cos(\cdot,\cdot)$ is the cosine similarity. The significant embedding movements may reflect big social status changes of Donald\_Trump and Joe\_Biden \protect\footnotemark in this dynamic Wikipedia graph.\vspace{-5mm}} \label{fig:example-model} \end{figure} \footnotetext{Two English Wikipedia articles are accessible at \textcolor{blue}{\url{https://en.wikipedia.org/wiki/Donald_Trump}} and \textcolor{blue}{\url{https://en.wikipedia.org/wiki/Joe_Biden}}.} Specifically, we study the following dynamic embedding problem: We are given a subset $S=\{v_1,v_2,\ldots, v_k\}$ and an initial graph $\mathcal{G}^t$ with $t=0$. Between time $t$ and $t+1$, there are edge events of insertions and/or deletions. The task is to design an algorithm to learn embeddings for $k$ nodes with time complexity independent on the number of nodes $n$ per time $t$ where $k \ll n$. This problem setting is both technically challenging and practically important. For example, in the English Wikipedia graph, one need focus only on embedding movements of articles related to political leaders, a tiny portion of whole Wikipedia. Current dynamic embedding methods \cite{du2018dynamic,zhou2018dynamic,zhang2018billion,nguyen2018continuous,zhu2016scalable} are not applicable to this large-scale problem setting due to the lack of efficiency. More specifically, current methods have the \textit{dependence issue} where one must learn all embedding vectors. This dependence issue leads to per-embedding update is linear-dependent on $n$, which is inefficient when graphs are large-scale. This obstacle motivates us to develop a new method. In this paper, we propose a dynamic personalized PageRank embedding (\textsc{DynamicPPE}) method for learning a subset of node representations over large-sale dynamic networks. \textsc{DynamicPPE} is based on an effective approach to compute dynamic PPVs \cite{zhang2016approximate}. There are two challenges of using \citet{zhang2016approximate} directly: 1) the quality of dynamic PPVs depend critically on precision parameter $\epsilon$, which unfortunately is unknown under the dynamic setting; and 2) The update of per-edge event strategy is not suitable for batch update between graph snapshots. To resolve these two difficulties, first, we adaptively update $\epsilon$ so that the \textit{estimation error} is independent of $n,m$, thus obtaining high quality PPVs. Yet previous work does not give an estimation error guarantee. We prove that the time complexity is only dependent on $\bar{d}$. Second, we incorporate a batch update strategy inspired from \cite{guo2017parallel} to avoid frequent per-edge update. Therefore, the total run time to keep track of $k$ nodes for given snapshots is $\mathcal{O}(k \bar{d} m)$. Since real-world graphs have the sparsity property $\bar{d} \ll n $, it significantly improves the efficiency compared with previous methods. Inspired by \textit{InstantEmbedding} \cite{postuavaru2020instantembedding} for static graph, we use hash kernels to project dynamic PPVs into embedding space. Figure \ref{fig:example-model} shows an example of successfully applying \textsc{DynamicPPE} to study the dynamics of social status in the English Wikipedia graph. To summarize, our contributions are: \begin{enumerate}[leftmargin=*] \item We propose a new algorithm \textsc{DynamicPPE}, which is based on the recent advances of local network embedding on static graph and a novel computation of dynamic PPVs. \textsc{DynamicPPE} effectively learns PPVs and then projects them into embedding space using hash kernels. \item \textsc{DynamicPPE} adaptively updates the precision parameter $\epsilon$ so that PPVs always have a provable estimation error guarantee. In our subset problem setting, we prove that the time and space complexity are all linear to the number of edges $m$ but independent on the number of nodes $n$, thus significantly improve the efficiency. \item Node classification results demonstrate the effectiveness and efficiency of the proposed. We compile three large-scale datasets to validate our method. As an application, we showcase that learned embeddings can be used to detect the changes of Chinese cities during this ongoing COVID-19 pandemic articles on a large-scale English Wikipedia. \end{enumerate} The rest of this paper is organized as follows: In Section \ref{sec:related-work}, we give the overview of current dynamic embedding methods. The problem definition and preliminaries are in Section \ref{sec:defintions}. We present our proposed method in Section \ref{sec:proposed}. Experimental results are reported in Section \ref{sec:experiments}. The discussion and conclusion will be presented in Section \ref{sec:conclusion}. Our code and created datasets are accessible at \textcolor{blue}{\url{https://github.com/zjlxgxz/DynamicPPE}}. \section{Related Work} \label{sec:related-work} There are two main categories of works for learning embeddings from the dynamic graph structure data. The first type is focusing on capturing the evolution of dynamics of graph structure \cite{zhou2018dynamic}. The second type is focusing on both dynamics of graph structure and features lie in these graph data \cite{trivedi2019dyrep}. In this paper, we focus on the first type and give the overview of related works. Due to the large mount of works in this area, some related works may not be included, one can find more related works in a survey \cite{kazemi2020representation} and references therein. \noindent\textbf{Dynamic latent space models}\quad The dynamic embedding models had been initially explored by using latent space model \cite{hoff2002latent}. The dynamic latent space model of a network makes an assumption that each node is associated with an $d$-dimensional vector and distance between two vectors should be small if there is an edge between these two nodes \cite{sarkar2005dynamic-kdd,sarkar2005dynamic-nips}. Works of these assume that the distance between two consecutive embeddings should be small. The proposed dynamic models were applied to different applications \cite{sarkar2007latent,hoff2007modeling}. Their methods are not scalable from the fact that the time complexity of initial position estimation is at least $\mathcal{O}(n^2)$ even if the per-node update is $\log(n)$. \noindent\textbf{Incremental SVD and random walk based methods} \quad \citet{zhang2018timers} proposed \textsc{TIMERS} that is an incremental SVD-based method. To prevent the error accumulation, \textsc{TIMERS} properly set the restart time so that the accumulated error can be reduced. \citet{nguyen2018continuous} proposed continuous-time dynamic network embeddings, namely CTDNE. The key idea of CTNDE is that instead of using general random walks as DeepWalk \cite{perozzi2014deepwalk}, it uses temporal random walks contain a sequence of edges in order. Similarly, the work of \citet{du2018dynamic} was also based on the idea of DeepWalk. These methods have time complexity dependent on $n$ for per-snapshot update. \citet{zhou2018dynamic} proposed to learn dynamic embeddings by modeling the triadic closure to capture the dynamics. \noindent\textbf{Graph neural network methods} \citet{trivedi2019dyrep} designed a dynamic node representation model, namely \textsc{DyRep}, as modeling a latent mediation process where it leverages the changes of node between the node's social interactions and its neighborhoods. More specifically, \textsc{DyRep} contains a temporal attention layer to capture the interactions of neighbors. \citet{zang2020neural} proposed a neural network model to learn embeddings by solving a differential equation with ReLU as its activation function. \citep{kumar2019predicting} presents a dynamic embedding, a recurrent neural network method, to learn the interactions between users and items. However, these methods either need to have features as input or cannot be applied to large-scale dynamic graph. \citet{kumar2019predicting} proposed an algorithm to learn the trajectory of the dynamic embedding for temporal interaction networks. Since the learning task is different from ours, one can find more details in their paper. \section{Notations and preliminaries} \label{sec:defintions} \textbf{Notations}\quad We use $[n]$ to denote a ground set $[n]:=\{ 0,1, \ldots, n-1\}$. The graph snapshot at time $t$ is denoted as $\mathcal{G}^t\left(\mathbb{V}^t,\mathbb{E}^t\right)$. The degree of a node $v$ is $d(v)^t$. In the rest of this paper, the average degree at time $t$ is $\bar{d}^t$ and the subset of target nodes is $S\subseteq \mathbb{V}^t$. Bold capitals, e.g. $\bm A, \bm W$ are matrices and bold lower letters are vectors $\bm w,\bm x$. More specifically, the embedding vector for node $v$ at time $t$ denoted as $\bm w_v^t \in \mathbb{R}^d$ and $d$ is the embedding dimension. The $i$-th entry of $\bm w_v^t$ is $w_v^t(i) \in \mathbb{R}$. The embedding of node $v$ for all $T$ snapshots is written as $\bm W_v = [\bm w_v^1,\bm w_v^2,\ldots, \bm w_v^T]^\top$. We use $n_t$ and $m_t$ as the number of nodes and edges in $\mathcal{G}^t$ which we simply use $n$ and $m$ if time $t$ is clear in the context. Given the graph snapshot $\mathcal{G}^t$ and a specific node $v$, the personalized PageRank vector (PPV) is an $n$-dimensional vector $\bm \pi_v^t \in \mathbb{R}^{n}$ and the corresponding $i$-th entry is $\pi_v^t(i)$. We use $\bm p_v^t \in \mathbb{R}^{n}$ to stand for a calculated PPV obtained from a specific algorithm. Similarly, the corresponding $i$-th entry is $p_v^t(i)$. The teleport probability of the PageRank is denoted as $\alpha$. The \textit{estimation error} of an embedding vector is the difference between true embedding $\bm w_v^t$ and the estimated embedding $\hat{\bm w}_v^t$ is measure by $\| \cdot \|_1 := \sum_{i=1}^n \left| w_v^t(i) - \hat{w}_v^t(i)\right|$. \subsection{Dynamic graph model and its embedding} Given any initial graph (could be an empty graph), the corresponding dynamic graph model describes how the graph structure evolves over time. We first define the dynamic graph model, which is based on \citet{kazemi2020representation}. \begin{definition}[Simple dynamic graph model \cite{kazemi2020representation}] \label{def:dynamic-graph-model} A simple dynamic graph model is defined as an ordered of snapshots $\mathcal{G}^0, \mathcal{G}^1$, $\mathcal{G}^2, \ldots , \mathcal{G}^T$ where $\mathcal{G}^0$ is the initial graph. The \textit{difference} of graph $\mathcal{G}^t$ at time $t=1,2,\ldots,T$ is $\Delta G^t(\Delta \mathbb{V}^t,\Delta\mathbb{E}^t) := G^t \backslash G^{t-1}$ with $\Delta \mathbb{V}^t := \mathbb{V}^t \backslash \mathbb{V}^{t-1}$ and $\Delta \mathbb{E}^t :=\mathbb{E}^t \backslash \mathbb{E}^{t-1}$. Equivalently, $\Delta \mathcal{G}^t$ corresponds to a sequence of edge events as the following \begin{equation} \Delta \mathcal{G}^t = \left\{ e_1^t,e_2^t,\ldots, e_{m^\prime}^t \right\}, \end{equation} where each edge event $e_i^t$ has two types: \textit{insertion} or \textit{deletion}, i.e, $ e_i^t = \left(u,v, \operatorname{event} \right)$ where $\operatorname{event} \in \{ \operatorname{Insert}, \operatorname{Delete}\}$ \footnote{The node insertion can be treated as inserting a new edge and then delete it and node deletion is a sequence of deleting its edges.}. \end{definition} The above model captures evolution of a real-world graph naturally where the structure evolution can be treated as a sequence of edge events occurred in this graph. To simplify our analysis, we assume that the graph is undirected. Based on this, we define the subset dynamic representation problem as the following. \begin{definition}[Subset dynamic network embedding problem] Given a dynamic network model $\left\{\mathcal{G}^0, \mathcal{G}^1, \mathcal{G}^2, \ldots, \mathcal{G}^T\right\}$ define in Definition \ref{def:dynamic-graph-model} and a subset of target nodes $S=\left\{ v_1,v_2,\ldots,v_k \right\}$, the subset dynamic network embedding problem is to learn dynamic embeddings of $T$ snapshots for all $k$ nodes $S$ where $k \ll n$. That is, given any node $v\in S$, the goal is to learn embedding matrix for each node $v \in S$, i.e. \begin{equation} \bm W_v := [\bm w_v^1,\bm w_v^2,\ldots, \bm w_v^T]^\top \text{ where }\bm w_v^t \in \mathbb{R}^d \text{ and } v \in S. \end{equation} \end{definition} \subsection{Personalized PageRank} Given any node $v$ at time $t$, the personalized PageRank vector for graph $\mathcal{G}^t$ is defined as the following \begin{definition}[Personalized PageRank (PPR)] \label{def:ppr} Given normalized adjacency matrix $\bm W_t = \bm D_t^{-1} \bm A_t$ where $\bm D_t$ is a diagonal matrix with $D_t(i,i) = d(i)^t$ and $\bm A_t$ is the adjacency matrix, the PageRank vector $\bm \pi_s^t$ with respect to a source node $s$ is the solution of the following equation \begin{equation} \bm \pi_s^t = \alpha * \bm 1_s + (1-\alpha)\bm \pi_s^t \bm W^t, \label{equ:ppr} \end{equation} where $\bm 1_s$ is the unit vector with $1_s(v)=1$ when $v =s$, 0 otherwise. \end{definition} There are several works on computing PPVs for static graph \cite{andersen2006local,berkhin2006bookmark,andersen2007local}. The idea is based a local push operation proposed in \cite{andersen2006local}. Interestingly, \citet{zhang2016approximate} extends this idea and proposes a novel updating strategy for calculating dynamic PPVs. We use a modified version of it as presented in Algorithm \ref{algo:forward-local-push}. \begin{algorithm}[H] \caption{$\textsc{ForwardPush}$ \cite{zhang2016approximate}} \begin{algorithmic}[1] \State \textbf{Input: }$\bm p_s, \bm r_s, \mathcal{G}, \epsilon, \beta = 0$ \While{$\exists u, r_s(u) > \epsilon d(u)$} \State $\textsc{Push}(u)$ \EndWhile \While{$\exists u, r_s(u) < -\epsilon d(u)$} \State $\textsc{Push}(u)$ \EndWhile \State \Return $(\bm p_s, \bm r_s)$ \Procedure{Push}{$u$} \State $p_s(u) \mathrel{{+}{=}} \alpha r_s(u)$ \For{$v \in \operatorname{Nei}(u)$} \State $r_s(v) \mathrel{{+}{=}} (1-\alpha) r_s(u) (1-\beta) / d(u)$ \EndFor \State $r_s(u) = (1-\alpha) r_s(u) \beta $ \EndProcedure \end{algorithmic} \label{algo:forward-local-push} \end{algorithm} Algorithm \ref{algo:forward-local-push} is a generalization from \citet{andersen2006local} and there are several variants of forward push \cite{andersen2006local,lofgren2015efficient,berkhin2006bookmark}, which are dependent on how $\beta$ is chosen (we assume $\beta=0$). The essential idea of forward push is that, at each \textsc{Push} step, the frontier node $u$ transforms her $\alpha$ residual probability $r_s(u)$ into estimation probability $p_s(u)$ and then pushes the rest residual to its neighbors. The algorithm repeats this push operation until all residuals are small enough \footnote{There are two implementation of forward push depends on how frontier is selected. One is to use a first-in-first-out (FIFO) queue \cite{gleich2015pagerank} to maintain the frontiers while the other one maintains nodes using a priority queue is used \cite{berkhin2006bookmark} so that the operation cost is $\mathcal{O}(1/\epsilon \alpha)$ instead of $\mathcal{O}(\log n/ \epsilon \alpha)$.}. Methods based on local push operations have the following invariant property. \begin{restatable}[Invariant property \cite{hong2016discriminating}]{lemma}{primelemma} \label{lemma:1} \textsc{ForwardPush} has the following invariant property \begin{equation} \pi_s(u) = p_s(u) + \sum_{v \in V} r_s(v) \pi_v(u), \forall u \in \mathbb{V}. \end{equation} \end{restatable} The local push algorithm can guarantee that the each entry of the estimation vector $p_s(v)$ is very close to the true value $\pi_s(v)$. We state this property as in the following \begin{lemma}[\cite{andersen2006local,zhang2016approximate}] \label{lemma:2} Given any graph $\mathcal{G}(\mathbb{V},\mathbb{E})$ with $\bm p_s = \bm 0, \bm r_s = \bm 1_s$ and a constant $\epsilon$, the run time for \textsc{ForwardLocalPush} is at most $\frac{1-\|\bm r_s\|_1}{\alpha \epsilon}$ and the estimation error of $\pi_s(v)$ for each node $v$ is at most $\epsilon$, i.e. $|p_s(v) - \pi_s(v)|/d(v)| \leq \epsilon$ \end{lemma} The main challenge to directly use forward push algorithm to obtain high quality PPVs in our setting is that: 1) the quality $\bm p_s$ return by forward push algorithm will critically depend on the precision parameter $\epsilon$ which unfortunately is unknown under our dynamic problem setting. Furthermore, the original update of per-edge event strategy proposed in \cite{zhang2016approximate} is not suitable for batch update between graph snapshots. \citet{guo2017parallel} propose to use a batch strategy, which is more practical in real-world scenario where there is a sequence of edge events between two consecutive snapshots. This motivates us to develop a new algorithm for dynamic PPVs and then use these PPVs to obtain high quality dynamic embedding vectors. \section{Proposed method} \label{sec:proposed} To obtain dynamic embedding vectors, the general idea is to obtain dynamic PPVs and then project these PPVs into embedding space by using two kernel functions \cite{weinberger2009feature,postuavaru2020instantembedding}. In this section, we present our proposed method \textsc{DynamicPPE} where it contains two main components: 1) an adaptive precision strategy to control the estimation error of PPVs. We then prove that the time complexity of this dynamic strategy is still independent on $n$. With this quality guarantee, learned PPVs will be used as proximity vectors and be "projected" into lower dimensional space based on ideas of \textit{Verse} \cite{tsitsulin2018verse} and \textit{InstantEmbedding} \cite{postuavaru2020instantembedding}. We first show how can we get high quality PPVs and then present how use PPVs to obtain dynamic embeddings. Finally, we give the complexity analysis. \subsection{Dynamic graph embedding for single batch} For each batch update $\Delta G^t$, the key idea is to dynamically maintain PPVs where the algorithm updates the estimate from $\bm p_v^{t-1}$ to $\bm p_v^t$ and its residuals from $\bm r_v^{t-1}$ to $\bm r_v^t$. Our method is inspired from \citet{guo2017parallel} where they proposed to update a personalized contribution vector by using the local reverse push \footnote{One should notice that, for undirected graph, PPVs can be calculated by using the invariant property from the contribution vectors. However, the invariant property does not hold for directed graph. It means that one cannot use reverse local push to get a personalized PageRank vector directly. In this sense, using forward push algorithm is more general for our problem setting.}. The proposed dynamic single node embedding, \textsc{DynamicSNE} is illustrated in Algorithm \ref{algo:dynamic-sne}. It takes an update batch $\Delta \mathcal{G}^t$ (a sequence of edge events), a target node $s$ with a precision $\epsilon^t$, estimation vector of $s$ and residual vector as inputs. It then obtains an updated embedding vector of $s$ by the following three steps: 1) It first updates the estimate vector $\bm p_s^t$ and $\bm r_s^t$ from Line 2 to Line 9; 2) It then calls the forward local push method to obtain the updated estimations, $\bm p_s^t$; 3) We then use the hash kernel projection step to get an updated embedding. This projection step is from \textit{InstantEmbedding} where two universal hash functions are defined as $h_d: \mathbb{N} \rightarrow [d]$ and $h_{\operatorname{sgn}} : \mathbb{N} \rightarrow \{\pm 1\}$ \footnote{For example, in our implementation, we use MurmurHash \textcolor{blue}{\url{https://github.com/aappleby/smhasher}}}. Then the hash kernel based on these two hash functions is defined as $H_{h_{\operatorname{sgn}},h_d}(\bm x): \mathbb{R}^n \rightarrow \mathbb{R}^d$ where each entity $i$ is $\sum_{j \in h_d^{-1}(i)} x_j h_{\operatorname{sgn}}(j)$. Different from random projection used in RandNE \cite{zhang2018billion} and FastRP \cite{chen2019fast}, hash functions has $\mathcal{O}(1)$ memory cost while random projection based method has $\mathcal{O}(d n)$ if the Gaussian matrix is used. Furthermore, hash kernel keeps unbiased estimator for the inner product \cite{weinberger2009feature}. In the rest of this section, we show that the time complexity is $\mathcal{O}(m \bar{d} / \epsilon)$ in average and the estimation error of learned PPVs measure by $\| \cdot \|_1$ can also be bounded. Our proof is based on the following lemma which follows from \citet{zhang2016approximate,guo2017parallel}. \begin{lemma} \label{lemma:6} Given current graph $\mathcal{G}^t$ and an update batch $\Delta \mathcal{G}^t$, the total run time of the dynamic single node embedding, \textsc{DynamicSNE} for obtaining embedding $\bm w_s^t$ is bounded by the following \begin{equation} T_t \leq \frac{\|\bm r_s^{t-1}\|_1 - \|\bm r_s^t\|_1}{\alpha \epsilon^t} + \sum_{u\in \Delta \mathcal{G}^t}\frac{2-\alpha}{\alpha} \frac{p_s^{t-1}(u)}{d(u)} \end{equation} \end{lemma} \begin{proof} We first make an assumption that there is only one edge update $(u,v,\operatorname{event})$ in $\Delta \mathcal{G}^t$, then based Lemma 14 of \cite{zhang2016approximate-extended}, the run time of per-edge update is at most: \begin{equation} \frac{\|\bm r_s^{t-1}\|_1 - \|\bm r_s^{t-1}\|_1}{\alpha \epsilon^t} + \frac{\Delta_t(s)}{\alpha \epsilon^t}, \end{equation} where $\Delta_t(s) = \frac{2-\alpha}{\alpha} \frac{p_s^{t-1}(u)}{d(u)}$. Suppose there are $k$ edge events in $\Delta \mathcal{G}^t$. We still obtain a similar bound, by the fact that forward push algorithm has monotonicity property: the entries of estimates $ p_s^t(v)$ only increase when it pushes positive residuals (Line 2 and 3 of Algorithm \ref{algo:forward-local-push}). Similarly, estimates $p_s^t(v)$ only decrease when it pushes negative residuals (Line 4 and 5 of Algorithm \ref{algo:forward-local-push}). In other words, the amount of work for per-edge update is not less than the amount of work for per-batch update. Similar idea is also used in \cite{guo2017parallel}. \end{proof} \newcommand{=\mathrel{+}}{=\mathrel{+}} \begin{algorithm}[H] \caption{$\textsc{DynamicSNE}(\mathcal{G}^t, \Delta \mathcal{G}^t, s,\bm p_s^{t-1},\bm r_s^{t-1}, \epsilon^t,\alpha)$} \begin{algorithmic}[1] \State \textbf{Input: } graph $\mathcal{G}^t, \Delta \mathcal{G}^t$, target node $s$, precision $\epsilon$, teleport $\alpha$ \For{$(u,v,\operatorname{op}) \in \Delta G^{t}$} \If{$\operatorname{op}==\textsc{Insert}(u,v)$} \State $\Delta_p = p_s^{t-1}(u) / (d(u)^t -1)$ \EndIf \If{$\operatorname{op} == \textsc{Delete}(u,v)$} \State $\Delta_p = -p_s^{t-1}(u) / (d(u)^t + 1)$ \EndIf \State $p_s^{t-1}(u) \leftarrow p_s^{t-1}(u) + \Delta_p$ \State $r_s^{t-1}(u) \leftarrow r_s^{t-1}(u) - \Delta_p / \alpha$ \State $r_s^{t-1}(v) \leftarrow r_s^{t-1}(v) + \Delta_p / \alpha - \Delta_p$ \EndFor \State $\bm p_s^t = \textsc{ForwardPush}(\bm p_s^{t-1},\bm r_s^{t-1},\mathcal{G}^t,\epsilon^t,\alpha)$ \State $\bm w_s^t = \bm 0$ \For{ $i \in \{ v : p_s^t(v) \ne 0, v \in \mathbb{V}^t\}$} \State $w_s^{t}(h_d(i)) \mathrel{{+}{=}} h_{\operatorname{sgn}}(i) \max\left(\log \left(p_s^t(i) n^t\right), 0\right)$ \EndFor \end{algorithmic} \label{algo:dynamic-sne} \end{algorithm} \begin{theorem} Given any graph snapshot $\mathcal{G}^t$ and an update batch $\Delta G^t$ where there are $m_t$ edge events and suppose the precision parameter is $\epsilon^t$ and teleport probability is $\alpha$, \textsc{DynamicSNE} runs in $\mathcal{O}(m_t/\alpha^2 + m_t \bar{d}^t / (\epsilon\alpha^2) + m_t / (\epsilon\alpha))$ with $\epsilon^t = \epsilon / m_t$ \label{thm:run-time} \end{theorem} \begin{proof} Based lemma \ref{lemma:6}, the proof directly follows from Theorem 12 of \cite{zhang2016approximate-extended}. \end{proof} The above theorem has an important difference from the previous one \cite{zhang2016approximate}. We require that the precision parameter will be small enough so that $\| \bm p_s^t - \bm \pi_s^t\|_1$ can be bound ( will be discussed later). As we did the experiments in Figure \ref{fig:epsilon-fix}, the fixed epsilon will make the embedding vector bad. We propose to use a dynamic precision parameter, where $\epsilon^t \sim \mathcal{O}(\epsilon^\prime /m_t)$, so that the $\ell_1$-norm can be properly bounded. Interestingly, this high precision parameter strategy will not case too high time complexity cost from $\mathcal{O}(m/\alpha^2)$ to $\mathcal{O}(m \bar{d} / (\epsilon\alpha^2))$. The bounded estimation error is presented in the following theorem. \begin{theorem}[Estimation error] Given any node $s$, define the estimation error of PPVs learned from \textsc{DynamicSNE} at time $t$ as $\| \bm p_s^t - \bm \pi_s^t \|_1$, if we are given the precision parameter $\epsilon^t = \epsilon / m_t$, the estimation error can be bounded by the following \begin{equation} \| \bm p_s^t - \bm \pi_s^t \|_1 \leq \epsilon, \end{equation} where we require $\epsilon \leq 2$ \footnote{By noticing that $\|\bm p_s^t - \bm \pi_s^t\|_1 \leq \|\bm p_s^t\|_1 + \| \bm \pi_s^t\|_1 \leq 2$, any precision parameter larger than 2 will be meaningless. } and $\epsilon$ is a global precision parameter of \textsc{DynamicPPE} independent on $m_t$ and $n_t$. \end{theorem} \begin{proof} Notice that for any node $u$, by Lemma \ref{lemma:2}, we have the following inequality \begin{equation} | \pi_s^t(u) - \pi_s^t(u) | \leq \epsilon d^t(u). \nonumber \end{equation} Summing all these inequalities over all nodes $u$, we have \begin{align*} \| \bm p_s^t - \bm \pi_s^t \|_1 &= \sum_{u\in \mathbb{V}^t} \left| p_s^t(u) - \pi_s^t(u)\right| \\ &\leq \sum_{u \in \mathbb{V}^t} \epsilon^t d^t(u) = \epsilon^t m_t = \frac{\epsilon}{m_t} m_t = \epsilon. \end{align*} \end{proof} \begin{figure}[H] \centering \includegraphics[width=8cm,height=3.5cm]{figs/nc-2001-512-dynamic-dne-epsilon.pdf} \caption{$\epsilon$ as a function of year for the task of node classification on the English Wikipedia graph. Each line corresponds to a fixed precision strategy of \textsc{DynamicSNE}. Clearly, when the precision parameter $\epsilon$ decreases, the performance of node classification improves.} \label{fig:epsilon-fix} \end{figure} The above theorem gives estimation error guarantee of $\bm p_s^t$, which is critically important for learning high quality embeddings. First of all, the dynamic precision strategy is inevitable because the precision is unknown parameter for dynamic graph where the number of nodes and edges could increase dramatically over time. To demonstrate this issue, we conduct an experiments on the English Wikipedia graph where we learn embeddings over years and validate these embeddings by using node classification task. As shown in Figure \ref{fig:epsilon-fix}, when we use the fixed parameter, the performance of node classification is getting worse when the graph is getting bigger. This is mainly due to the lower quality of PPVs. Fortunately, the adaptive precision parameter $\epsilon / m_t$ does not make the run time increase dramatically. It only dependents on the average degree ${\bar d}^t$. In practice, we found $\epsilon =0.1$ are sufficient for learning effective embeddings. \subsection{\textsc{DynamicPPE}} Our finally algorithm \textsc{DynamicPPE} is presented in Algorithm \ref{algo:dynamic-ppe}. At every beginning, estimators $\bm p_s^t$ are set to be zero vectors and residual vectors $\bm r_s^t$ are set to be unit vectors with mass all on one entry (Line 4). The algorithm then call the procedure \textsc{DynamicSNE} with an empty batch as input to get initial PPVs for all target nodes \footnote{For the situation that some nodes of $S$ has not appeared in $\mathcal{G}^t$ yet, it checks every batch update until all nodes are initialized. } (Line 5). From Line 6 to Line 9, at each snapshot $t$, it gets an update batch $\Delta \mathcal{G}^t$ at Line 7 and then calls \textsc{DynamicSNE} to obtain the updated embeddings for every node $v$. \begin{algorithm}[H] \caption{$\textsc{DynamicPPE}(\mathcal{G}_0, S,\epsilon,\alpha)$} \begin{algorithmic}[1] \State \textbf{Input: } initial graph $\mathcal{G}^0$, target set $S$, global precision $\epsilon$, teleport probability $\alpha$ \State $t=0$ \For{$s \in S := \{v_1,v_2,\ldots, v_k\}$} \State $\bm p_s^t = \bm 0,\quad \bm r_s^t = \bm 1_s$ \State \textsc{DynamicSNE}$(\mathcal{G}^0, \emptyset, s, \bm p_s^t, \bm r_s^t, 1/ m_0, \alpha)$ \EndFor \For{$t \in \{1,2,\ldots, T\}$} \State \text{ read a sequence of edge events $\Delta \mathcal{G}^t := \mathcal{G}^t \backslash \mathcal{G}^{t-1}$} \For{$s \in S := \{v_1,v_2,\ldots, v_k\}$} \State $ \bm w_s^t = \textsc{DynamicSNE}(\mathcal{G}^t, \Delta \mathcal{G}^t, s, \bm p_s^{t-1}, \bm r_s^{t-1}, \epsilon/m_t,\alpha)$ \EndFor \EndFor \State \textbf{return} $\bm W_s^t = [\bm w_s^1,\bm w_s^2,\ldots, \bm w_s^T], \forall s\in S$. \end{algorithmic} \label{algo:dynamic-ppe} \end{algorithm} Based on our analysis, \textsc{DynamicPPE} is an dynamic version of \textit{InstantEmbedding}. Therefore, \textsc{DynamicPPE} has two key properties observed in \cite{postuavaru2020instantembedding}: \textit{locality} and \textit{global consistency}. The embedding quality is guaranteed from the fact that \textit{InstantEmbedding} implicitly factorizes the proximity matrix based on PPVs \cite{tsitsulin2018verse}. \subsection{Complexity analysis} \textbf{Time complexity}\quad The overall time complexity of \textsc{DynamicPPE} is the $k$ times of the run time of \textsc{DynamicSNE}. We summarize the time complexity of \textsc{DynamicPPE} as in the following theorem \begin{theorem} The time complexity of \textsc{DynamicPPE} for learning a subset of $k$ nodes is $\mathcal{O}(k \frac{m_t}{\alpha^2} + k \frac{m_t \bar{d}^t}{\alpha^2} + \frac{m_t}{\epsilon} + k T \min\{n, \frac{m}{\epsilon \alpha}\})$ \end{theorem} \begin{proof} We follow Theorem \ref{thm:run-time} and summarize all run time together to get the final time complexity. \end{proof} \noindent\textbf{Space complexity}\quad The overall space complexity has two parts: 1) $\mathcal{O}(m)$ to store the graph structure information; and 2) the storage of keeping nonzeros of $\bm p_s^t$ and $\bm r_s^t$. From the fact that local push operation \cite{andersen2006local}, the number of nonzeros in $\bm p_s^t$ is at most $\frac{1}{\epsilon \alpha}$. Thus, the total storage for saving these vectors are $\mathcal{O}(k \min\{n,\frac{m }{\epsilon \alpha}\})$. Therefore, the total space complexity is $\mathcal{O}(m + k \min(n,\frac{m}{\epsilon\alpha}))$. \noindent\textbf{Implementation}\quad Since learning the dynamic node embedding for any node $v$ is independent with each other, \textsc{DynamicPPE} is are easy to parallel. Our current implementation can take advantage of multi-cores and compute the embeddings of $S$ in parallel. \section{Experiments} \label{sec:experiments} To demonstrate the effectiveness and efficiency of \textsc{DynamicPPE}, in this section, we first conduct experiments on several small and large scale real-world dynamic graphs on the task of node classification, followed by a case study about changes of Chinese cities in Wikipedia graph during the COVID-19 pandemic. \subsection{Datasets} We compile the following three real-world dynamic graphs, more details can be found in Appendix \ref{appendix::data}. \noindent \textbf{Enwiki20} {English Wikipedia Network\quad} We collect the internal Wikipedia Links (WikiLinks) of English Wikipedia from the beginning of Wikipedia, January 11th, 2001, to December 31, 2020 \footnote{We collect the data from the dump \url{https://dumps.wikimedia.org/enwiki/20210101/}}. The internal links are extracted using a regular expression proposed in \cite{consonni2019wikilinkgraphs}. During the entire period, we collection 6,151,779 valid articles\footnote{A valid Wikipedia article must be in the 0 namespace}. We generated the WikiLink graphs only containing edge insertion events. We keep all the edges existing before Dec. 31 2020, and sort the edge insertion order by the creation time. There are 6,216,199 nodes and 177,862,656 edges during the entire period. Each node either has one label (\textit{Food, Person, Place,...}) or no label. \noindent \textbf{Patent} ({US Patent Graph}) \quad The citation network of US patent\cite{hall2001nber} contains 2,738,011 nodes with 13,960,811 citations range from year 1963 to 1999. For any two patents $u$ and $v$, there is an edge $(u,v)$ if the patent $u$ cites patent $v$. Each patent belongs to six different types of patent categories. We extract a small weakly-connected component of 46,753 nodes and 425,732 edges with timestamp, called \textit{Patent-small}. \noindent \textbf{Coauthor} \quad We extracted the co-authorship network from the Microsoft Academic Graph \cite{sinha2015overview} dumped on September 21, 2019. We collect the papers with less than six coauthors, keeping those who has more than 10 publications, then build undirected edges between each coauthor with a timestamp of the publication date. In addition, we gather temporal label (e.g.: \textit{Computer Science, Art, ... }) of authors based on their publication's field of study. Specifically we assign the label of an author to be the field of study where s/he published the most up to that date. The original graph contains 4,894,639 authors and 26,894,397 edges ranging from year 1800 to 2019. We also sampled a small connected component containing 49,767 nodes and 755,446 edges with timestamp, called \textit{Coauthor-small}. \noindent \textbf{Academic} The co-authorship network is from the academic network \cite{zhou2018dynamic,tang2008arnetminer} where it contains 51,060 nodes and 794,552 edges. The nodes are generated from 1980 to 2015. According to the node classification setting in \citet{zhou2018dynamic}, each node has either one binary label or no label. \subsection{Node Classification Task} \noindent\textbf{Experimental settings\quad} We evaluate embedding quality on binary classification for Academic graph (as same as in \cite{zhou2018dynamic}), while using multi-class classification for other tasks. We use balanced logistic regression with $\ell_2$ penalty in on-vs-rest setting, and report the Macro-F1 and Macro-AUC (ROC) from 5 repeated trials with 10\% training ratio on the labeled nodes in each snapshot, excluding dangling nodes. Between each snapshot, we insert new edges and keep the previous edges. We conduct the experiments on the aforementioned small and large scale graph. In small scale graphs, we calculate the embeddings of all nodes and compare our proposed method (\textbf{DynPPE.}) against other state-of-the-art models from three categories\footnote{Appendix \ref{appendix::parameter} shows the hyper-parameter settings of baseline methods}. 1) Random walk based static graph embeddings (\textbf{Deepwalk}\footnote{\url{https://pypi.org/project/deepwalk/}} \cite{perozzi2014deepwalk}, \textbf{Node2Vec}\footnote{\url{https://github.com/aditya-grover/node2vec}} \cite{grover2016node2vec}); 2) Random Projection-based embedding method which supports online update: \textbf{RandNE}\footnote{\url{https://github.com/ZW-ZHANG/RandNE/tree/master/Python}} \cite{zhang2018billion}; 3) Dynamic graph embedding method: \textbf{DynamicTriad} (\textbf{DynTri.}) \footnote{\url{https://github.com/luckiezhou/DynamicTriad}} \cite{zhou2018dynamic} which models the dynamics of the graph and optimized on link prediction. \begin{table}[!h] \centering \caption{Node classification task on the \textit{Academic, Patent Small, Coauthor Small} graph on the final snapshot} \small \begin{tabular}{p{0.05\textwidth}|p{0.06\textwidth}|p{0.03\textwidth}|p{0.03\textwidth}|p{0.03\textwidth}|p{0.03\textwidth}|p{0.03\textwidth}|p{0.03\textwidth} } \toprule \multicolumn{2}{l|}{} & \multicolumn{2}{l|}{Academic} & \multicolumn{2}{l|}{Patent Small} & \multicolumn{2}{l}{Coauthor Small}\\ \multicolumn{2}{l|}{} & F1 & AUC & F1 & AUC & F1 & AUC \\ \cline{1-8} \multicolumn{8}{c}{$d=128$} \\ \cline{1-8} \multirow{2}{0mm}{Static method} & Node2Vec &0.833 &\textbf{0.975} &0.648 &0.917 &0.477 &\textbf{0.955}\\ \cline{2-8} &Deepwalk &\textbf{0.834} &\textbf{0.975} &\textbf{0.650} &\textbf{0.919} &\textbf{0.476} &0.950\\ \cline{1-8} \multirow{4}{0mm}{Dynamic method} &DynTri. &0.817 &0.969 &0.560 &0.866 &0.435 &0.943\\ \cline{2-8} &RandNE &0.587 &0.867 &0.428 &0.756 &0.337 &0.830\\ \cline{2-8} &DynPPE. &0.808 &0.962 &0.630 &0.911 &0.448 &0.951\\ \hline \multicolumn{8}{c}{$d=512$} \\ \hline \multirow{2}{0mm}{Static method} & Node2Vec &0.841 &\textbf{0.975} &0.677 &0.931 &0.486 &0.955 \\ \cline{2-8} &Deepwalk &\textbf{0.842} &\textbf{0.975} &0.680 &0.931 &0.495 &0.955 \\ \cline{1-8} \multirow{4}{0mm}{Dynamic method} &DynTri. &0.811 &0.965 &0.659 &0.915 &0.492 &0.952 \\ \cline{2-8} &RandNE &0.722 &0.942 &0.560 &0.858 &0.493 &0.895 \\ \cline{2-8} &DynPPE. &\textbf{0.842} &0.973 &\textbf{0.682} & \textbf{0.934} &\textbf{0.509} &\textbf{0.958}\\ \bottomrule \end{tabular} \label{tab:nc-small-table} \end{table} \begin{table}[!h] \caption{Total CPU time for small graphs (in second). RandNE-I is with orthogonal projection, the performance is slightly better, but the running time is significantly increased. RandNE-II is without orthogonal projection.} \centering \begin{tabular}{p{0.08\textwidth}|p{0.08\textwidth}|p{0.12\textwidth}|p{0.12\textwidth}} \toprule & Academic & Patent Small & Coauthor Small \\ \hline Deepwalk\footnotemark & 498211.75& 181865.56 & 211684.86 \\ \hline Node2vec & 4584618.79& 2031090.75 & 1660984.42 \\ \hline DynTri. & 247237.55 & 117993.36 & 108279.4 \\ \hline RandNE-I & 12732.64 & 9637.15 & 8436.79 \\ \hline RandNE-II & 1583.08 & 9208.03 & 177.89 \\ \hline DynPPE. & 18419.10 & 3651.59 & 21323.74 \\ \bottomrule \end{tabular} \label{tab:runtime-small} \end{table} \footnotetext{ We ran static graph embedding methods over a set of sampled snapshots and estimate the total CPU time for all snapshots.} \begin{figure*}[h!] \centering \begin{subfigure}{.33\textwidth} \includegraphics[width=5cm]{figs/nc-small-dataset/nc-512-academic_full-f1.pdf}% \end{subfigure} \begin{subfigure}{.33\textwidth} \includegraphics[width=5cm]{figs/nc-small-dataset/nc-512-patent_small-f1.pdf}% \end{subfigure} \begin{subfigure}{.33\textwidth} \includegraphics[width=5cm]{figs/nc-small-dataset/nc-512-mag_coauthor_small-f1.pdf}% \end{subfigure} \begin{subfigure}{.33\textwidth} \includegraphics[width=5cm]{figs/nc-large-dataset/nc-512-enwiki_full-f1.pdf}% \end{subfigure} \begin{subfigure}{.33\textwidth} \includegraphics[width=5cm]{figs/nc-large-dataset/nc-512-patent_full-f1.pdf}% \end{subfigure} \begin{subfigure}{.33\textwidth} \includegraphics[width=5cm]{figs/nc-large-dataset/nc-512-mag_coauthor_full-f1.pdf}% \end{subfigure} \caption{Macro-F1 scores of node classification as a function of time. The results of the small and large graphs are on the first and second row respectively (dim=512). Our proposed methods achieves the best performance on the last snapshot when all edges arrived and performance curve matches to the static methods as the graph becomes more and more complete.} \label{fig:nc-full-macro-f1-over-time} \end{figure*} Table \ref{tab:nc-small-table} shows the classification results on the final snapshot. When we restrict the dimension to be 128, we observe that static methods outperform all dynamic methods. However, the static methods independently model each snapshot and the running time grows with number of snapshots, regardless of the number of edge changes. In addition, our proposed method (DynPPE.) outperforms other dynamic baselines, except that in the \textit{academic} graph, where DynTri. is slightly better. However, their CPU time is 13 times more than ours as shown in Table \ref{tab:runtime-small}. According to the Johnson-Lindenstrauss lemma\cite{johnson1984extensions,dasgupta1999elementary}, we suspect that the poor result of RandNE is partially caused by the dimension size. As we increase the dimension to 512, we see a great performance improvement of RandNE. Also, our proposed method takes the same advantage, and outperform all others baselines in F1-score. Specifically, the increase of dimension makes hash projection step (Line 12-13 in Algorithm \ref{algo:dynamic-sne}) retain more information and yield better embeddings. We attach the visualization of embeddings in Appendix.\ref{tsne-embedding}. The first row in the Figure \ref{fig:nc-full-macro-f1-over-time} shows the F1-scores in each snapshot when the dimension is 512. We observe that in the earlier snapshots where many edges are not arrived, the performance of DynamicTriad \cite{zhou2018dynamic} is better. One possible reason is that it models the dynamics of the graph, thus the node feature is more robust to the "missing" of the future links. While other methods, including ours, focus on an online feature updates incurred by the edge changes without explicitly modeling the temporal dynamics of a graph. Meanwhile, the performance curve of our method matches to the static methods, demonstrating the embedding quality of the intermediate snapshots is comparable to the state-of-the-art. Table \ref{tab:runtime-small} shows the CPU time of each method (Dim=512). As we expected, static methods is very expensive as they calculate embeddings for each snapshot individually. Although our method is not blazingly fast compared to RandNE, it has a good trade-off between running time and embedding quality, especially without much hyper-parameter tuning. Most importantly, it can be easily parallelized by distributing the calculation of each node to clusters. We also conduct experiment on large scale graphs (\textit{EnWiki20, Patent, Coauthor}). We keep track of the vertices in a subset containing $|S|=3,000$ nodes randomly selected from the first snapshot in each dataset, and similarly evaluate the quality of the embeddings of each snapshot on the node classification task. Due to scale of the graph, we compare our method against \textbf{RandNE} \cite{zhang2018billion} and an fast heuristic \textbf{Algorithm \ref{algo:commute}}. Our method can calculate the embeddings for a subset of useful nodes only, while other methods have to calculate the embeddings of all nodes, which is not necessary under our scenario detailed in Sec. \ref{sec:case-study}. The second row in Figure \ref{fig:nc-full-macro-f1-over-time} shows that our proposed method has the best performance. \begin{table}[!h] \caption{Total CPU time for large graphs (in second) } \centering \begin{tabular}{p{0.15\textwidth}|p{0.08\textwidth}|p{0.08\textwidth}|p{0.08\textwidth}}\toprule & Enwiki20 & Patent & Coauthor \\ \hline Commute & 6702.1 & 639.94 & 1340.74 \\ \hline RandNE-II & 47992.81 & 6524.04 & 20771.19 \\ \hline DynPPE. & 1538215.88 & 139222.01 & 411708.9 \\ \hline DynPPE (Per-node) & 512.73 & 46.407 & 137.236 \\ \bottomrule \end{tabular} \label{tab:runtime-large} \end{table} Table \ref{tab:runtime-large} shows the total CPU time of each method (Dim=512). Although total CPU time of our proposed method seems to be the greatest, the average CPU time for one node (as shown in row 4) is significantly smaller. This benefits a lot of downstream applications where only a subset of nodes are interesting to people in a large dynamic graph. For example, if we want to monitor the weekly embedding changes of a single node (e.g., the city of Wuhan, China) in English Wikipedia network from year 2020 to 2021, we can have the results in roughly 8.5 minutes. Meanwhile, other baselines have to calculate the embeddings of all nodes, and this expensive calculation may become the bottleneck in a downstream application with real-time constraints. To demonstrate the usefulness of our method, we conduct a case study in the following subsection. \begin{comment} Each method will make a prediction at the end of each year. As expected, the method receive more edges, the performance of these methods will increase except for \textsc{Random}. \begin{figure}[H] \centering \includegraphics[width=8cm,height=3cm]{figs/nc-enwiki-2001-128.pdf} \caption{The node classification performance as a function of year. The classification tasks are conducted on 10\% Wikipedia nodes selected from 2001. It has 5,799 labeled nodes.} \label{fig:nc-order-2001} \end{figure} \begin{table}[!h] \centering \caption{Node classification and Prediction task on the \textit{Academic} graph. The results of the first four methods, i.e. DeepWalk, TNE, node2vec, and DynamicTriad are from \cite{zhou2018dynamic}.} \small \begin{tabular}{p{0.16\textwidth}|p{0.03\textwidth}|p{0.03\textwidth}|p{0.03\textwidth}|p{0.03\textwidth}|p{0.03\textwidth}|p{0.03\textwidth}} \toprule & \multicolumn{3}{l|}{Node Classification} & \multicolumn{3}{l}{Vertex Prediction} \\ & Prec. & Rec. & F1 & Prec. & Rec. & F1 \\ \hline DeepWalk & 0.541 & 0.755 & 0.630 & 0.516 & 0.692 & 0.591 \\ \hline TNE & 0.266 & 0.554 & 0.359 & 0.264 & 0.540 & 0.355 \\ \hline node2vec & 0.527 & 0.768 & 0.625 & 0.516 & 0.705 & 0.596 \\ \hline DynamicTriad & 0.618 & 0.818 & 0.704 & 0.584 & 0.790 & 0.671 \\ \hline DynamicTriad (Repeat) & 0.795 & 0.770 & 0.782 & 0.782 & 0.760 & 0.771 \\ \hline DynamicNE ($d=48$) & 0.879 & 0.827 & 0.853 & 0.856 & 0.765 & 0.808 \\ \hline DynamicNE ($d=128$) & 0.921 & 0.879 & 0.900 & 0.899 & 0.805 & 0.850 \\ \bottomrule \end{tabular} \end{table} \noindent\textbf{Node classification as a function of year.\quad} In year of 2001, it has 5799 articles that have labels. We randomly select 10\% percentage of articles generated in 2001 as training nodes and the rest articles as testing. The node classification performance has illustrated in Figure \ref{fig:nc-order-2001}. As we expected, the Macro and Micro F1 scores will increase as the dynamic embedding methods see more edges (except for the random method). We also compare the dynamic embedding-based method with Instant-Embedding\cite{postuavaru2020instantembedding}, a static method, runs on static graph as it seen. Similarly, we conduct the experiment on the year of 2002 where it has 58,906 labeled articles. \begin{figure}[H] \centering \includegraphics[width=8cm,height=3.5cm]{figs/nc-patent-1975-256.pdf} \caption{The node classification performance as a function of year. The classification tasks are conducted on 10\% Wikipedia nodes selected from 2001. It has 58,906 labeled nodes.} \label{fig:nc-order-2002} \end{figure} \noindent\textbf{Comparison of Edge order.} In order to see, whether edge order will affect the performance or not, we compare these two baseline methods with respect to the order of edges. As shown in Figure \ref{fig:nc-random-2001}, the order of edges does affect the performance. Compared with Centroid method, the Commute method affect more by the order of edges, this is because the Commute method relies more on the node degree. One critical observation is that previous method cannot have estimation guarantee if use random projection. The key property of random projection/random hash works is due to the inner product preserving. \begin{figure}[H] \centering \includegraphics[width=8cm,height=3.24cm]{figs/node-classification-us-patent.pdf} \caption{Node classification on US-Patent dataset.} \label{fig:nc-us-patent} \end{figure} \end{comment} \subsection{Change Detection} \label{sec:case-study} Thanks to the contributors timely maintaining Wikipedia, we believe that the evolution of the Wikipedia graph reflects how the real world is going on. We assume that when the structure of a node greatly changes, there must be underlying interesting events or anomalies. Since the structural changes can be well-captured by graph embedding, we use our proposed method to investigate whether anomalies happened to the Chinese cities during the COVID-19 pandemic (from Jan. 2020 to Dec. 2020). \begin{table*}[!ht] \caption{The top cities ranked by the z-score along time. The corresponding news titles are from the news in each time period. $d(v)$ is node degree, $\Delta d(v)$ is the degree changes from the previous timestamp.} \centering \small \begin{tabular}{p{0.05\textwidth}|p{0.082\textwidth}|p{0.03\textwidth}|p{0.035\textwidth}|p{0.05\textwidth}|p{0.68\textwidth}} \toprule Date & City & $d(v)$ & $\Delta d(v)$ & Z-score & Top News Title \\ \hline 1/22/20 & Wuhan & 2890 & 54 & 2.210 & NBC: "New virus prompts U.S. to screen passengers from Wuhan, China" \\ \hline 2/2/20 & Wuhan & 2937 & 47 & 1.928 & WSJ: "U.S. Sets Evacuation Plan From Coronavirus-Infected Wuhan" \\ \hline 2/13/20 & Hohhot & 631 & 20 & 1.370 & Poeple.cn: "26 people in Hohhot were notified of dereliction of duty for prevention and control, and the director of the Health Commission was removed" (Translated from Chinese). \\ \hline 2/24/20 & Wuhan & 3012 & 38 & 2.063 & USA Today: "Coronavirus 20 times more lethal than the flu? Death toll passes 2,000" \\ \hline 3/6/20 & Wuhan & 3095 & 83 & 1.723 & Reuters: "Infelctions may drop to zero by end-March in Wuhan: Chinese government expert" \\ \hline 3/17/20 & Wuhan & 3173 & 78 & 1.690 & NYT: "Politicians Use of 'Wuhan Virus' Starts a Debate Health Experets Wanted to Avoid" \\ \hline 3/28/20 & Zhangjiakou & 517 & 15 & 1.217 & "Logo revealed for Freestyle Ski and Snowboard World Championships in Zhangjiakou" \\ \hline 4/8/20 & Wuhan & 3314 & 47 & 2.118 & CNN:"China lifts 76-day lockdown on Wuhan as city reemerges from conronavirus crisis" \\ \hline 4/19/20 & Luohe & 106 & 15 & 2.640 & Forbes: "The Chinese Billionaire Whose Company Owns Troubled Pork Processor Smithfield Foods" \\ \hline 4/30/20 & Zunhua & 52 & 17 & 2.449 & XINHUA: "Export companies resume production in Zunhua, Hebei" \\ \hline 5/11/20 & Shulan & 88 & 46 & 2.449 & CGTN: "NE China's Shulan City to reimpose community lockdown in 'wartime' battle against COVID-19" \\ \bottomrule \end{tabular} \label{tab:z-score-city-changes} \end{table*} \noindent \textbf{Changes of major Chinese Cities\quad} We target nine Chinese major cities (\textit{Shanghai, Guangzhou, Nanjing, Beijing, Tianjin, \textbf{Wuhan}, Shenzhen, Chengdu, Chongqing)} and keep track of the embeddings in a 10-day time window. From our prior knowledge, we expect that \textit{Wuhan} should greatly change since it is the first reported place of the COVID-19 outbreak in early Jan. 2020. \begin{figure}[!h] \centering \begin{subfigure}{.23\textwidth} \includegraphics[width=4.3cm]{figs/Case-Study/cs-Wuhan-Chengdu-deg-change.pdf}% \end{subfigure} \begin{subfigure}{.23\textwidth} \includegraphics[width=4.8cm]{figs/Case-Study/cs-Wuhan-Chengdu-cos.png}% \end{subfigure} \caption{The changes of major Chinese cities in 2020. \textit{Left}:Changes in Node Degree. \textit{Right}: Changes in Cosine distance } \label{fig:cs-changes} \end{figure} Figure.\ref{fig:cs-changes}(a) shows the node degree changes of each city every 10 days. The curve is quite noisy, but we can still see several major peaks from \textit{Wuhan} around 3/6/20 and \textit{Chengdu} around 8/18/20. When using embedding changes \footnote{Again, the embedding movement $\operatorname{Dist}(\cdot,\cdot)$ is defined as $1-\cos(\cdot,\cdot)$} as the measurement, Figure.\ref{fig:cs-changes} (b) provides a more clear view of the changed cities. We observe strong signals from the curve of \textit{Wuhan}, correlating to the initial COVID-19 outbreak and the declaration of pandemic \footnote{COIVD-19: \url{https://www.who.int/news/item/27-04-2020-who-timeline---covid-19}}. In addition, we observed an peak from the curve of \textit{Chengdu} around 8/18/20 when U.S. closed the consulate in Chengdu, China, reflecting the U.S.-China diplomatic tension\footnote{US Consulate: \url{https://china.usembassy-china.org.cn/embassy-consulates/chengdu/}}. \noindent \textbf{Top changed city along time\quad} We keep track of the embedding movement of 533 Chinese cities from year 2020 to 2021 in a 10-day time window, and filter out the inactive records by setting the threshold of degree changes (e.g. greater than 10). The final results are 51 Chinese cities from the major ones listed above and less famous cities like \textit{Zhangjiakou, Hohhot, Shulan, ...}. Furthermore, we define the z-score of a target node $u$ as $Z_t(u)$ based on the embedding changes within a specific period of time from $t-1$ to $t$. \begin{align*} Z_t(u|u\in S) &= \frac{Dist(w_u^{t}, w_u^{t-1}) - \mu }{\sigma} \\ \mu = \frac{1}{|S|} \sum_{u' \in S} Dist(w_{u'}^{t}, w_{u'}^{t-1})&,\ \ \sigma = \sqrt{\frac{1}{|S|} \sum_{u' \in S} (Dist(w_{u'}^{t} w_{u'}^{t-1}) - \mu)^2 } \\ \end{align*} In Table \ref{tab:z-score-city-changes}, we list the highest ranked cities by the z-score from Jan.22 to May 11, 2020. In addition, we also attach the top news titles corresponding to the city within each specific time period. We found that Wuhan generally appears more frequently as the situation of the pandemic kept changing. Meanwhile, we found the appearance of \textit{Hohhot} and \textit{Shulan} reflects the time when COVID-19 outbreak happened in those cities. We also discovered cities unrelated to the pandemic. For example, \textit{Luohe}, on 4/19/20, turns out to be the city where the headquarter of the organization which acquired Smithfield Foods (as mentioned in the news). In addition, \textit{Zhangjiakou}, on 3/28/20, is the city, which will host World Snowboard competition, released the Logo of that competition. \section{Discussion and Conclusion} \label{sec:conclusion} In this paper, we propose a new method to learn dynamic node embeddings over large-scale dynamic networks for a subset of interesting nodes. Our proposed method has time complexity that is linear-dependent on the number of edges $m$ but independent on the number of nodes $n$. This makes our method applicable to applications of subset representations on very large-scale dynamic graphs. For the future work, as shown in \citet{trivedi2019dyrep}, there are two dynamics on dynamic graph data, \textit{structure evolution} and dynamics of \textit{node interaction}. It would be interesting to study how one can incorporate dynamic of node interaction into our model. It is also worth to study how different version of local push operation affect the performance of our method. \begin{acks} This work was partially supported by NSF grants IIS-1926781, IIS-1927227, IIS-1546113 and OAC-1919752. \end{acks} \bibliographystyle{ACM-Reference-Format}
{'timestamp': '2021-06-04T02:09:43', 'yymm': '2106', 'arxiv_id': '2106.01570', 'language': 'en', 'url': 'https://arxiv.org/abs/2106.01570'}
arxiv
\section{Introduction} \footnotetext{ {\texttt{[email protected]}. \url{https://github.com/PAL-ML/CLIPPER} \textsuperscript{*,+}\textit{Equal Contribution} }} Data-efficiency and generalization are key challenges in deep learning, and representation learning has been at the heart of deep learning \cite{bengio2012deep}. Recently, self-supervised or weakly supervised models have been leveraged to learn from large-scale uncurated datasets and have shown sample-efficient transfer to labeled tasks \cite{chen_big_2020, radford2021learning, henaff2020data, he2020momentum, devlin_bert_2019, radford2019language}. However, commonly used transfer techniques, e.g., fine-tuning or distillation, do not currently support few-shot, multilabel, and continual learning. Few-shot learning (FSL) has made great strides in the area of sample-efficient learning \cite{wang2020generalizing}. However, FSL models are pretrained on large, domain-specific, and expensive-to-label datasets and have not leveraged pretrained models to avoid training on large and domain-specific labeled datasets. Also, FSL methods do not outperform pretrained models when domain shift is present \cite{chen2019closer, kornblith2019better}. We consider the problem of enabling \textit{few-shot, multilabel, and continual learning} for real-world downstream tasks, and investigate combining representation learning from pretrained self-supervised or weakly supervised models with few-shot, multilabel, and continual learning techniques. Our model \textbf{CLIPPER} {(CLIP PERsonalized)} uses image representations, i.e., embeddings, from CLIP, a weakly-supervised image representation learning model, for FSL. Inspired by Weight Imprinting \cite{qi_low-shot_2018}, an FSL method, we develop an approach called Multilabel Weight Imprinting for few-shot, multilabel, and continual learning. CLIPPER combines image embeddings from CLIP along with Multilabel Weight Imprinting for continual and multilabel few-shot learning. We evaluated CLIPPER on 10 single-label and 5 multi-label datasets. CLIPPER shows robust and competitive performance, e.g., it outperforms the state-of-the-art FSL method on MiniImagenet. We set benchmarks for few-shot, continual, and multilabel learning on several different datasets. We make 3 key contributions. \begin{enumerate}[topsep=0pt,itemsep=-1ex,partopsep=1ex,parsep=1ex] \item A new methodology combining the flexibility of few-shot learning methods with the sample-efficiency and generalizability of transfer learning methods using self-supervised or weakly supervised pretrained models. Our method eliminates the need for data- and compute-intensive pretraining on large, domain-specific, and labeled datasets for FSL. \item A modified FSL technique, which enables few-shot, continual, and multilabel learning. Combined with our first contribution, our second contribution enables few-shot, continual, and multilabel learning using self-supervised or weakly supervised pretrained models. \item Evaluations and benchmarks for few-shot, continual, and multilabel learning on 15 multilabel and single-label datasets, showing the robust and competitive performance of our technique. \end{enumerate} \section{Related Work} \subsection{Few-shot Learning (FSL)} There are three types of approaches for FSL: model-, metric-, and optimization-based. Unlike previous work, we use a pretrained weakly supervised model for data- and compute-efficient training. Our Multilabel Weight Imprinting technique lies in the category of metric-based approaches \cite{koch2015siamese, snell_prototypical_2017, sung_learning_2018, vinyals_matching_2017}. More specifically, we use a prototype-based metric-learning approach, as they assign trainable proxies to each category and enable faster convergence via element-category comparison, instead of element-wise comparisons. Our work extends a previous FSL technique, called weight imprinting \cite{qi_low-shot_2018}. We not only use a pretrained base model \cite{qi_low-shot_2018}, instead of training a base network from scratch, but we also extend weight imprinting to enable multilabel and continual learning. Other metric-based methods are complementary to our approach and our model can be further extended, e.g., with MatchingNet-like attention \cite{vinyals_matching_2017} or with RelationNet-like relation learning \cite{sung_learning_2018}. Model-based methods \cite{santoro2016one, munkhdalai_meta_2017} use especially designed models for rapid parameter updates, and optimization-based techniques \cite{ravi_optimization_2016, finn_model-agnostic_2017, nichol2018first} adjust the optimization method to meta-learn efficiently. Recent research indicates that learning a good embedding model can be more effective than sophisticated meta-learning algorithms \cite{tian2020rethinking} and efficient meta-learning may be predominantly due to the reuse of high-quality features \cite{raghu2019rapid}. Nonetheless, these techniques, though relatively training-intensive, are complementary to our work and may be used to improve both upstream and downstream models. \subsection{Self-supervised Representation Learning} Self-supervised and weakly supervised models have been used in natural language processing \cite{dai2015semi, radford2018improving, devlin_bert_2019} and computer vision \cite{henaff2020data, he2020momentum, chen_simple_2020, chen_big_2020, radford2021learning} to learn from large-scale unlabeled or weakly labeled datasets. Though pre-training is still imperfect \cite{ericsson2020well, mahajan2018exploring}, pretrained models trained on large-scale datasets have shown robust and sample-efficient transfer to diverse tasks \cite{he2020momentum, henaff2020data, chen_big_2020, radford2021learning}. Transfer learning is closely related to few-shot learning, but FSL does not use a pretrained method. Instead, FSL is trained and evaluated using the same distribution and does not necessarily outperform transfer learning when domain shift is present \cite{chen2019closer}. Transfer learning, however, could benefit from the specialized FSL techniques \cite{kornblith2019better}. Also, to the best of our knowledge, unlike our work, transfer learning using pretrained models has not been combined with multi-label and continual learning. Like previous work, we use self-supervised learning via data augmentation to boost FSL \cite{gidaris2019boosting, qi_low-shot_2018}. \subsection{Multilabel and Continual Learning} Continual learning techniques \cite{mai2021online} include regularization-based methods (e.g., Elastic Weight Consolidation), memory-based methods (e.g., Incremental Classifier and Representation Learning \cite{rebuffi2017icarl}), and parameter isolation (like Continual Neural Dirichlet Process Mixture). Previously used continual techniques, however, did not use pretrained models for few-shot, multilabel, and continual learning. Common multilabel classification techniques include ML-kNN, Multi-label DecisionTree, etc \cite{devkar2017survey}. Multi-Label Image Classification has also been done using knowledge distillation from weakly supervised detection \cite{liu2018multi}. However, none of the existing methods combine multilabel, continual, and few-shot learning, especially using pre-trained models. Several multilabel and continual learning techniques, nonetheless, are complementary to our work and can be extensions of our work. \section{Approach} \subsection{Desiderata} We outline 3 desiderata for real-world computer vision applications. First, \textbf{few-shot learning} so that the applications can start well in data-scarce scenarios and can also be customized and personalized for different needs. Second, \textbf{continual learning} to incrementally learn new information and avoid catastrophic forgetting, e.g., replacing of older classes when new ones are added. Third, \textbf{multilabel learning} as the right label may not be just one label but a subset of all the given labels, including 0 to all labels. The multi-label case is important for not only assigning multiple labels to a particular data point but also for assigning zero labels, in case we get data points that we currently do not have labels for, i.e., the continual learning case. Continual learning often considers the addition of data points along with their respective labels. However, we consider the more realistic continual case when a point may be added even before their label is added and thus, the model needs to assign no label. \subsection{Decisions} We made the following three design choices to enable few-shot, multilabel, and continual learning. \textbf{Pretrained base model}: FSL models are typically pre-trained on large domain-specific training sets, which contain examples not in the support/test set. The models are then trained and tested on support and test sets, which have the same classes. Large-scale, domain-specific, and labeled datasets, however, may not always be available in real-world settings. Also, FSL models trained on domain-specific sets may not generalize well to domain shifts \cite{hu2021well}. Large-scale self-supervised or weakly supervised models, on the other hand, learn good representations and can be fine-tuned for data-efficient and diverse downstream tasks \cite{chen_big_2020, radford2021learning}. We use pretrained models trained on diverse datasets as base models for FSL, instead of training base models from scratch on domain-specific datasets. As a result, unlike FSL methods, we only train with a support test, which we call train set. \textbf{Weight Imprinting (WI):} Weight imprinting \cite{qi_low-shot_2018} is a FSL learning method that learns a linear layer on top of the embeddings, where the columns of the linear layer weight matrix are prototype embeddings for each class. Many self-supervised or weakly supervised models have been shown to learn linearly-separable embeddings using linear probes \cite{radford2021learning} and thus, a linear layer can be added to pretrained embeddings to classify different classes. Compared to transfer learning, which learns a fixed number of classes, weight imprinting adds new classes as new columns of the linear layer weight matrix, making adding classes computationally and conceptually simpler and avoiding catastrophic forgetting. Thus, weight imprinting supports prototype-based few-shot and continual learning. \textbf{Sigmoids, not Softmax:} The original weight imprinting model uses softmax and thus is compatible with single-label classification. We replace the softmax with sigmoid activations for each class in weight imprinting to enable multi-label learning. Sigmoids also support an output of 0 labels for continual learning, i.e., when the label for a given data point has not yet been added to the label set. \subsection{Details} We created a multilabel version of weight imprinting \cite{qi_low-shot_2018}, called \textbf{Multilabel Weight Imprinting (MWI)}. Our model has two parts. First, an embeddings extractor, $\phi : \mathbb{R}^N \rightarrow \mathbb{R}^D$, maps input image $x \in \mathbb{R}^N$ to a $D$-dimensional embedding vector $\phi(x)$, followed by an $L_2$ norm. Second, a sigmoid function, $f(\phi(x))$, maps the embedding using sigmoid activations for each category. \[f_{i}(\phi(x)) = \frac{1}{1-exp(-w_i^T \phi(x))} \] where $w_i$ is the $i$-th column of the weight matrix normalized to unit length (with no bias term). Each column of the weight imprinting matrix is a template of the corresponding category. The linear layer computes the inner product between the input embeddings $\phi(x)$ and each template embedding $w_i$. The result represents `close-by' templates in the embedding space using a threshold function. \[\hat{y} = sgn (w^T \phi(x) - \vartheta)\] where $sgn$ is the sign function and $\vartheta$ is the threshold. \section{Implementation} \begin{figure} \centering \includegraphics[width=\linewidth]{clip.jpg} \caption{CLIPPER (CLIP-PERsonalized) uses embeddings from CLIP's vision transformer with Multilabel Weight Imprinting technique for few-shot, multilabel, and continual learning.} \label{fig:architecture} \end{figure} We share our implementation details below, model architecture in Fig \ref{fig:architecture}, and algorithm in Appendix. \textbf{Embeddings Generator:} Weight imprinting \cite{qi_low-shot_2018} uses a base classifier trained on ``abundant'' labeled training samples. We replace the base classifier with CLIP (ViT B/32), a pretrained weakly supervised model \cite{radford2021learning}. We do not re-train or fine-tune the weights of the pretrained CLIP model. As shown in section 6 (Figure \ref{fig:fig1}), we compared embeddings from different supervised, self-supervised, and weakly supervised models, and chose CLIP because it had the best FSL performance using WI. \textbf{Image Embeddings:} We embed images using CLIP's vision transformer and then use the normalized embeddings for multilabel weight imprinting. Compared to weight imprinting \cite{qi_low-shot_2018}, which used 64-dimensional embeddings, we use 512-dimensional embeddings from CLIP. Qi et al. \cite{qi_low-shot_2018} also tried 512-dimensional embeddings and reported no significant effects on the results. \textbf{Multilabel Weight Imprinting (MWI):} The MWI layer is a single dense layer with an input size equal to the embedding size of the embeddings generator and output equal to the number of classes. We initialize the MWI weights as an average of the embeddings for each class corresponding to the weight column. We normalize the weights columns and use sigmoid activations with a threshold. When training the MWI layer, we use the binary cross-entropy loss with an Adam optimizer \cite{kingma2014adam}. \textbf{MWI+ = MWI + Training (T) + Augmentations (A)}: When training with non-trivial (nt) augmentations, we use 3 types of augmentations \cite{chen_simple_2020}: i. random crop, resize, and random horizontal flip; ii. random color jitter; iii. random Gaussian blur. Trivial (t) augmentations refer to repeating the image. \textbf{Continual Learning (CL)} We use Experience Replay (ER) \cite{lin1992self}, which involves keeping a memory of old data and rehearsing it. ER has been used for CL \cite{rolnick2018experience, chaudhry2019tiny, hayes2019memory} and has been shown to outperform many CL approaches with and without a memory buffer \cite{chaudhry2019tiny}. In our multilabel continual learning setting, we retrain the old data with \textit{having/not having} the new label when new labels are received. \section{Experiment Study} \subsection{Datasets} We selected 10 single-label and 5 multi-label datasets based on 5 reasons: i. \textit{Few-shot learning: } We added commonly used datasets for FSL; ii. \textit{Diversity:} We included diverse datasets to evaluate performance under distributional and task shifts; iii. \textit{Robustness:} We also picked an adversarial example dataset to evaluate robustness; iv. \textit{Multilabel settings:} We chose multilabel datasets, including object detection, fine-grained detection, and overlapping labels; v. \textit{AI for good:} We included a medical dataset to illustrate the broader impact of our work. Our dataset list is in Table \ref{tab:datasets}. \subsection{Evaluations} We compared FSL in 7 settings: i. using different embeddings generators; ii. using sigmoid (MWI) versus softmax (WI) activations; iii. with and without training (T) and augmentations (A), both trivial (t) and non-trivial (nt) augmentations; iv. in 4 FSL settings like \cite{sung_learning_2018}): (5-way 5-shot, 15 test; 20-way 5-shot, 5 test; 5 way 1 shot, 19 test; 20-way 1-shot, 10 test); v. in continual learning settings; vi. with CLIP's zero-shot and FSL linear probe; vii. with state-of-the-art (SOTA) results -- there are no previous few-shot, multi-label, and continual learning evaluations, but we compare with FSL and also full training/test set evaluations. All evaluations are 5-way 5-shot, except for Ch (results in Appendix). We randomly sample classes and data points from each dataset 100 times and average the results. \begin{table}[] \caption{Details about our chosen datasets, including their abbreviations (Abbr.).} \label{tab:datasets} \centering \begin{tabular}{lllll} Dataset Name & Abbr. & SOTA & Content & Selection Reason \\ \hline \multicolumn{5}{l}{\textbf{Single}} \\ Omniglot \cite{lake2015human} & OM & \cite{liu2019decoder} & Handwritten chars & Few-shot \\ MiniImagenet \cite{vinyals_matching_2017} & MI & \cite{luo2019direction} & ImageNet subset & Few-shot\\ Labeled Faces in the Wild \cite{huang2008labeled} & LFW & \cite{chrysos2020p} & Faces & Diversity - Faces \\ UCF101 \cite{soomro2012ucf101} & UCF & \cite{kalfaoglu2020late} & Action videos & Diversity - Actions \\ Imagenet-R \cite{hendrycks2020many} & IR & \cite{radford2021learning} & ImageNet art & Diversity - Art \\ Imagenet-Sketch \cite{wang2019learning} & IS & \cite{wang2019learning} & Imagenet sketches & Diversity - Sketch \\ Indoor Scene Recognition \cite{quattoni2009recognizing} & ISR & \cite{rahimzadeh2021wise} & Indoor location & Diversity - Indoor \\ CIFAR10 \cite{Krizhevsky09learningmultiple} & C10 & \cite{foret2020sharpness} & 10 classes & Diversity \\ Imagenet-A \cite{hendrycks2019nae} & IA & \cite{radford2021learning} & Difficult images & Robustness \\ Colorectal Histology \cite{kather2016multi} & CH & \cite{ghosh2021colorectal} & Medical Images & AI for good \\ \multicolumn{5}{l}{\textbf{Multi-label}} \\ CelebA Attributes \cite{liu2018large} & CAA & \cite{kehrenberg2020null} & 40 attribute & Label overlap \\ UTK Faces \cite{zhifei2017cvpr} & UTK & \cite{karkkainen2019fairface} & Gender, age, race & Label overlap\\ Yale Faces \cite{georghiades2001few} & YF & \cite{khalili2019robust} & 11 face labels & Label overlap \\ Common Objects in Context \cite{lin2014microsoft} & COCO & \cite{ridnik2021imagenet} & 90 objects & Object Detection \\ iMaterialist (Fashion) \cite{guo2019imaterialist} & IM & \cite{guo2019imaterialist} & Fashion/apparel & Fine-grained \\ \hline \end{tabular} \end{table} \subsection{Metrics} Commonly used single-label classification metrics, e.g., top-1 accuracy, are not applicable in multilabel settings. Multilabel evaluations have used different metrics, including class and overall precision, recall, and F1, as well as mean average precision (mAP) \cite{wang2016cnn}. We calculated a total of 13 diverse metrics for each of our evaluations and included all the results in the supplementary materials. We primarily use overall \textbf{F1-score} in this paper since F1-score accounts for class imbalance, which may be present in multilabel datasets, especially in real-world settings. The only downside of F1-score is that compared to mAP, it is threshold-dependent. However, in real-life situations, the threshold is also important, and therefore, we also discuss the optimal cut-off thresholds for our evaluations. To compare our results with state-of-the-art (SOTA) results, we also report the metrics used by different SOTA results, i.e., top-1 accuracy for single-label datasets and average class accuracy (cAc) for multi-label datasets, except COCO, which uses mAP. We report these metrics along with F1-scores so that the F1-scores can be compared to the different SOTA metrics. SOTA references are in Table \ref{tab:datasets}. \section{Results} We share our main results in this section and ablations in the next. First, CLIP+WI performance is similar to CLIP's linear probe performance, possibly because both are linear layers (Fig \ref{fig:fig1}). Second, without training and augmentations, MWI performs worse than WI for single-label classifications -- MWI F1-score is worse than WI F1-score (Fig \ref{fig:fig1}), even though the accuracies are comparable (Fig \ref{fig:fig7}). Third, MWI with training (50-80 epochs) and augmentations (10 trivial/non-trivial), i.e., MWI+, does at least as well as WI using CLIP (Fig \ref{fig:fig1}-\ref{fig:fig7}), CLIP's linear probes (Fig -\ref{fig:fig1}), and state-of-the-art baselines (Fig \ref{fig:fig7}). MWI and MWI+ are also compared with SOTA and CLIP's baselines in Table \ref{tab:final}. \begin{table}[] \caption{Comparing CLIPPER Multilabel Weight Imprinting (MWI) with SOTA and CLIP baselines\textsuperscript{\ref{clip}} } \label{tab:final} \centering \begin{tabular}{llllllllllllllll} \toprule & C10 & Ia & Ir & Is & Isr & Lfw & Mi & Om & Ucf & Ca & Co & Im & Ut & Yf & Ch \\ \hline 1 & .91 & .85 & .89 & .60 & .74 & 1.0 & .92 & 1.0 & .99 & .82 & .84 & .72 & .86 & .85 & .93 \\ 2 & .91 & .75 & .82 & .91 & .95 & 1.0 & .95 & .96 & .95 \\ 3 & .89 & .75 & .79 & .89 & .94 & 1.0 & .94 & .94 & .94 & .69 & .88 & .79 & .74 & .88\\ 4 & .70 & .54 & .60 & .72 & .83 & .94 & .78 & .66 & .83 & .62 & .75 & .48 & .60 & .66 \\ 5 & .90 & .74 & .80 & .90 & .94 & 1.0 & .94 & .95 & .94 & .69 & .73 & .56 & .78 & .79 & .69 \\ 6 & .96 & .90 & .92 & .96 & .98 & .99 & .98 & .98 & .98 & .76 & .89 & .83 & .86 & .91 & .92 \\ 7 & .91 & .77 & .83 & .92 & .96 & 1.0 & .95 & .97 & .95 & -- & .87 & -- & -- & -- \\ \multicolumn{16}{l}{\textbf{SOTA}(1); \textbf{CLIP} Lin. Probe Ac(2); \textbf{MWI} Ac(3),F1(4); \textbf{MWI+T+A} F1(5),CAc(6),Top1/mAP(7)} \\ \bottomrule \end{tabular} \end{table} \begin{figure} \includegraphics[width=\linewidth]{fig1_bigger.png} \caption{Comparing embeddings models (left) and Multilabel Weight Imprinting results (right).} \label{fig:fig1} \end{figure} \begin{figure}[h!] \includegraphics[width=\linewidth]{fig7_bigger.png} \caption{Comparing SOTA, WI, and MWI for single-label (left) and multi-label (right) datasets.} \label{fig:fig7} \end{figure} \textbf{Comparing CLIP's embeddings: } We compared embeddings from different pretrained supervised (Resnet50 \cite{he2016deep}, VGG16 \cite{simonyan2014very}, Inception V3), self-supervised (SimCLR v2 \cite{chen_big_2020}, MoCo v2 Resnet50 \cite{chen_simple_2020, chen2020improved}, PCL Resnet50 \cite{tang2018pcl}, SwAV Resnet50 \cite{caron2020unsupervised}), and weakly supervised (CLIP \cite{radford2021learning}) models (Figure \ref{fig:fig1} left). CLIP is trained on 400 million images, while the others are on 14 million Imagenet images. We have three key findings. First, CLIP gives the best results, possibly because CLIP is trained on a bigger dataset than other pretrained models. Second, SimCLR's performance is closest to CLIP, even though it was trained only on a smaller dataset than CLIP. Third, Resnet50-based models performed much worse than the other models, even though all models, except CLIP, were trained on Imagenet. \textbf{SOTA caveats:} There are 3 caveats to our SOTA comparisons (Table \ref{tab:final}). First, to the best of our knowledge, there is no prior work on multilabel few-shot learning and hence, we are setting new benchmarks and have no direct prior work to compare with. Second, even though we list the SOTA 5-way 5-shot results for OM and MI, there are two main differences: i. Previous few-shot results were pre-trained on large-scale, domain-specific, and labeled datasets, whereas our model is trained only on the few-shot set. Thus, performance for new domains like OM may not be as good as few-shot models pre-trained on OM; ii. Also, previous few-shot works did not do multilabel few-shot learning. Third, we list SOTA for other datasets, which have previously not been evaluated for few-shot learning, so the SOTA results are for full dataset training and testing and we only list them as a reference. \footnote{\label{clip}Both 1. Ia and Ir \& 2 in Table \ref{tab:final} use CLIP but 2 uses the ViT B/32 architecture whereas 1. Ia and Ir use the ViT L/14-336px architecture. L/14-336px is a bigger and better performing architecture but is not public \cite{radford2021learning}} \textbf{CLIP baselines:} Since we use embeddings from CLIP, we also compare our CLIP + MWI results to CLIP's linear probe, zero-shot, and CLIP + WI performance. We use both F1-score and accuracy, and all comparisons, other than zero-shot, are 5-way 5-shot. MWI+ using CLIP is comparable to CLIP's baselines, but unlike the linear probe, also enables few-shot, multilabel, and continual learning. \section{Ablations} \subsection{MWI: Without Training and Augmentations} \begin{figure} \includegraphics[width=\linewidth]{fig2_3.png} \caption{Comparing metrics, without training and augmentations, for single- and multi-label datasets.} \label{fig:fig2_3} \end{figure} We compare CLIPPER's 5-way 5-shot performance on 9 \textbf{single-label datasets} (Figure \ref{fig:fig2_3} left) and 5 \textbf{multilabel datasets} (Figure \ref{fig:fig2_3} right). For single-label, we perform two evaluations: i. Weight imprinting with softmax activations (f1-score and accuracy); ii. Multilabel weight imprinting with sigmoids (f1-score, top-1 accuracy, and per-class accuracy). For multilabel datasets with bounding boxes, i.e., COCO and iMaterialist, we compared full-full and patch-patch configurations, where `full' represents the full image and `patch' represents the bounding box of the relevant object. In n-m, n represents the training configuration and m represents the testing configuration. We had three key findings (Fig \ref{fig:fig2_3}). First, for single-label datasets, WI accuracy is comparable to MWI top-1 accuracy, which means that the sigmoid activation can get us comparable results to the softmax activation. Though, as expected, MWI F1-scores are much lower in value than MWI Top-1 accuracy. Second, multi-label datasets on average have much lower performance than single-label datasets, which is expected as they have more labels than single-label datasets. Third, the patch-patch configuration works best for iMaterialist whereas the full-full configuration works best for COCO, possibly because the background is meaningful in COCO but mostly white in iMaterialist. \subsection{MWI+: With Training and Augmentations} \begin{figure} \includegraphics[width=\linewidth]{fig4.png} \caption{Comparing MWI with training and augmentations for single- and multi-label datasets}. \label{fig:fig4} \end{figure} We evaluated the performance of Multilabel Weight Imprinting by adding \textbf{training (T) and augmentations (A)} (Figure \ref{fig:fig4}). We had three key findings. First, CLIPPER's performance improved with both training and augmentations -- after training and augmentations, F1-scores for multi-label weight imprinting were comparable to the F1-scores for weight imprinting with softmax. Second, the performance saturates around 50-80 epochs, and trivial (t) augmentations, i.e., image repetitions, are as good or sometimes even better than non-trivial (nt) augmentations. Third, with training, the best threshold values stabilized around 0.5 for most datasets (Figure \ref{fig:thresh} (left). We also compared 4 \textbf{few-shot learning settings} (Figure \ref{fig:fig5}): 5-way 5-shot, 20-way 5-shot, 5 way 1 shot, 20-way 1-shot. The performance worsens with decreasing shots and with increasing classes. \begin{figure} \includegraphics[width=\linewidth]{fig5.png} \caption{Comparing different few-shot settings with MWI+ (L:single-label, R:multi-label datasets)} \label{fig:fig5} \end{figure} \begin{figure} \includegraphics[width=\linewidth]{fig6.png} \caption{MWI+ Continual learning results for increasing classes (L:single-, R:multi-label dataset)} \label{fig:fig6} \end{figure} \begin{figure}[h!] \includegraphics[width=\linewidth]{thresh.png} \caption{Optimal thresholds with (left) and without (right) continual learning for all datasets.} \label{fig:thresh} \end{figure} \subsection{Continual learning} We evaluated 5 way 5 shot continual learning. We incrementally added the number of labeled classes and their respective training data and labels, while keeping the test set fixed. We had three key findings. First, CL performance (Figure \ref{fig:fig6}) varies with the number of classes but reaches approximately the same 5-way 5-shot value with continual learning as it does without continual learning (\ref{fig:fig4}). Second, the optimal-performance thresholds vary with the number of classes and we share the best accuracies and their respective thresholds for each dataset for different number of classes (Figure \ref{fig:thresh} right). Third, the thresholds are higher with lower number of classes, possibly because of lesser training data, but converge to approximately the same 5-way 5-shot value with and without continual learning (Fig \ref{fig:thresh}). \section{Discussion and Limitations} With advances in representation learning, either using generative or contrastive models, the question arises: \textit{how to best use the representations in downstream tasks}. Previous work suggests, ``combining the strength of zero-shot transfer with the flexibility of few-shot learning is a promising direction'' \cite{radford2021learning} and ``obtain better results...by combining few-shot learning methods with fine-tuning'' \cite{kornblith2019better}. We outline few-shot, continual, and multilabel learning as the desiderata for downstream tasks and introduce a technique, called Multilabel Weight Imprinting, to meet the desiderata. Our model uses embeddings from a pertained CLIP model and shows promising performance on diverse and challenging tasks. We set few-shot, multilabel, and continual learning benchmarks for many datasets. Our work has three \textbf{key findings}. First, using pretrained models with an existing FSL technique, i.e., weight imprinting \cite{qi_low-shot_2018}, enables sample-efficient learning with two additional benefits: i. Unlike commonly-used transfer learning techniques like fine-tuning and distillation, we have a prototype for each class and can flexibly add/update each class prototype without influencing (e.g., forgetting) the other class prototypes; ii. Unlike commonly-used FSL methods, the base model need not be trained with computationally-intensive techniques involving large, domain-specific, and expensive-to-label datasets. Second, replacing weight imprinting's softmax function with a sigmoid and threshold function enables multilabel weight imprinting, and using training and augmentations helps improve performance. Finally, adding experience reply enables multilabel continual learning. Our work has three \textbf{key limitations}: i. Multilabel learning has poorer and even threshold-dependent performance compared to single-label learning, but multi-label learning is still more realistic than single-label classification as even single-label datasets have multiple labels \cite{yun2021re}; ii. Prototype-based few-shot learning scales the number of prototypes with the number of classes and comparing with every single prototype may not be efficient. Thus, efficient and scalable methods, e.g., hierarchical prototypes, are needed; iii. Experience replay for multilabel continual learning is memory-inefficient and memory-efficient continual learning, e.g., prototype-based contrastive learning, could be leveraged. We have three key directions for \textbf{future work}: i. Use downstream few-shot learning for correcting/filtering labels from upstream models, without necessarily sending data to the upstream models; ii. Make few-shot, multilabel, and continual learning memory-efficient, robust, and deployable; iii. Deploy and test in real-world settings, e.g., for human-in-the-loop and personalized applications. \section{Broader Impact} We highlight three key areas for positive impact of our work. First, we designed our model for few-shot, multilabel, and continual learning to enable real-world sample-efficient applications, including personalized and AI for good applications (more details in appendix). Second, since we do not train the upstream model, the data does not have to be sent to the upstream model, affording privacy-preserving and offline model training. Third, since we only train a linear layer, our model affords easy and lightweight real-world training and deployment, including on mobile, web, and wearable devices, especially if the pretrained base model can be mobile-optimized \cite{howard2017mobilenets, tan2019efficientnet} as in \cite{khan2021cvpr}. Like many machine learning techniques, our model is as good as its applications. We have made our model flexible, easy-to-use, and easy-to-train -- it can be used with any state-of-the-art pre-trained model, trained and run using free Google Colab notebooks, and personalized using only a few examples. Moreover, few-shot and personalized learning may also help mitigate data/labeling bias. Thus, we hope that our work will enable interdisciplinary stakeholders to ethically design and deploy personalized, privacy-preserving, and meaningful real-world deep learning applications. \section{Conclusion} Data-efficiency and generalization are key challenges for deep learning. Self-supervised or weakly supervised models trained on unlabeled or uncurated datasets have shown promising transfer to few-shot tasks. Few-shot learning methods have also demonstrated sample-efficient learning. We highlight the need for few-shot, multilabel, and continual learning, and developed a technique, called Multi-label Weight Imprinting (MWI), for few-shot, continual, and multi-label learning. Unlike previous FSL techniques, our model, CLIPPER, uses MWI with pretrained representations from a weakly-supervised model, i.e., CLIP. Thus, CLIPPER combines the sample-efficiency and generalizability of transfer learning with the flexibility and specialization of FSL methods. CLIPPER shows robust and competitive performance and is the first step in the direction of using pretrained models for few-shot, multilabel, and continual learning. Our model is also lightweight and the data does not have to be sent back to the upstream model, enabling privacy-preserving and on-device downstream training. Thus, our model enables few-shot, multilabel, and continual learning, especially for easy-to-train, light-weight, and privacy-preserving real-world applications.
{'timestamp': '2021-06-04T02:06:30', 'yymm': '2106', 'arxiv_id': '2106.01499', 'language': 'en', 'url': 'https://arxiv.org/abs/2106.01499'}
arxiv
\section{Introduction} Directed acyclic graph (DAG) is an important tool to characterize pairwise directional relations among multivariate and high-dimensional random variables. It has been frequently used in a wide range of scientific applications. One example is the gene regulatory network analysis in genetics \citep{Sachs2005}. The time-course expression data of multiple genes are measured over multiple cellular samples through microarray or RNA sequencing, and the goal is to understand the regulatory activation or repression relations among different genes. Another example is the brain effective connectivity analysis in neuroscience \citep{Garg2011}. The time-course neural activities are measured at multiple brain regions for multiple experimental subjects through functional magnetic resonance imaging, and the goal is to infer the influences of brain regions exerting over each other under the stimulus. There is a large body of literature studying penalized estimation of DAGs given the observational data \citep[see, e.g.,][among many others]{Spirtes2000, van2013, zheng2018dags, Yuan2019}. These existing works all imposed some specific model structures, most often, linear models or additive models. More recently, there have emerged a number of proposals in the computer science literature that used neural networks or reinforcement learning to estimate DAGs, which have been shown to be more effective for learning nonlinear models \citep{yu2019dag, zheng2020learning, zhu2020causal}. While all these works have made crucial contributions to estimate directional links, DAG \emph{estimation} is an utterly different problem from DAG \emph{inference}. The two problems are closely related, and both can, in effect, identify directional relations, i.e., important links of a DAG. Besides, DAG inference usually relies on DAG estimation as a precedent step. Nevertheless, estimation does not produce an explicit quantification of statistical significance as inference does. Bayesian networks have been used for DAG estimation and inference. However, the difficulty of inferring Bayesian networks lies in the computational complexity of searching through all possible graph structures, which is NP-hard \citep{Chickering2004}. As a result, the dimension of the Bayesian networks is often small \citep{Friston2011}. There are very few frequentist inference solutions for directional relations of DAG models. Only recently, \citet{Jana2019Inf} proposed a de-biased estimator to construct confidence intervals for the edge weights in a DAG, whereas \citet{li2019likelihood} developed a constrained likelihood ratio test to infer individual links or some given directed paths of a DAG. These works are probably the most relevant to our proposal. However, both methods focused on Gaussian linear DAGs, and cannot be easily extended to more general nonlinear DAG models. Moreover, all the above works considered the setting where the data observations are independent and identically distributed. Learning DAGs from time-dependent data remains largely unexplored. There is another body of literature studying conditional independence testing; see \citet{li2019nonparametric} for an overview and the references therein. Conditional independence testing is closely related to DAG inference, and is to serve as a building block of our proposed testing procedure. On the other hand, naively performing conditional independence test on two variables given the rest would fail to infer their directional relationships; see Section \ref{sec:equiv} for details. Besides, most conditional independence testing methods assume the data observations are independent, and are not suitable for the setting where the measurements are time-dependent. In this article, we propose a new testing method for \emph{statistical inference} of individual links or some given paths in a large and general DAG given the time-dependent observational data. The new test hinges upon some highly flexible neural networks-based learning techniques. The associations among the random variables can be either linear or nonlinear, and the variables themselves can be either continuous or discrete-valued. As a result, our proposal makes a number of unique and useful contributions. First, rigorous inference of directional relations in DAGs is a vital and long-standing problem. But the existing solutions rely on particular model structures such as linear or additive models, and mostly deal with i.i.d.\ data. Such requirements can be restrictive in numerous applications, since the actual relations may be nonlinear and the data are correlated. By contrast, we only require an additive noise structure \citep{Peters2014causal}. To the best of our knowledge, our work is the first frequentist solution for general DAG inference with time-dependent data. Second, we propose a novel testing procedure for inferring individual links or some given paths in a large and general DAG, by employing a number of state-of-the-art deep learning techniques that are highly flexible and can capture nonlinear associations among high-dimensional variables. We begin with a new characterization of pairwise directional relations under the additive noise assumption; see Theorem \ref{thm1}. Based on this characterization, we propose a testing procedure that integrates the following three key components: \vspace{-0.1in} \begin{enumerate}[(a)] \setlength\itemsep{-0.25em} \item A DAG structural learning method based on neural networks or reinforcement learning to estimate the DAG; \item A supervised learning method based on neural networks to estimate the conditional mean; \item A distribution generator produced by generative adversarial networks \citep[GANs]{goodfellow2014generative} to approximate the conditional distribution of the variables in the DAG. \end{enumerate} \noindent We remark that, we employ modern machine learning techniques such as neural networks and GANs to help address a classical statistical inference problem. Conceptually, they serve as nonparametric learners, and play a similar role as splines and reproducing kernels type learning methods. But they are often more flexible and can handle more complex data. With more and more efficient implementations, and better understanding of their statistical properties \citep{farrell2018deep, Bauer2019, chen2020statistical, WangX2021}, this family of deep learning methods offer a powerful set of tools for classical statistical analyses. Our proposal is an example of harnessing such power, as the use of these machine learning techniques allows us to accurately estimate the DAG structure, the conditional means, as well as the distribution functions, and to improve the power of our test. Third, we establish the asymptotic size and power guarantees for the proposed test. We couple the three learners with the data-splitting and cross-fitting strategy to ensure the resulting test has the guaranteed theoretical properties under mild conditions on those learning methods. Actually our inferential framework is fairly general, and can work with a wide range of learning methods. Specifically, we only require the DAG learner to consistently estimate the ordering of the true DAG, and we show that the neural network-based DAG learner we choose satisfies this requirement. This is much weaker than requiring the DAG learner to be selection consistent, or to satisfy the sure screening property. Besides, we require the supervised learner and the distribution generator to converge, but at rates that are slower than the usual parametric rate. The capacity of modern neural networks-based learning methods and their successes in structural learning, prediction, and distribution modeling make these requirements achievable. Finally, to establish the consistency of the proposed test, we introduce a bidirectional asymptotic framework that allows either the number of subjects, or the number of time points for each subject, to diverge to infinity. This is useful for different types of applications. There are plenty of studies where the interest is about the directional relations for a general population, and thus it is reasonable to let the number of subjects or samples to go to infinity. Meanwhile, there are other applications, for instance, neuroimaging-based brain networks studies, where the number of subjects is almost always limited. On the other hand, the scanning time and the temporal resolution can be greatly increased. For those applications, it is more suitable to let the number of time points to diverge. The rest of the article is organized as follows. We formally define the hypotheses, along with the model and data structure, in Section \ref{sec:formulation}. We develop the testing procedure in Section \ref{sec:test}, and establish the theoretical properties in Section \ref{sec:theory}. We study the empirical performance of the test through simulations and a real data example in Sections \ref{sec:sim} and \ref{sec:realdata}. We discuss some extensions in Section \ref{sec:extensions}. All technical proofs are relegated to the supplementary appendix. \section{Problem formulation} \label{sec:formulation} In this section, we first present the DAG model, based on which we formally define our hypotheses. We next propose an equivalent characterization of the hypotheses, for which we develop our testing procedure. Finally, we detail the data structure. \subsection{DAG model} Consider $d$ random variables $X = (X_1, \ldots, X_d)^\top$, each with a finite fourth moment. We use a directed graph to characterize the directional relationships among these variables, where a node of the graph corresponds to a variable in $X$. For two nodes $i,j\in \{1,\ldots,d\}$, if $X_i$ directly influences $X_j$, then an arrow is drawn from $i$ to $j$, i.e., $i\rightarrow j$. In this case, $X_i$ is called a parent of $X_j$, and $X_j$ a child of $X_i$. A directed path in the graph is a sequence of distinct nodes $i_1, \ldots, i_{d'}$, such that there is a directed edge $i_k \to i_{k+1}$ for all $k=1,\ldots,d'-1$. If there exists a directed path from $i$ to $j$, then $X_i$ is called an ancestor of $X_j$, and $X_j$ a descendant of $X_i$. For node $X_j$, let $\hbox{PA}_j, \hbox{DS}_j$ and $\hbox{AC}_j$ denote the set of indices of the parents, descendants, and ancestors of $X_j$, respectively. Moreover, let $X_{\mathcal{M}}$ denote the sub-vector of $X$ formed by those whose indices are in a subset $\mathcal{M} \subseteq \{1, \ldots, d\}$. To rigorously formulate our problem, we make two assumptions. \vspace{-0.1in} \begin{enumerate}[({A}1)] \setlength\itemsep{-0.25em} \item The directed graph is acyclic; i.e., no variable is an ancestor of itself. \item The DAG is identifiable from the joint distribution of $X$. \end{enumerate} \noindent Assumption (A1) has been commonly imposed in directed graph analysis. It does not permit any variable to be its own ancestor. As a result, the relationship between any two variables is unidirectional. Assumption (A2) helps simplify the problem, and avoids dealing with the equivalence class of DAG. This assumption is again frequently imposed in the DAG estimation literature \citep{zheng2018dags,Yuan2019,li2019likelihood,zheng2020learning}. Inference with the equivalence class is beyond the scope of this article, and we leave it as future research. To meet the identifiability requirement, we consider a class of structural equation models that follow an additive noise structure, \begin{eqnarray}\label{eqn:model} X_j=f_j(X_{\scriptsize{\hbox{PA}}_j})+\varepsilon_j, \quad \textrm{ for any } j=1, \ldots, d, \end{eqnarray} where $\{f_j\}_{j=1}^d$ are a set of continuous functions, and $\{\varepsilon_j\}_{j=1}^{d}$ are a set of independent zero mean random errors. Model \eqref{eqn:model} permits a fairly flexible structure. For instance, if each $f_j$ is a linear function, then \eqref{eqn:model} reduces to a linear structural equation model. If each $f_j$ is an additive function, i.e., $f_j(X_{\scriptsize{\hbox{PA}}_j})=\sum_{k \in {\scriptsize{\hbox{PA}}_j}} f_{j,k}(X_k)$, then \eqref{eqn:model} becomes an additive model. In our test, we do \emph{not} impose linear or additive model structures. Moreover, we can easily extend the proposed test to the setting of generalized linear model, where the $X_j$ can be either continuous or discrete-valued. We discuss such an extension in Section \ref{sec:extglm}. When \eqref{eqn:model} holds, the corresponding DAG is identifiable under mild conditions \citep{Peters2014causal}. \subsection{Hypotheses and equivalent characterization} \label{sec:equiv} We next formally define the hypotheses we target, and then give an equivalent characterization. For a given pair of nodes $(j,k)$, $j,k=1, \ldots, d, j \neq k$, we aim at the hypotheses: \begin{eqnarray}\label{eqn:hypothesis} \mathcal{H}_0(j,k):k \notin \hbox{PA}_j, \quad \textrm{versus} \quad \mathcal{H}_1(j,k):k \in \hbox{PA}_j. \end{eqnarray} When the alternative hypothesis holds, we say $X_k$ directly influences $X_j$. In the following, we mainly focus on testing an individual directional relation $\mathcal{H}_0(j,k)$. We discuss the extensions of testing a directed pathway, or a union of directional relations in Sections \ref{sec:extpath} and \ref{sec:extunion}. We next consider a pair of hypotheses that involve two variables that are \emph{conditionally independent} (CI). The new hypotheses are closely related to \eqref{eqn:hypothesis}, but are not exactly the same. \vspace{-0.05in} \begin{eqnarray}\label{eqn:hypothesis1} \begin{split} \hspace{1cm} & \mathcal{H}_0^*(j,k):X_k\,\,\textrm{and}\,\, X_j\,\,\textrm{are}\,\,\textrm{CI\,\,given the rest of variables}, \,\,\, \textrm{ versus } \\ & \mathcal{H}_1^*(j,k):X_k\,\,\textrm{and}\,\, X_j\,\,\textrm{are}\,\,\textit{\hbox{not}}\,\,\textrm{CI\,\,given the rest of variables}. \end{split} \end{eqnarray} We point out that, testing for \eqref{eqn:hypothesis1} is generally \emph{not} the same as testing for \eqref{eqn:hypothesis}. To elaborate this, we consider a three-variable DAG with a v-structure. \begin{example}[v-structure]\label{examv} \tsb{Consider three random variables $X_1, X_2, X_3$ that form a v-structure, as illustrated in Figure \ref{fig1}(a), where $X_1$ and $X_2$ are the common parents of $X_3$. Even if $X_1$ and $X_2$ are \textit{marginally} independent, they can be \textit{conditionally} dependent given $X_3$. To better understand this, consider the following toy illustration. Either the ballgame or the rain could cause traffic jam, but they are uncorrelated. However, seeing traffic jam puts the ballgame and the rain in competition as a potential explanation. As such, these two events are conditionally dependent. Since $X_2$ is not a parent of $X_1$, both $H_0(1,2)$ and $H_1^*(1,2)$ hold. Consequently, testing for \eqref{eqn:hypothesis1} can have an inflated type-I error for testing \eqref{eqn:hypothesis}.} \end{example} \begin{figure}[t!] \centering \begin{tabular}{ccc} \includegraphics[width=3cm]{./fig/v_str.png} & \hspace{0.5in} & \includegraphics[width=6cm]{./fig/MLP1.png} \\ (a) & & (b) \end{tabular} \caption{(a) A three-variable DAG with a v-structure. (b) Illustration of multilayer perceptron with two hidden layers, $m_0=2$, $m_1=m_2=3$. Here $u$ is the input, $A^{(\ell)}$ and $b^{(\ell)}$ denote the corresponding parameters to produce the linear transformation for the $(\ell-1)$th layer.} \label{fig1} \end{figure} In the above example, we note that the reason that testing for \eqref{eqn:hypothesis1} is not the same as for \eqref{eqn:hypothesis} is because the conditioning set of $X_1$ and $X_2$ contains their common descendant $X_3$. This key observation motivates us to consider a variant of \eqref{eqn:hypothesis1}, which we show is equivalent to \eqref{eqn:hypothesis} under certain conditions. Specifically, for a given set of indices $\mathcal{M}\subseteq \{1,\ldots,d\}$ such that $j\notin \mathcal{M}$, and letting $X_{\mathcal{M}-\{k\}}$ denote the set of variables in $\mathcal{M}-\{k\}$, we consider the hypotheses: \vspace{-0.05in} \begin{eqnarray}\label{eqn:hypothesis2} \begin{split} &\mathcal{H}_0^*(j,k|\mathcal{M}):X_k\,\,\textrm{and}\,\, X_j\,\,\textrm{are}\,\,\textrm{CI\,\,given }X_{\mathcal{M}-\{k\}}, \,\,\,\,\,\textrm{versus}\,\,\,\,\\ &\mathcal{H}_1^*(j,k|\mathcal{M}):X_k\,\,\textrm{and}\,\, X_j\,\,\textrm{are}\,\,\textit{\hbox{not}}\,\,\textrm{CI\,\,given\,\,}X_{\mathcal{M}-\{k\}}, \end{split} \end{eqnarray} \begin{prop}\label{prop1} For a given pair of nodes $(j,k)$ such that $j \in \tsb{\hbox{DS}}_k$, $j, k = 1, \ldots, d$, and for any $\mathcal{M}$ such that $j \notin \mathcal{M}$, $\tsb{\hbox{PA}}_j\subseteq \mathcal{M}$ and $ \mathcal{M}\cap \tsb{\hbox{DS}}_j = \emptyset$, testing \eqref{eqn:hypothesis2} is equivalent to testing \eqref{eqn:hypothesis}. \end{prop} \noindent Proposition \ref{prop1} forms the basis for our test. That is, to infer the directional relations, we first restrict our attention to the pairs $(j,k)$ such that $j\in \hbox{DS}_k$. Apparently, $H_0(j,k)$ does not hold when $j \notin \hbox{DS}_k$. Next, when devising a conditional independence test for $H_0(j,k)$, the conditioning set $\mathcal{M}$ is supposed to contain the parents of node $j$, but \emph{cannot} contain any common descendants of $j, k$. Under these conditions, we establish the equivalence between \eqref{eqn:hypothesis2} and \eqref{eqn:hypothesis}. Next, we develop a test statistic for the hypotheses \eqref{eqn:hypothesis2}. We introduce a key quantity. Let $h$ denote a square-integrable function that takes $X_k$ and $X_{\mathcal{M}-\{k\}}$ as the input. Define \begin{eqnarray*} I(j,k|\mathcal{M};h)= {\mathbb{E}} \left\{ X_j - {\mathbb{E}} \left( X_j | X_{\mathcal{M}-\{k\}} \right) \right\} \left[ h\left( X_k,X_{\mathcal{M}-\{k\}} \right) - {\mathbb{E}} \left\{ h\left( X_k,X_{\mathcal{M}-\{k\}} \right) | X_{\mathcal{M}-\{k\}} \right\} \right]. \end{eqnarray*} \noindent Under the additive noise model \eqref{eqn:model}, the next theorem connects this quantity with the null hypothesis $\mathcal{H}_0^*(j,k|\mathcal{M})$ in \eqref{eqn:hypothesis2}. Together with Proposition \ref{prop1}, it shows that $I(j,k|\mathcal{M};h)$ can serve as a test statistic for \eqref{eqn:hypothesis2}, and equivalently, for \eqref{eqn:hypothesis} that we target. \begin{theorem}\label{thm1} Suppose \eqref{eqn:model} holds. For a given pair of nodes $(j,k)$ such that $j\in \tsb{\hbox{DS}}_k$, $j,k=1, \ldots, d$, for any $\mathcal{M}$ such that $j\notin \mathcal{M}$, $\tsb{\hbox{PA}}_j \subseteq {\mathcal{M}}$ and ${\mathcal{M}} \cap \tsb{\hbox{DS}}_j = \emptyset$, the null hypothesis $\mathcal{H}_0^*(j,k|\mathcal{M})$ in \eqref{eqn:hypothesis2} is equivalent to $\sup_h |I(j,k|\mathcal{M};h)|=0$ where the supremum is taken over all square-integrable functions $h$. \end{theorem} \noindent Theorem \ref{thm1} immediately suggests a possible testing procedure for \eqref{eqn:hypothesis2}. That is, we first employ a DAG estimator to learn the ancestors and descendants for node $j$. We then consider a natural choice for $h$, where $h\left( X_k, X_{\mathcal{M}-\{k\}} \right) = X_k$. Then $I(j,k|\mathcal{M};h)$ becomes \begin{align} \label{eqn:DGT} I(j,k|\mathcal{M};h) = {\mathbb{E}} \left\{ X_j - {\mathbb{E}} \left( X_j | X_{\mathcal{M}-\{k\}} \right) \right\} \left\{ X_k - {\mathbb{E}} \left( X_k|X_{\mathcal{M}-\{k\}} \right) \right\}. \end{align} This measure can be estimated by plugging in the estimators of the conditional mean functions $\widehat{{\mathbb{E}}} \left( X_j | X_{\mathcal{M}-\{k\}} \right)$ and $\widehat{{\mathbb{E}}} \left( X_k|X_{\mathcal{M}-\{k\}} \right)$. By Theorem \ref{thm1}, under the null hypothesis $\mathcal{H}_0^*(j,k|\mathcal{M})$, a consistent estimator for \eqref{eqn:DGT} should be close to zero. A Wald type test can then be devised to determine the rejection region. Such a test is similar in spirit as the tests of \citet{zhang2018measuring} and \cite{shah2018hardness}. Since it involves estimation of two conditional mean functions, we refer to it as the \emph{double regression-based test}. We later numerically compare our proposed test with this test in Section \ref{sec:sim}. However, a drawback of this test is that it may not have a sufficient power to detect $\mathcal{H}_1(j,k)$. As an illustration, we revisit Example \ref{examv}. For this example, consider the structural equation model: $X_1=\varepsilon_1$, $X_2=\varepsilon_2$, and $X_3=X_1^2+X_2+\varepsilon_3$. Under this model, $\mathcal{H}_1(1,3)$ holds. Meanwhile, $I(1,3) = {\mathbb{E}} (X_3-X_2)X_1 = {\mathbb{E}} \varepsilon_1^3$. When the distribution of $\varepsilon_1$ is symmetric, $I(1,3) = 0$, despite the fact that $X_1$ is a parent of $X_3$. As such, for this example, the double regression-based test is to have no power at all. This observation motivates us to consider multiple functions $h$, instead of a single $h$, to improve the power of the test. That is, we consider a large class of functions of $h$, compute $\{I(j,k|\mathcal{M};h):h\}$ for each $h$, then take the maximum of some standardized version of those measures to form our test statistic. We detail this idea in Section \ref{sec:test}, and numerically show that the resulting test is more powerful than the double regression-based test in Section \ref{sec:sim}. \subsection{Time-dependent observational data} Throughout this article, we use $X$ to denote the population variables, and $\mathbb{X}$ to denote the data realizations. Suppose the data come from an observational study, and are of the form, $\{\mathbb{X}_{i,t,j} : i=1, \ldots, N, t=1, \ldots, T_i, j=1, \ldots, d\}$, where $i$ indexes the $i$th subject, $t$ indexes the $t$th time point, and $j$ indexes the $j$th random variable. Suppose there are totally $N$ subjects, with $T_i$ observations for the $i$th subject. Write $\mathbb{X}_{i,t} = (\mathbb{X}_{i,t,1}, \ldots, \mathbb{X}_{i,t,d})^\top$, $i=1, \ldots, N, t=1, \ldots, T_i$. We consider the following data structure. \vspace{-0.05in} \begin{enumerate}[({B}1)] \setlength\itemsep{-0.25em} \item Across subjects, the measurements $\mathbb{X}_{1,t}$, $\ldots$, $\mathbb{X}_{N,t}$ are i.i.d. \item Across time points, the random vectors $\mathbb{X}_{i,1}$, $\ldots$, $\mathbb{X}_{i,T_i}$ are stationary. \item For any $i,t$, $\mathbb{X}_{i,t,1}$, $\ldots$, $\mathbb{X}_{i,t,d}$ are DAG-structured. In addition, their joint distribution is the same as that of $X_1,\ldots,X_d$. \end{enumerate} \noindent Assumption (B1) is reasonable, as the subjects are usually independent from each other. In this article, we do not study the scenario where the data come from the same families or clusters. Assumption (B2) about the stationarity is common in numerous applications such as brain connectivity analysis \citep{Bullmore2009, Kang2016, QiuHan2016, WangKang2016}. Assumption (B3) brings the data into the DAG framework that we study. Our objective is then to test the hypotheses in \eqref{eqn:hypothesis}, through \eqref{eqn:hypothesis2}, given the observational data $\mathbb{X}_{i,t,j}$. \section{Testing procedure} \label{sec:test} In this section, we develop an inferential procedure for \eqref{eqn:hypothesis} through \eqref{eqn:hypothesis2}. We first present the main ideas and the complete procedure of our test. We then detail the major steps. Given that our test is implemented based on \textbf{S}tructural learning, s\textbf{U}pervised learning, and \textbf{G}enerative \textbf{A}dve\textbf{R}sarial networks, we call our testing method \textbf{sugar}. \subsection{The main algorithm} Our main idea is to construct a series of measures $\{I(j,k|\mathcal{M};h_b) : b=1,\ldots,B\}$, for a large number of functions $h_1, \ldots,$ $h_B$, then take the maximum of some standardized version of $I(j,k|\mathcal{M};h_b)$. Toward that goal, we need to estimate three key quantities. \vspace{-0.05in} \begin{enumerate}[(a)] \setlength\itemsep{-0.25em} \item The set of indices $\mathcal{M}$ that satisfy the conditions of Proposition \ref{prop1}; \item The conditional mean function ${\mathbb{E}} \left( X_j|X_{\mathcal{M}-\{k\}} \right)$; \item The functional that maps each $h_b$ into ${\mathbb{E}} \left\{ h_b\left(X_k, X_{\mathcal{M}-\{k\}}\right) | X_{\mathcal{M}-\{k\}} \right\}$. \end{enumerate} Correspondingly, our testing procedure involves three key steps. First, to estimate (a), we apply a structural learning algorithm to learn the underlying DAG $\mathcal{G}$ corresponding to $X$. The input of this step is the observed data $\{\mathbb{X}_{i,t,j} : i=1, \ldots, N, t=1, \ldots, T_i, j=1, \ldots, d\}$, and the output is the estimated DAG, denoted by $\widehat{\mathcal{G}}$. Furthermore, let $\widehat{\hbox{AC}}_j$ and $\widehat{\hbox{PA}}_j$ denote the corresponding estimated set of ancestors and parents of $X_j$, respectively. Then we set $\widehat{\mathcal{M}} = \widehat{\hbox{AC}}_j$. To capture potential sparsity and nonlinear associations in $\mathcal{G}$, we employ a recent DAG estimation method by \cite{zheng2020learning}. Other methods, e.g., \cite{zhu2020causal}, can be used as well. We remark that we only require ${\mathbb{P}}(\hbox{PA}_j \subseteq \widehat{\hbox{AC}}_j \subseteq \hbox{DS}_j^c -\{j\})\to 1$. We show in Section \ref{sec:thmcsl} that this requirement is satisfied when using the method of \cite{zheng2020learning}. Meanwhile, this is much weaker than requiring the selection consistency, i.e., ${\mathbb{P}}(\hbox{PA}_j= \widehat{\hbox{PA}}_j)\to 1$. See Section \ref{sec:CSL} for details. Second, to estimate (b), we employ a supervised learning algorithm, as this step is essentially a regression problem. The input includes $X_{\widehat{\mathcal{M}}-\{k\}}$ that serves as the ``predictors", and $X_j$ that serves as the ``response", and the output is the estimated mean $\widehat{{\mathbb{E}}} \left( X_j|X_{\widehat{\mathcal{M}}-\{k\}} \right)$. Numerous choices are available, ranging from boosting or random forests to neural networks methods. In our implementation, we employ a multilayer perceptron learner, which has been shown to have a good capacity of estimating the conditional mean function that is complex and involves high-dimensional covariates. The resulting estimator also has the desired consistency guarantees \citep{schmidt2017nonparametric,farrell2018deep}. See Section \ref{sec:SL} for details. Third, to compute (c), we propose to use generative adversarial networks \citep[GANs]{goodfellow2014generative} to approximate the conditional distribution of $X_k$ given $X_{\widehat{\mathcal{M}}-\{k\}}$. GANs provide a powerful method for generative modeling of high-dimensional datasets. They have been successfully applied in numerous applications ranging from image processing and computer vision, to modelling sequential data such as natural language, music, speech, and to medical fields such as DNA design and drug discovery; see e.g., \cite{gui2020review} for reviews of the related applications. Specifically, we learn a generator $\mathbb{G}(\cdot,\cdot)$ that takes $\mathbb{X}_{i,t,\widehat{\mathcal{M}}-\{k\}}$ and a set of multivariate Gaussian noise vectors as the input, and the output are a set of pseudo samples $\widetilde{\mathbb{X}}_{i,t,k}^{(m)}$, $m = 1, \ldots, M$, where $M$ is the total number of pseudo samples. The generator $\mathbb{G}(\cdot,\cdot)$ is trained such that the divergence between the conditional distribution of $\mathbb{X}_{i,t,k} | \mathbb{X}_{i,t,\widehat{\mathcal{M}}-\{k\}}$ and that of $\widetilde{\mathbb{X}}_{i,t,k}^{(m)} | \mathbb{X}_{i,t,\widehat{\mathcal{M}}-\{k\}}$ is minimized. Given the generated pseudo samples, we then proceed to estimate the conditional mean function ${\mathbb{E}} \big\{ h_b\big(X_k, X_{\widehat{\mathcal{M}}-\{k\}}\big) |$ $X_{\widehat{\mathcal{M}}-\{k\}} \big\}$, and construct the corresponding test statistic. In addition to GANs, other deep generative learning approaches such as variational autoencoders \citep{kingma2013auto} are equally applicable here. We also remark that, an alternative approach for this step is to separately apply a supervised learning algorithm $B$ times to estimate ${\mathbb{E}} \big\{h_b\big( X_k,X_{\widehat{\mathcal{M}}-\{k\}} \big) | X_{\widehat{\mathcal{M}}-\{k\}} \big\}$, for $b=1,\ldots,B$. However, when $B$ is large, and in our implementation, $B = 2000$, this approach is computationally very expensive. Besides, in our asymptotic analysis, $B$ is to diverge to infinity with the sample size to guarantee the power property of the test. Therefore, we choose the generative learning approach for this step. See Section \ref{sec:gans} for details. In addition to these three components, we also propose to couple the test with a data-splitting and cross-fitting strategy. This is to ensure a valid type-I error control for the test under minimal conditions for the above three learners. The same strategy has been commonly used in statistical testing; see, e.g., \citet{romano2019}. Specifically, at the beginning of our testing procedure, we randomly split all the subjects $\{1,\ldots,N\}$ into two equal halves $\mathcal{I}_1 \cup \mathcal{I}_2$, where $\mathcal{I}_{s}$ denotes the set of indices of the subsamples, $s=1,2$. We then compute the three learners in (a) to (c) using each half of the data $\{ \mathbb{X}_{i,t} : i\in \mathcal{I}_{s}, t=1, \ldots, T_i \}$ separately. Based on these learners, we next use cross-fitting to estimate $\{I(j,k|\mathcal{M};h_b) : b=1,\ldots,B\}$, and their associated standard deviations. We construct our test statistic as the largest standardized version of $I(j,k|\mathcal{M};h_b)$ in the absolute value. This allows us to construct two Wald-type test statistics, one for each half of the data. Finally, we derive the $p$-values based on Gaussian approximation, and reject the null hypothesis when either one of the $p$-value is smaller than $\alpha/2$. By Bonferroni's inequality, this yields a valid $\alpha$-level test. See Section \ref{sec:pvalue} for details. A summary of the proposed testing procedure is given in Algorithm \ref{alg:full}. \begin{algorithm}[t!] \caption{Testing procedure for a given edge $(j,k)$.} \label{alg:full} \begin{algorithmic} \item[]\normalsize \begin{enumerate}[Step 1.] \setlength\itemsep{-0.25em} \item Randomly split the data into two equal halves, $\{\mathbb{X}_{i,t,k}\}_{i \in \mathcal{I}_{s}, t=1, \ldots, T_i}$, $s=1,2$. \item For each half of the data, $s=1,2$, \vspace{-0.1in} \begin{enumerate}[({2}a)] \item Apply the structural learning method \eqref{eqn:DAG} to estimate the DAG $\mathcal{G}$. Denote the estimated graph by $\widehat{\mathcal{G}}^{(s)}$, and the estimated set of ancestors of $j$ by $\widehat{\hbox{AC}}^{(s)}_j$. Set $\widehat{\mathcal{M}}_{j,k}^{(s)} = \widehat{\hbox{AC}}^{(s)}_j-\{k\}$. \item If $k\notin \widehat{\hbox{AC}}^{(s)}_j$, return the $p$-value, $p^{(s)}(j,k)=1$. \end{enumerate} \item For $s=1,2$, apply the supervised learning method \eqref{eqn:SL} to estimate the conditional mean ${\mathbb{E}} \big( X_j | X_{\widehat{\mathcal{M}}^{(s)}_{j,k}} \big)$, with $\big\{ \mathbb{X}_{i,t,\widehat{\mathcal{M}}_{j,k}^{(s)}} \big\}_{i\in \mathcal{I}_{s}, t=1, \ldots, T_i}$ as the ``predictors", and $\{\mathbb{X}_{i,t,j}\}_{i\in \mathcal{I}_{s},t=1, \ldots, T_i}$ as the ``response". Denote the estimated function by $\widehat{g}_{j,k}^{(s)}(x) = \widehat{{\mathbb{E}}} \big( X_j|X_{\widehat{\mathcal{M}}_{j,k}^{(s)}}=x \big)$. \item For $s=1,2$, apply the GANs method to learn a generator $\mathbb{G}^{(s)}$ to approximate the conditional distribution of $\mathbb{X}_{i,t,k}$ given $\mathbb{X}_{i,t,\widehat{\mathcal{M}}_{j,k}^{(s)}}$. It takes $\mathbb{X}_{i,t,\widehat{\mathcal{M}}_{j,k}^{(s)}}$ and a multivariate Gaussian vector as the input, and returns the pseudo samples $\big\{ \widetilde{\mathbb{X}}_{i,t,k}^{(m)} \big\}_{m=1}^{M}$ as the output. \item Construct the test statistic: \vspace{-0.15in} \begin{enumerate}[({5}a)] \item Randomly generate $B$ functions $\big\{ h_b^{(s)} \big\}_{b=1}^B$ from the bounded function class $\mathbb{H}^{(s)}$ in \eqref{eqn:funclass}. \item For each $(s,b)$, construct two standardized measures, $\widehat{T}_{b,\textrm{CF}}^{(s)}$ and $\widehat{T}_{b,\textrm{NCF}}^{(s)}$, with and without cross-fitting, using \eqref{eqn:measure}. \item Select the index, $\widehat{b}^{(s)}=\argmax_{b\in \{1,\ldots,B\}} \big| \widehat{T}_{b,\textrm{NCF}}^{(s)} \big|$, based on the measure without cross-fitting. \item Set the test statistic as $\widehat{T}_{\widehat{b}^{(s)},\textrm{CF}}^{(s)}$, based on the measure with cross-fitting. \end{enumerate} \item Return the $p$-value: \vspace{-0.1in} \begin{enumerate}[({6}a)] \item Compute the $p$-value, $p^{(s)}(j,k)=2{\mathbb{P}} \big\{ Z_0 \ge \big| \widehat{T}_{\widehat{b}^{(s)},\textrm{CF}}^{(s)} \big| \big\}$, for each half of the data, $s = 1, 2$, where $Z_0$ is standard normal. \item Return $p(j,k)=2\min\left\{ p^{(1)}(j,k),p^{(2)}(j,k) \right\}$. \end{enumerate} \end{enumerate} \end{algorithmic} \end{algorithm} \subsection{DAG structural learning} \label{sec:CSL} The first key component of our testing procedure is to estimate the DAG $\mathcal{G}$ associated with $X = (X_1, \ldots, X_d)^\top$, so that we can construct $\mathcal{M}$ for the subsequent test. In our implementation, we employ the neural structural learning method of \cite{zheng2020learning}. Meanwhile, there are other methods available that allow complex nonlinear relationships \citep[e.g.,][]{yu2019dag}. Consider a multilayer perceptron (MLP) with $L$ hidden layers and an activation function $\sigma$: \begin{align} \label{eqn:MLP} \begin{split} \textrm{MLP}\left( u; A^{(1)}, b^{(1)}, \ldots, A^{(L)}, b^{(L)} \right) = \; A^{(L)} \sigma\left\{ \ldots A^{(2)} \sigma\left( A^{(1)} \mu + b^{(1)} \right) \ldots + b^{(L-1)} \right\} + b^{(L)}, \end{split} \end{align} where $u \in \mathbb{R}^{m_0}$ is the input signal of the MLP, $A^{(s)} \in \mathbb{R}^{m_{\ell} \times m_{\ell-1}}, b^{(s)} \in \mathbb{R}^{m_{\ell}}$ are the parameters that produce the linear transformation of the $(\ell-1)$th layer, and the output is a scalar with $m_L=1$. The dimension $m_{\ell}$ denotes the number of nodes at layer $\ell$, $\ell = 0, \ldots, L$. See Figure \ref{fig1}(b) for a graphic illustration of an MLP. We employ MLP to approximate the functions $f_j$ in our DAG model \eqref{eqn:model}. Specifically, let $\theta_j = \big\{ A_j^{(1)}, b^{(1)} \big\}$ collect all the parameters for the $j$th MLP that approximates $f_j$, $j=1, \ldots, d$. For each half of the data, $s = 1, 2$, we estimate the DAG via the following optimization, \begin{eqnarray*} \min_{\theta} \sum_{i\in \mathcal{I}_{s}} \sum_{t,j} \left\{ \mathbb{X}_{i,t,j}-\textrm{MLP}(\mathbb{X}_{i,t};\theta_j) \right\}^2, \,\,\textrm{ subject to } \,\, \mathcal{G}(\theta)\in \textrm{DAGs}, \end{eqnarray*} where $\mathcal{G}(\theta)$ denotes the graph induced by $\theta$. This optimization problem is challenging to solve, however, due to the fact that the search space scales super-exponentially with the dimension $d$. To resolve this issue, \cite{zheng2020learning} proposed a novel characterization of the acyclic constraint, and showed that the DAG constraint can be represented by trace$[\exp\{ W(\theta) \circ W(\theta) \}]=d$, where $\circ$ denotes the Hadamard product, $\exp(W)$ is the matrix exponential of $W$, trace$(W)$ is the trace of $W$, and $W(\theta)$ is a $d\times d$ matrix whose $(k,j)$th entry equals the Euclidean norm of the $k$th column of $A_j^{(1)}$. Based on this characterization, the optimization problem becomes, \begin{align}\label{eqn:DAG} \begin{split} \min_{\theta} \sum_{j=1}^{d} \left[\sum_{i\in \mathcal{I}_{s}} \sum_{t=1}^{T_i} \left\{ \mathbb{X}_{i,t,j}-\textrm{MLP}(\mathbb{X}_{i,t};\theta_j)\right\}^2+\lambda n_s\big\| A_j^{(1)} \big\|_{1,1}\right], \\ \textrm{subject to}\,\,\,\,\textrm{trace}[\exp\{ W(\theta) \circ W(\theta) \}]=d, \end{split} \end{align} where $n_s=\sum_{i\in \mathcal{I}_s} T_i$ is the number of observations in $\mathcal{I}_s$, $\big\| A_j^{(1)} \big\|_{1,1}$ is the sum of all elements in $A_j^{(1)}$ in absolute values, and $\lambda>0$ is a sparsity tuning parameter. Note that the sparsity penalization is placed only on $A_j^{(1)}$, since this is the only layer that determines the sparsity of the input variables $X_1, \ldots, X_d$. The optimization problem in \eqref{eqn:DAG} can be efficiently solved using the augmented Lagrangian method \citep{zheng2020learning}. Denote the estimated graph by $\widehat{\mathcal{G}}^{(s)}$, and the estimated set of ancestors of $j$ by $\widehat{\hbox{AC}}^{(s)}_j$. If $k \notin \widehat{\textrm{AC}}_j^{(s)}$, then it follows from $\textrm{PA}_j\subseteq \widehat{\textrm{AC}}_j^{(s)}$ that $k\notin \hbox{PA}_j$. Consequently, $X_k$ is not to directly influence $X_j$, and thus we simply set the corresponding $p$-value $p^{(s)}(j,k)=1$. Our subsequent inference procedure is to focus on the case where $k \in \widehat{\textrm{AC}}_j^{(s)}$, and we set $\widehat{\mathcal{M}}_{j,k}^{(s)} = \widehat{\hbox{AC}}^{(s)}_j-\{k\}$. We also remark that, the subsequent inference built on $\widehat{\mathcal{G}}^{(s)}$ does not require $\widehat{\mathcal{G}}^{(s)}$ to be consistent to $\mathcal{G}$. Instead, we only require ${\mathbb{P}}(\textrm{PA}_j\subseteq \widehat{\textrm{AC}}_j^{(s)} \subseteq \hbox{DS}_j^c -\{j\})\to 1$. \subsection{Supervised learning} \label{sec:SL} The second key component of our testing procedure is to learn a conditional mean function $g_{j,k}^{(s)}(x)={\mathbb{E}} \left( X_j|X_{\mathcal{M}_{j,k}^{(s)}}=x \right)$. This is essentially a regression problem, and there are many methods available. In our implementation, we use the MLP again, by seeking \begin{eqnarray}\label{eqn:SL} \min_{\theta_j} \sum_{i\in \mathcal{I}_{s}} \sum_{t=1}^{T_i} \left\{ \mathbb{X}_{i,t,j}-\textrm{MLP}\left( \mathbb{X}_{i,t,\widehat{\mathcal{M}}_{j,k}^{(s)}};\theta_j \right) \right\}^2, \end{eqnarray} where the learner MLP$(\cdot)$ is as defined in \eqref{eqn:MLP}. The optimization problem in \eqref{eqn:SL} can be solved using a stochastic gradient descent algorithm, or the limited-memory Broyden-Fletcher-Goldfarb-Shanno algorithm \citep{byrd1995limited}. Denote the estimated conditional mean function by $\widehat{g}^{(s)}_{j,k}(x) = \widehat{{\mathbb{E}}} \Big( X_j|X_{\widehat{\mathcal{M}}-\{k\}}$ $= x \Big)$. \subsection{Generative adversarial learning} \label{sec:gans} The third key component of our testing procedure is to use GANs to produce a generator $\mathbb{G}^{(s)}(\cdot, \cdot)$, such that the divergence between the conditional distribution of $\mathbb{X}_{i,t,k}$ given $\mathbb{X}_{i,t,\widehat{\mathcal{M}}_{j,k}^{(s)}}$ and that of $\widetilde{\mathbb{X}}_{i,t,k}^{(m)}$ given $\mathbb{X}_{i,t,\widehat{\mathcal{M}}_{j,k}^{(s)}}$ is minimized. To that end, we adopt the proposal of \cite{genevay2017learning} to learn the generator. Specifically, let $\mu_{j,k}$ and $\nu_{j,k}$ denote the joint distribution of $\left( \mathbb{X}_{i,t,k},\mathbb{X}_{i,t,\widehat{\mathcal{M}}_{j,k}^{(s)}} \right)$ and $\left( \widetilde{\mathbb{X}}_{i,t,k}^{(m)},\mathbb{X}_{i,t,\widehat{\mathcal{M}}_{j,k}^{(s)}} \right)$, respectively. We estimate $\mathbb{G}^{(s)}$ by optimizing \begin{eqnarray}\label{eqn:GAN} \min_{\mathbb{G}} \max_c \widetilde{\mathcal{D}}_{c,\rho}(\mu_{j,k}, \nu_{j,k}). \end{eqnarray} Here $\widetilde{\mathcal{D}}_{c,\rho}$ is the Sinkhorn loss function between two probability measures $\mu, \nu$, with respect to a cost function $c$ and a regularization parameter $\rho>0$, \begin{eqnarray*} \mathcal{\widetilde{D}}_{c, \rho}(\mu, \nu) & = & 2\mathcal{D}_{c, \rho}(\mu, \nu) - \mathcal{D}_{c, \rho}(\mu, \mu) - \mathcal{D}_{c, \rho}(\nu, \nu), \\ \mathcal{D}_{c, \rho}(\mu, \nu) & = & \inf_{\pi \in \Pi(\mu, \nu)} \int_{x,y} \big\{ c(x, y)-\rho H(\pi|\mu \otimes \nu) \big\} \pi(dx,dy), \end{eqnarray*} where $\Pi(\mu, \nu)$ is a set containing all probability measures $\pi$ whose marginal distributions correspond to $\mu$ and $\nu$, $H$ is the Kullback-Leibler divergence, and $\mu \otimes \nu$ is the product measure of $\mu$ and $\nu$. When $\rho = 0$, $\mathcal{D}_{c, 0}(\mu, \nu)$ measures the optimal transport of $\mu$ into $\nu$ with respect to the cost function $c(\cdot, \cdot)$ \citep{cuturi2013sinkhorn, genevay2016stochastic}. When $\rho \neq 0$, an entropic regularization is added to this optimal transport. As such, the objective function $\mathcal{\widetilde{D}}_{c, \rho}$ in \eqref{eqn:GAN} is a regularized optimal transport metric, and the regularization is to facilitate the computation, so that $\mathcal{\widetilde{D}}_{c, \rho}$ can be efficiently evaluated. Intuitively, the closer the two conditional distributions, the smaller the Sinkhorn loss. Therefore, maximizing $\mathcal{\widetilde{D}}_{c, \rho}$ with respect to the cost function $c$ learns a discriminator that can better discriminate $\mu_{j,k}$ and $\nu_{j,k}$. On the other hand, minimizing the maximum cost with respect to the generator $\mathbb{G}$ makes the conditional distribution of $\widetilde{\mathbb{X}}_{i,t,k}^{(m)}$ given $\mathbb{X}_{i,t,\widehat{\mathcal{M}}_{j,k}^{(s)}}$ closer to that of $\mathbb{X}_{i,t,k}$ given $\mathbb{X}_{i,t,\widehat{\mathcal{M}}_{j,k}^{(s)}}$. This yields the minimax formulation in \eqref{eqn:GAN}. In our implementation, we approximate the cost function $c$ and the generator based on MLP \eqref{eqn:MLP}. The distributions $\mu_{j,k}$ and $\nu_{j,k}$ in \eqref{eqn:GAN} are approximated by the empirical distributions of the data samples. The parameters involved in GANs are updated by the Adam algorithm \citep{Kingma2015}. Denote the learnt generator by $\mathbb{G}^{(s)}$. It takes $\mathbb{X}_{i,t,\widehat{\mathcal{M}}_{j,k}^{(s)}}$ and a set of multivariate Gaussian noise vectors $\{Z_{j,k}^{(m)}\}_{m=1}^M$ as the input, and returns the pseudo samples $\widetilde{\mathbb{X}}_{i,t,k}^{(m)}=\mathbb{G}^{(s)}(\mathbb{X}_{i,t,\widehat{\mathcal{M}}_{j,k}^{(s)}},Z_{j,k}^{(m)})$, $m=1,\cdots,M$, as the output. \subsection{Test statistic and $p$-value} \label{sec:pvalue} We next derive the test statistic and the corresponding $p$-value. First, for each half of the data, $s=1,2$, we begin with a bounded function class $\mathbb{H}^{(s)} = \left\{ h_{\omega}^{(s)} : \omega \in \Omega^{(s)} \right\}$, indexed by some parameter $\omega$. In our implementation, we consider the class of characteristic functions of $X_k$, \vspace{-0.05in} \begin{eqnarray}\label{eqn:funclass} \mathbb{H}^{(1)} = \mathbb{H}^{(2)} = \mathbb{H} = \big\{ \cos(\omega X_k), \; \sin(\omega X_k):\omega\in \mathbb{R} \big\}. \end{eqnarray} Alternatively, one can set $\mathbb{H}^{(s)}$ to the class of characteristic functions of $(X_k,X_{\widehat{\mathcal{M}}_{j,k}^{(s)}})$. By the Fourier Theorem \citep{siebert1986circuits}, such a choice of $\mathbb{H}^{(s)}$ is able to approximate any square integrable function $h$ in Theorem \ref{thm1}. Consequently, the resulting test is consistent against all alternatives. However, in our numerical experiments, we find that setting $\mathbb{H}^{(s)}$ according to \eqref{eqn:funclass} results in a better empirical performance in power. Although the test based on \eqref{eqn:funclass} is not able to detect all alternatives, it is powerful for most practically interesting alternatives. For simplicity, we choose an even number for the total number of transformation functions $B$. We then randomly generate i.i.d.\ standard normal variables $\omega_1,\ldots,\omega_{\frac{B}{2}}$, and set \begin{eqnarray*} h_b^{(s)}\left( X_k,X_{\widehat{\mathcal{M}}_{j,k}^{(s)}} \right) = \begin{cases} \cos(\omega_b X_k), & \textrm{ for } b=1, \ldots, B/2, \\ \sin(\omega_b X_k), & \textrm{ for } b = B/2+1, \ldots, B. \end{cases} \end{eqnarray*} Next, for each pair of $(s,b)$, $b=1, \ldots, B, s = 1, 2$, we compute two estimators $\widehat{I}_{b,\textrm{CF}}^{(s)}$ and $\widehat{I}_{b,\textrm{NCF}}^{(s)}$ for the measure $I\left( j,k|\widehat{\textrm{AC}}_j^{(s)},h_b^{(s)} \right)$, one \emph{with} cross-fitting, and the other \emph{without} cross-fitting. Specifically, we compute \begin{eqnarray*} \widehat{I}_{b,\textrm{CF}}^{(s)} = \left( \sum_{i\in \mathcal{I}_{s}^c} T_i \right)^{-1} \left( \sum_{i\in \mathcal{I}_{s}^c} I_{i,t,b}^{(s)} \right), \quad \widehat{I}_{b,\textrm{NCF}}^{(s)} & = & \left( \sum_{i\in \mathcal{I}_{s}} T_i \right)^{-1} \left( \sum_{i\in \mathcal{I}_{s}} I_{i,t,b}^{(s)} \right), \end{eqnarray*} where \begin{align*} \begin{split} I_{i,t,b}^{(s)} = \left\{ \mathbb{X}_{i,t,j}-\widehat{g}_{j,k}^{(s)}\left( \mathbb{X}_{i,t,\mathcal{M}_{j,k}^{(s)}} \right) \right\} \left\{ h_b^{(s)}\left( \mathbb{X}_{i,t,k},\mathbb{X}_{i,t,\mathcal{M}_{j,k}^{(s)}} \right) - \frac{1}{M}\sum_{m=1}^M h_b^{(s)}\left( \widetilde{\mathbb{X}}_{i,t,k}^{(m)}, \mathbb{X}_{i,t,\mathcal{M}_{j,k}^{(s)}} \right) \right\}, \end{split} \end{align*} and $M$ is the total number of pseduo samples generated by $\mathbb{G}^{(s)}$. We remark that, for $\widehat{I}_{b,\textrm{NCF}}^{(s)}$, we use the same subset of data to learn the graph, the generator, the condition mean function, and to construct $I_{i,t,b}^{(s)}$. By contrast, for $\widehat{I}_{b,\textrm{CF}}^{(s)}$, the data used for the DAG learner, the conditional mean learner and the generator are independent from the data used to construct $I_{i,t,b}^{(s)}$. Next, we compute the corresponding standard errors $\widehat{\sigma}_{b,\textrm{CF}}^{(s)}$ and $\widehat{\sigma}_{b,\textrm{NCF}}^{(s)}$ for $\widehat{I}_{b,\textrm{CF}}^{(s)}$ and $\widehat{I}_{b,\textrm{NCF}}^{(s)}$, respectively. We note that, since our data observations are time-dependent, the usual sample variance would not be a consistent estimator. To address this issue, we employ the batched estimator that is commonly used in time series analysis \citep{Carlstein1986}. That is, we divide the data associated with each subject into non-overlapping batches, with each batch containing at most $K$ observations. For simplicity, suppose $T_i$ is divisible by $K$ for all $i=1, \ldots, N$. We then obtain the following standard error estimators, \vspace{-0.01in} \begin{align*} \begin{split} \widehat{\sigma}_{b,\textrm{CF}}^{(s)} & = \left[\frac{K}{\sum_{i\in \mathcal{I}_{s}^c} T_i} \sum_{i\in \mathcal{I}_{s}^c}\sum_{k=1}^{T_i/K} \left\{ \frac{\sum_{t=(k-1)K+1}^{kK} \left( I_{i,t,b}^{(s)}-\widehat{I}_{b,\textrm{CF}}^{(s)} \right) }{\sqrt{K}} \right\}^2 \right]^{1/2},\\ \widehat{\sigma}_{b,\textrm{NCF}}^{(s)} & = \left[ \frac{K}{\sum_{i\in \mathcal{I}_{s}} T_i} \sum_{i\in \mathcal{I}_{s}}\sum_{k=1}^{T_i/K} \left\{ \frac{\sum_{t=(k-1)K+1}^{kK} \left( I_{i,t,b}^{(s)}-\widehat{I}_{b,\textrm{NCF}}^{(s)} \right) }{\sqrt{K}} \right\}^2 \right]^{1/2}. \end{split} \end{align*} Putting $\widehat{I}_{b,\textrm{CF}}^{(s)}$ and $\widehat{I}_{b,\textrm{NCF}}^{(s)}$ together with their standard error estimators, we obtain two standardized measures, \begin{eqnarray}\label{eqn:measure} \begin{split} \quad\quad\quad \widehat{T}_{b,\textrm{CF}}^{(s)} = \sqrt{\sum_{i\in \mathcal{I}_{s}^c} T_i} \, \frac{\widehat{I}_{b,\textrm{CF}}^{(s)}}{\widehat{\sigma}_{b,\textrm{CF}}^{(s)}}, \quad \textrm{ and } \quad \widehat{T}_{b,\textrm{NCF}}^{(s)} = \sqrt{\sum_{i\in \mathcal{I}_{s}} T_i} \, \frac{\widehat{I}_{b,\textrm{NCF}}^{(s)}}{\widehat{\sigma}_{b,\textrm{NCF}}^{(s)}}. \end{split} \end{eqnarray} Finally, we select the index $\widehat{b}^{(s)}$ that maximizes the standardized measure without cross-fitting, $\widehat{T}_{b,\textrm{NCF}}^{(s)}$, in absolute value. That is, \begin{align*} \widehat{b}^{(s)} = \argmax_{b\in \{1,\ldots,B\}} \left| \widehat{T}_{b,\textrm{NCF}}^{(s)} \right|. \end{align*} We take the measure with cross-fitting, $\widehat{T}_{\widehat{b}^{(s)},\textrm{CF}}^{(s)}$, under the selected $\widehat{b}^{(s)}$, as our final test statistic. Note that, $\widehat{b}^{(s)}$ is selected so that the test based on $\widehat{T}_{\widehat{b}^{(s)},\textrm{CF}}^{(s)}$ achieves the largest power asymptotically. Meanwhile, since $\widehat{b}^{(s)}$ is determined by $\widehat{T}_{b,\textrm{NCF}}^{(s)}$, it depends solely on the data in $\mathcal{I}_s$, and is independent of the data in $\mathcal{I}_s^c$. This allows us to derive the limiting distribution of $\widehat{T}_{\widehat{b}^{(s)},\textrm{CF}}^{(s)}$ and compute the corresponding $p$-value easily. Specifically, for each $b = 1, \ldots, B$, $\widehat{T}_{b,\textrm{CF}}^{(s)}$ converges in distribution to standard normal under the null hypothesis $\mathcal{H}_0(j,k)$; see Theorem \ref{thm2}. Since $\widehat{b}^{(s)}$ is independent of the data in $\mathcal{I}_{s}^c$, $\widehat{T}_{\widehat{b}^{(s)},\textrm{CF}}^{(s)}$ converges in distribution to standard normal under $\mathcal{H}_0(j,k)$ as well. We thus compute the $p$-value for each half of the data as $p^{(s)}(j,k)=2\Phi\left\{ Z_0 > \left| \widehat{T}_{\widehat{b}^{(s)},\textrm{CF}}^{(s)} \right| \right\}$, $s=1,2$, where $Z_0$ denotes a standard normal random variable. The final $p$-value of the test is then $p(j,k)=2\min\left\{ p^{(1)}(j,k),p^{(2)}(j,k) \right\}$. \section{Bidirectional theories} \label{sec:theory} In this section, we first establish the asymptotic size and power of the proposed test. We then derive the oracle property of the DAG estimator produced by \eqref{eqn:DAG}, which is needed to guarantee the validity of the test. To simplify the theoretical analysis, we assume $T_1=\ldots=T_n=T$. All the asymptotic results are derived when either the number of subjects $N$, or the number of time points $T$, diverges to infinity. The results of this type provide useful theoretical guarantees for different types of applications, and are referred as bidirectional theories. \subsection{Asymptotic size and power} We begin with a set of regularity conditions needed for the asymptotic consistency of the test. \vspace{-0.05in} \begin{enumerate}[({C}1)] \setlength\itemsep{-0.25em} \item With probability approaching one, $\textrm{PA}_j\subseteq \widehat{\textrm{AC}}^{(s)}_j\subseteq \hbox{DS}_j^c-\{j\}$. \item Suppose ${\mathbb{E}} \Big | g_{j,k}^{(s)} \Big( X_{\mathcal{M}_{j,k}^{(s)}} \Big) - \widehat{g}_{j,k}^{(s)} \Big( X_{\mathcal{M}_{j,k}^{(s)}} \Big) \Big |^2 = O\left\{ (NT)^{-2\kappa_1} \right\}$ for some constant $\kappa_1>0$. In addition, $\widehat{g}_{j,k}^{(s)}$ is uniformly bounded almost surely. \item Suppose ${\mathbb{E}} \sup_{\widetilde{B} \in \mathcal{B}} \Big| {\mathbb{P}}\Big\{ X_k \in \widetilde{B} | X_{\mathcal{M}_{j,k}^{(s)}} \Big\} - {\mathbb{P}}\Big\{ \mathbb{G}^{(s)}\Big( X_{\mathcal{M}_{j,k}^{(s)}},Z_{j,k}^{(m)} \Big) \in \widetilde{B} |$ $X_{\mathcal{M}_{j,k}^{(s)}} \Big\} \Big|^2 = O\left\{ (NT)^{-2\kappa_2} \right\}$ for some constant $\kappa_2>0$, where $\mathcal{B}$ denotes the Borel algebra on $\mathbb{R}$. \item The random process $\{\mathbb{X}_{i,t}\}_{t\ge 0}$ is $\beta$-mixing if $T$ diverges to infinity. The $\beta$-mixing coefficients $\{\beta(q)\}_{q}$ satisfy that $\sum_q q^{\kappa_3} \beta(q)<+\infty$ for some constant $\kappa_3>0$. Here, $\beta(q)$ denotes the $\beta$-mixing coefficient at lag $q$, which measures the time dependence between the set of variables $\{\mathbb{X}_{i,j}\}_{j\le t}$ and $\{\mathbb{X}_{i,j}\}_{j\ge t+q}$. \item Suppose the number of observations $K$ in the batched standard error estimators $\widehat{\sigma}_{b,\textrm{CF}}^{(s)}$ and $\widehat{\sigma}_{b,\textrm{NCF}}^{(s)}$ satisfies that, $K=T$ if $T$ is bounded, and $T^{(1+\kappa_3)^{-1}} \ll K\ll NT$ otherwise. \end{enumerate} \noindent Assumptions (C1)-(C3) characterize the theoretical requirements on the three learners, respectively. In particular, Assumption (C1) concerns about the structural learner of DAG, and we show in Section \ref{sec:thmcsl} that (C1) holds when \eqref{eqn:DAG} is employed to estimate DAG. Assumption (C2) requires the squared prediction loss of the supervised learner of the conditional mean function to satisfy a certain convergence rate, whereas Assumption (C3) requires the squared total variation norm between the conditional distributions of the observed samples and the pseudo samples to satisfy a certain convergence rate. If some parametric models are imposed to learn the conditional mean function $g_{j,k}^{(s)}$ and the generator $\mathbb{G}^{(s)}$, we have $\kappa_1=\kappa_2=1/2$ in general. In our setup, we do \emph{not} impose any parametric models, and only require $\kappa_1+\kappa_2>1/2$. When using the multilayer perceptron models and GANs for function approximation, the corresponding convergence rates have been established \citep[see e.g.,][]{schmidt2017nonparametric, farrell2018deep, liang2018well, Bauer2019, chen2020statistical}. Consequently, both (C2) and (C3) are satisfied under some mild conditions. Assumption (C4) characterizes the dependence of the data observations over time, and is commonly imposed in the time series literature \citep{Bradley2005}. We also note that, (C4) is \emph{not} needed when $T$ is bounded but $N$ diverges to infinity. Assumption (C5) guarantees the consistency of the batched standard error estimators $\widehat{\sigma}_{b,\textrm{CF}}^{(s)}$ and $\widehat{\sigma}_{b,\textrm{NCF}}^{(s)}$, and is easily satisfied, since $K$ is a parameter that we specify. When $T$ is bounded and is relatively small compared to a large sample size $N$, we can simply set $K=T$, i.e., treating the entire time series as one batch. We next establish the asymptotic size of the propose testing procedure. \begin{theorem}[Size]\label{thm2} Suppose \eqref{eqn:model}, (C1)-(C5) hold. Suppose $\min_b NT{\mbox{Var}}\Big( \widehat{I}^{(s)}_{b,\textrm{CF}} |$ $\{\mathbb{X}_{i,t}\}_{i\in \mathcal{I}_s,1\le t\le T} \Big)$ $\ge \kappa_4$ for some constant $\kappa_4>0$. If the constants $\kappa_1$, $\kappa_2$, $\kappa_3$ satisfy that $\kappa_1+\kappa_2>1/2$, $\kappa_3>\max[\{2\min(\kappa_1,\kappa_2)\}^{-1}-1,2]$, then, as either $N$ or $T\to \infty$, \begin{enumerate}[(a)] \item The test statistic $\widehat{T}^{(s)}_{\widehat{b}^{(s)},\tsb{\rm{CF}}}\stackrel{d}{\to} \textrm{Normal}(0,1)$ under $\mathcal{H}_0(j,k)$. \item The $p$-value satisfies that ${\mathbb{P}}\{p(j,k)\le \alpha\}\le \alpha+o(1)$, for any nominal level $0<\alpha<1$. \end{enumerate} \end{theorem} \noindent To establish the asymptotic size of the test, we require the convergence rates of the supervised learner and the generator satisfy $\kappa_1+\kappa_2>1/2$, which is slower than the usual parametric rate. We also require $\beta(q)$ to decay at a polynomial rate with respect to $q$. Such a condition holds for many common time series models \citep[see, e.g.,][]{McDonald2015est}. We also require a minimum variance condition, which automatically holds when the conditional variance of $h_b^{(s)}\big( X_k, X_{\widehat{\mathcal{M}}_{j,k}^{(s)}} \big) - {\mathbb{E}} \big\{h_b^{(s)}\big( X_k, X_{\widehat{\mathcal{M}}_{j,k}^{(s)}} \big) | X_{\widehat{\mathcal{M}}_{j,k}^{(s)}} \big\}$ given $X_{\widehat{\mathcal{M}}_{j,k}^{(s)}}$ is bounded away from zero. Under these conditions, we establish the asymptotic normality of the test statistic $\widehat{T}^{(s)}_{\widehat{b}^{(s)},\tsb{\rm{CF}}}$, which further implies that the $p$-value $p^{(s)}(j,k)$ converges to a uniform distribution on $[0,1]$. By Bonferroni's inequality, $p(j,k)$ is a valid $p$-value, and consequently, the proposed test achieves a valid control of type-I error. Next, we study the asymptotic power of the test. We introduce a quantity to characterize the degree to which the alternative hypothesis deviates from the null for a given function class $\mathbb{H}$: $\Delta(\mathbb{H}) = \min_{\mathcal{M}}\sup_{h\in \mathbb{H}} |I(j,k|\mathcal{M};h)|$, where the minimum is taken over all subsets $\mathcal{M}$ that satisfy the conditions in Proposition \ref{prop1}. When $\mathbb{H}$ is taken over the class of characteristic functions of $(X_k,X_{\mathcal{M}})$, we have $\Delta(\mathbb{H})>0$. In addition, we introduce the notion of the VC type class \citep[][Definition 2.1]{Cherno2014}. Specifically, let $\mathcal{F}$ denote a class of measurable functions, with a measurable envelope function $F$ such that $\sup_{f\in \mathcal{F}}|f| \le F$. For any probability measure $Q$, let $e_Q$ denote a semi-metric on $\mathcal{F}$ such that $e_Q(f_1,f_2)=\|f_1-f_2\|_{Q,2} = \sqrt{\int |f_1-f_2|^2 dQ}$. An $\epsilon$-net of the space $(\mathcal{F}, e_Q)$ is a subset $\mathcal{F}_{\epsilon}$ of $\mathcal{F}$, such that for every $f\in \mathcal{F}$, there exists some $f_{\epsilon}\in \mathcal{F}_{\epsilon}$ satisfying $e_Q(f,f_{\epsilon}) < \epsilon$. We say that $\mathcal{F}$ is a VC type class with envelope $F$, if there exist constants $c_0 > 0, c_1 \ge 1$, such that $\sup_Q \mathbb{N}\left( \mathcal{F},e_Q, \epsilon\|F\|_{Q,2} \right) \le (c_0 / \epsilon)^{c_1}$, for all $0 < \epsilon \le 1$, where the supremum is taken over all finitely discrete probability measures on the support of $\mathcal{F}$, and $\mathbb{N}\left( \mathcal{F},e_Q, \epsilon\|F\|_{Q,2} \right)$ is the infimum of the cardinality of $\epsilon\|F\|_{Q,2}$-nets of $\mathcal{F}$. We refer to $c_1$ as the VC index of $\mathcal{F}$. To simplify the analysis, we also suppose $X_j$ is bounded, and without loss of generality, its support is $[0,1]$. \begin{theorem}[Power]\label{thm3} Suppose the conditions in Theorem \ref{thm2} hold, and the $\beta$-mixing coefficient $\beta(q)$ in (C4) satisfies that $\beta(q)=O(\kappa_5^q)$ for some constant $0<\kappa_5<1$ when $T$ diverges. Suppose $\Delta(\mathbb{H})\gg (NT)^{-1/2}\log (NT)$ under $\mathcal{H}_1(j,k)$. Suppose, with probability tending to one, $\widehat{g}_{j,k}^{(s)}$ and $\mathbb{G}^{(s)}$ belong to the class of VC type functions with bounded envelope functions and the bounded VC indices no greater than $O\{(NT)^{\min(2\kappa_1,2\kappa_2,1/2)}\}$, $s=1,2$. If the number of transformation functions $B=\kappa_6 (NT)^{\kappa_7}$ for some constants $\kappa_6 > 0, \kappa_7 \ge 1/2$, then, as either $N$ or $T\to \infty$, $p(j,k)\stackrel{p}{\to} 0$ under $\mathcal{H}_1(j,k)$. \end{theorem} \noindent To establish the asymptotic power of the test, we require the function $\widehat{g}_{j,k}^{(s)}$ and the generator $\mathbb{G}^{(s)}$ to both belong to the VC type class. This is to help establish the concentration inequalities for the measure $\widehat{I}^{(s)}_{b,\textrm{NCF}}$ without cross-fitting. This assumption automatically holds in our implementation where the MLP is used to model both \citep{farrell2018deep}. We have also strengthened the requirement on $\beta(q)$, so that it decays exponentially with respect to $q$. This is to ensure the $\sqrt{NT}$-consistency of the proposed test when $T\to \infty$. This condition holds when the process $\{\mathbb{X}_{i,t}\}_{t\ge 0}$ forms a recurrent Markov chain with a finite state space. It also holds for more general state space Markov chains \citep[see, e.g.,][Section 3]{Bradley2005}. Under these conditions, this theorem shows that our proposed test is consistent against some local alternatives that are $\sqrt{NT}$-consistent to the null up to some logarithmic term. \subsection{Oracle property of the DAG learner} \label{sec:thmcsl} As a by-product of theoretical analysis, we derive the oracle property of the DAG estimator produced by \eqref{eqn:DAG}. This result is to guarantee ${\mathbb{P}}\left( \cap_{j\in \{1,\cdots,d\}}\{\textrm{PA}_j\subseteq \widehat{\textrm{AC}}^{(s)}_j\} \right) \to 1$, which was not available in \cite{zheng2020learning}. It implies that the ordering of the true DAG can be consistently estimated, which in turn ensures the validity of (C1). See Theorem \ref{thm4} for details. We first define the oracle estimator. For an ordering $\pi=(\pi_1,\ldots,\pi_d)$ for a given DAG, consider the estimator $\widetilde{\theta}^{(s)}(\pi) = \big\{ \widetilde{\theta}^{(s)}_1(\pi), \ldots,$ $\widetilde{\theta}^{(s)}_d(\pi) \big\}$, where each $\widetilde{\theta}^{(s)}_j(\pi)$ is obtained by \begin{eqnarray*} \argmin_{\substack{\theta_j = \left\{ A_j^{(1)}, b^{(1)}, \ldots, A_j^{(L)}, b^{(L)} \right\} \scriptsize{\textrm{supp}}\left( A_j^{(1)} \right) \in \{\pi_1,\ldots,\pi_{j-1}\} } } \sum_{i \in \mathcal{I}_{s}} \sum_{t=1}^{T} \left\{ \mathbb{X}_{i,t,j}-\textrm{MLP}(\mathbb{X}_{i,t};\theta_j) \right\}^2 + \frac{\lambda NT}{2} \big\|A_j^{(1)} \big\|_{1,1}, \end{eqnarray*} where $\textrm{supp}\left( A_j^{(1)} \right) \in \{\pi_1,\ldots,\pi_{j-1}\}$ means that, for any $l$ that does not belong to this set, the $l$th column of $A_j^{(1)}$ equals zero. In other words, the estimator $\widetilde{\theta}^{(s)}_j(\pi)$ is computed as if the order $\pi$ were known in advance. Next, let $\Pi^*$ denote the set of all true orderings. This means, for any true ordering $\pi^*\in \Pi^*$, $\textrm{PA}_j\subseteq \{\pi_1^*,\ldots,\pi_{j-1}^*\}$, for any $j=1, \ldots, d$. In other words, the parents of each node should appear before the occurrence of this node under $\pi^*$. It is also worth mentioning that, the true ordering is \emph{not} necessarily unique, even though the underlying DAG is unique. For instance, consider Example 1 with a v-structure as shown in Figure \ref{fig1}(a). In this example, both $(1,2,3)$ and $(1,3,2)$ are the true orderings, as there are no directional edges between nodes $X_2$ and $X_3$. Next, we introduce some additional conditions. For any ordering $\pi$, define a least squares loss function, $\mathcal{L}(\pi)=\sum_{j=0}^{d-1} {\mathbb{E}} \left\{ X_{j+1}-{\mathbb{E}} \left( X_{j+1}|X_{\{\pi_1,\ldots,\pi_{j} \}} \right) \right\}^2$. Moreover, we focus on neural networks with a ReLU activation function, $\sigma(x)=\max(0,x)$. \vspace{-0.05in} \begin{enumerate}[({C}1)] \addtocounter{enumi}{5} \setlength\itemsep{-0.25em} \item All minimizers of $\mathcal{L}(\pi)$ are contained in $\Pi^*$. \item The widths of all layers in the MLP share a common asymptotic order $H$. Besides, the number of layers $L$ and the asymptotic order $H$ diverge with $NT$, in that $HL=O\{(NT)^{\kappa_8}\}$, for some constant $\kappa_8<1/2$. \item Suppose \tsb{MLP}$\big\{ \cdot;\widetilde{\theta}^{(s)}(\pi) \big\}$ is bounded for any $\pi$. \end{enumerate} \noindent Assumption (C6) is reasonable and holds in numerous scenarios. One example is when all the random errors $\{\varepsilon_j\}_{j=1}^{d}$ in model \eqref{eqn:model} are normally distributed with equal variance. In that case, the least squares loss $\mathcal{L}$ is proportional to the expected value of the log-likelihood of $X$. Since the underlying DAG is identifiable, any ordering that minimizes the expected log-likelihood belongs to $\Pi^*$. Assumption (C7) is also mild, as both $H$ and $L$ are the parameters that we specify. The part that $HL=O\{(NT)^{\kappa_8}\}$ ensures that the stochastic error resulting from the parameter estimation in the MLP is negligible. Assumption (C8) ensures that the optimizer would not diverge in the $\ell_{\infty}$ sense. Similar assumptions are common in the literature to derive the convergence rates of deep learning estimators \citep[see e.g.][]{farrell2018deep}. Now we show that the estimator $\widehat{\theta}^{(s)}$ obtained from \eqref{eqn:DAG} satisfies the oracle property, i.e., $\widehat{\theta}^{(s)}=\widetilde{\theta}^{(s)}(\pi^*)$, for some $\pi^* \in \Pi^*$. In other words, $\widehat{\theta}^{(s)}$ is computed as if one of the true ordering were known in advance. By the definition of $\Pi^*$, Assumption (C1) holds for our estimated DAG. Moreover, we note that the oracle property does \emph{not} imply the selection consistency, i.e., $\textrm{PA}_j = \widehat{\textrm{PA}}_j$ for any $j=1,\ldots,d$. Nor does it imply the sure screening property, in that $\textrm{PA}_j \subseteq \widehat{\textrm{PA}}_j$ for any $j=1,\ldots,d$. \begin{theorem}\label{thm4} Suppose (C6)-(C8) hold, the $\beta$-mixing coefficient $\beta(q)$ in (C4) decays exponentially with $q$, and $\lambda \to 0$. Then, with probability approaching one, $\widehat{\theta}^{(s)}=\widetilde{\theta}^{(s)}(\pi^*)$, for some $\pi^* \in \Pi^*$, as either $N$ or $T \to \infty$. \end{theorem} \section{Simulations} \label{sec:sim} In this section, we examine the finite-sample performance of the proposed testing procedure. We begin with a discussion of some implementation details. Our test employs three neural networks-based learners, which involve some tuning parameters. Many of these parameters are standard in neural networks learning, e.g., the number of hidden layers, the number of hidden nodes in each layer, the activation function, batch size, and epoch size. In our implementation, we set those parameters at their usual values as recommended by the literature. Specifically, for the DAG learning step, one tuning parameter is the sparsity parameter $\lambda$ in \eqref{eqn:DAG}. Following a similar strategy as in \cite{zheng2020learning}, we fix $\lambda=0.025$ in our implementation to speed up the computation. We have also experimented with a number of values of $\lambda$ in some interval and find the results are not overly sensitive. Moreover, $\lambda$ can be tuned via cross-validation. We set the rest of the parameters the same as in the implementation of \cite{zheng2020learning}. For the supervised learning step, we employ the multilayer perceptron regressor implementation of \citet{SCIKit2011}. For the GANs training step, we follow the implementation of \citet{genevay2017learning}. There are three additional parameters associated with our test, including the number of transformation functions $B$, the number of pseudo samples $M$ produced by the GAN generator, and the number of observations $K$ in the batched standard error estimators $\widehat{\sigma}_{b,\textrm{CF}}^{(s)}$ and $\widehat{\sigma}_{b,\textrm{NCF}}^{(s)}$. We have found that the results are not sensitive to the choice of $M$ and $K$, and we fix $M=100$ and $K=20$. For $B$, a larger value generally improves the power of the test, but also increases the computational cost. In our implementation, we set $B=2000$, which achieve a reasonable balance between the test accuracy and the computational cost. We compare the proposed test with two alternative solutions, the double regression-based test (DRT) as outlined in Section \ref{sec:equiv}, and the constrained likelihood ratio test (LRT) proposed by \citet{li2019likelihood} for linear DAGs. The implementation of DRT is similar to our proposed method. The main difference lies in that DRT uses the MLP regressor to first estimate the conditional mean function ${\mathbb{E}} (X_k|X_{\widehat{\mathcal{M}}^{(j)}_{j,k}})$ in Step 4, then plugs in this estimate to construct the test statistic in Step 5, with $B=1$ and $h_1^{(s)}(X_k,X_{\widehat{\mathcal{M}}^{(j)}_{j,k}})=X_k$. We consider two different models, a nonlinear DAG and a linear DAG, \begin{align} X_{t,j} & = \sum_{\substack{k_1,k_2 \in \scriptsize{\hbox{PA}}_{j}\\ k_1 \leq k_2}}c_{j,k_1,k_2}f^{(1)}_{j,k_1,k_2}(X_{t,k_1})f^{(2)}_{j,k_1,k_2}(X_{t,k_2}) \label{eqn:sim-nonlinear} + \sum_{k_3 \in \scriptsize{\hbox{PA}}_{j}}c_{j,k_3}f_{j,k_3}^{(3)}(X_{t,k_3}) + \varepsilon_{t,j}; \\ X_{t,j} & = \sum_{k \in \scriptsize{\hbox{PA}}_j} c_{j,k} X_{t,k} + \varepsilon_{t,j}. \label{eqn:sim-linear} \end{align} The data generation follows that of \cite{zhu2020causal}. Specifically, for the nonlinear model \eqref{eqn:sim-nonlinear}, the functions $f^{(1)}_{j,k_1,k_2}$, $f^{(2)}_{j,k_1,k_2}$, and $f_{j,k_3}^{(3)}$ are randomly set to be sine or cosine function with equal possibility, whereas the coefficients $c_{j,k_1,k_2}$ and $c_{j,k_3}$ are randomly generated from the uniform distribution $[0.5,1.5]$ or $[-1.5,-0.5]$ with equal possibility. For the linear model \eqref{eqn:sim-linear}, $c_{j,k}$ is the coefficient randomly generated from the uniform distribution $[0.3,0.5]$ or $[-0.3,-0.5]$ with equal possibility. Then a portion of coefficients are randomly set to zero. For both linear and nonlinear cases, the error $\varepsilon_{t,j}$ is an AR(0.5) process with a standard normal white noise. The DAG structure is determined by a $d \times d$ lower triangular binary adjacency matrix, in which each entry is randomly sampled from a Bernoulli distribution with the success probability $\zeta$. For the nonlinear model \eqref{eqn:sim-nonlinear}, we consider three combinations, $(d, \zeta) = (50, 0.1)$, $(d, \zeta) = (100, 0.04)$, and $(d, \zeta) = (150, 0.02)$, and for the linear model \eqref{eqn:sim-linear}, we consider $(d, \zeta) = (50, 0.1)$. In all cases, we set the number of subjects $N=20$, and the number of time points $T = 100$. \begin{table}[t!] \centering \caption{The percentage of times out of 500 data replications when the $p$-value is smaller than the nominal level $\alpha$. Three methods are compared: our proposed test (SUGAR), the double regression-based test (DRT), and the constrained likelihood ratio test (LRT). This table reports the results for the nonlinear model \eqref{eqn:sim-nonlinear} with $d=50, \zeta=0.1$.} \label{tab:nonlinear-d50} \setlength{\tabcolsep}{1.5mm}{ \begin{tabular}{|c|c|c|c|c|c|c|c|c|c|c|c|} \hline \multicolumn{3}{|c|}{\parbox{1.5cm}{\centering Edge}} & \multicolumn{3}{c|}{\parbox{2cm}{\centering j=35, k=5}} & \multicolumn{3}{c|}{\parbox{2cm}{\centering j=35, k=31}} & \multicolumn{3}{c|}{\parbox{2cm}{\centering j=40, k=16}} \\ \hline \multicolumn{3}{|c|}{Hypothesis}& \multicolumn{3}{c|}{$\mathcal{H}_0$} & \multicolumn{3}{c|}{$\mathcal{H}_0$} & \multicolumn{3}{c|}{$\mathcal{H}_0$} \\ \hline \multicolumn{3}{|c|}{Method} & SUGAR & DRT & LRT & SUGAR & DRT & LRT & SUGAR & DRT & LRT\\ \hline \multicolumn{3}{|c|}{$\alpha=0.05$} & 0.050 & 0.108 & 1.000 & 0.012 & 0.068 & 0.316 & 0.016 & 0.016 & 1.000 \\ \hline \multicolumn{3}{|c|}{$\alpha=0.10$} & 0.078 & 0.154 & 1.000 & 0.032 & 0.098 & 0.412 & 0.032 & 0.030 & 1.000 \\ \hline \multicolumn{3}{|c|}{Edge} & \multicolumn{3}{c|}{j=45, k=14} & \multicolumn{3}{c|}{j=45, k=15} & \multicolumn{3}{c|}{j=50, k=14} \\ \hline \multicolumn{3}{|c|}{Hypothesis}& \multicolumn{3}{c|}{$\mathcal{H}_0$} & \multicolumn{3}{c|}{$\mathcal{H}_0$} & \multicolumn{3}{c|}{$\mathcal{H}_0$} \\ \hline \multicolumn{3}{|c|}{Method} & SUGAR & DRT & LRT & SUGAR & DRT & LRT & SUGAR & DRT & LRT\\ \hline \multicolumn{3}{|c|}{$\alpha=0.05$} & 0.014 & 0.026 & 1.000 & 0.032 & 0.054 & 0.954 & 0.030 & 0.096 & 1.000 \\ \hline \multicolumn{3}{|c|}{$\alpha=0.10$}& 0.030 & 0.050 & 1.000 & 0.058 & 0.092 & 0.964 & 0.046 & 0.126 & 1.000 \\ \hline \multicolumn{3}{|c|}{Edge} & \multicolumn{3}{c|}{j=35, k=4} & \multicolumn{3}{c|}{j=35, k=30} & \multicolumn{3}{c|}{j=40, k=15} \\ \hline \multicolumn{3}{|c|}{Hypothesis}& \multicolumn{3}{c|}{$\mathcal{H}_1$} & \multicolumn{3}{c|}{$\mathcal{H}_1$} & \multicolumn{3}{c|}{$\mathcal{H}_1$} \\ \hline \multicolumn{3}{|c|}{Method} & SUGAR & DRT & LRT & SUGAR & DRT & LRT & SUGAR & DRT & LRT\\ \hline \multicolumn{3}{|c|}{$\alpha=0.05$} & 0.534 & 0.082 & 1.000 & 0.992 & 0.728 & 0.204 & 0.550 & 0.204 & 0.102 \\ \hline \multicolumn{3}{|c|}{$\alpha=0.10$} & 0.546 & 0.126 & 1.000 & 0.992 & 0.818 & 0.290 & 0.550 & 0.264 & 0.180 \\ \hline \multicolumn{3}{|c|}{Edge} & \multicolumn{3}{c|}{j=45, k=12} & \multicolumn{3}{c|}{j=45, k=13} & \multicolumn{3}{c|}{j=50, k=13} \\ \hline \multicolumn{3}{|c|}{Hypothesis}& \multicolumn{3}{c|}{$\mathcal{H}_1$} & \multicolumn{3}{c|}{$\mathcal{H}_1$} & \multicolumn{3}{c|}{$\mathcal{H}_1$} \\ \hline \multicolumn{3}{|c|}{Method} & SUGAR & DRT & LRT & SUGAR & DRT & LRT & SUGAR & DRT & LRT\\ \hline \multicolumn{3}{|c|}{$\alpha=0.05$} & 0.946 & 0.524 & 0.988 & 0.808 & 0.248 & 0.832 & 0.670 & 0.188 & 0.730\\ \hline \multicolumn{3}{|c|}{$\alpha=0.10$} & 0.948 & 0.616 & 0.996 & 0.816 & 0.318 & 0.870 & 0.672 & 0.252 & 0.824\\ \hline \end{tabular} } \end{table} \begin{table}[t!] \centering \caption{Results for model \eqref{eqn:sim-nonlinear} with $d=100, \zeta=0.04$. The rest is the same as Table \ref{tab:nonlinear-d50}.}\label{tab:nonlinear-d100} \setlength{\tabcolsep}{1.5mm}{ \begin{tabular}{|c|c|c|c|c|c|c|c|c|c|c|c|} \hline \multicolumn{3}{|c|}{\parbox{1.5cm}{\centering Edge}} & \multicolumn{3}{c|}{\parbox{2cm}{\centering j=80, k=37}} & \multicolumn{3}{c|}{\parbox{2cm}{\centering j=85, k=29}} & \multicolumn{3}{c|}{\parbox{2cm}{\centering j=85, k=68}}\\ \hline \multicolumn{3}{|c|}{Hypothesis}& \multicolumn{3}{c|}{$\mathcal{H}_0$} & \multicolumn{3}{c|}{$\mathcal{H}_0$} & \multicolumn{3}{c|}{$\mathcal{H}_0$} \\ \hline \multicolumn{3}{|c|}{Method} & SUGAR & DRT & LRT & SUGAR & DRT & LRT & SUGAR & DRT & LRT\\ \hline \multicolumn{3}{|c|}{$\alpha=0.05$} & 0.002 & 0.002 & 0.116 & 0.004 & 0.022 & 1.000 & 0.004 & 0.004 & 0.306\\ \hline \multicolumn{3}{|c|}{$\alpha=0.10$} & 0.006 & 0.004 & 0.186 & 0.018 & 0.032 & 1.000 & 0.004 & 0.008 & 0.390\\ \hline \multicolumn{3}{|c|}{Edge} & \multicolumn{3}{c|}{j=90, k=18} & \multicolumn{3}{c|}{j=90, k=67} & \multicolumn{3}{c|}{j=90, k=69} \\ \hline \multicolumn{3}{|c|}{Hypothesis}& \multicolumn{3}{c|}{$\mathcal{H}_0$} & \multicolumn{3}{c|}{$\mathcal{H}_0$} & \multicolumn{3}{c|}{$\mathcal{H}_0$} \\ \hline \multicolumn{3}{|c|}{Method} & SUGAR & DRT & LRT & SUGAR & DRT & LRT & SUGAR & DRT & LRT\\ \hline \multicolumn{3}{|c|}{$\alpha=0.05$} & 0.018 & 0.030 & 0.156 & 0.010 & 0.022 & 0.922 & 0.006 & 0.020 & 0.820\\ \hline \multicolumn{3}{|c|}{$\alpha=0.10$} & 0.032 & 0.038 & 0.252 & 0.032 & 0.048 & 0.942 & 0.016 & 0.034 & 0.876\\ \hline \multicolumn{3}{|c|}{Edge} & \multicolumn{3}{c|}{j=80, k=36} & \multicolumn{3}{c|}{j=85, k=28} & \multicolumn{3}{c|}{j=85, k=69} \\ \hline \multicolumn{3}{|c|}{Hypothesis}& \multicolumn{3}{c|}{$\mathcal{H}_1$} & \multicolumn{3}{c|}{$\mathcal{H}_1$} & \multicolumn{3}{c|}{$\mathcal{H}_1$} \\ \hline \multicolumn{3}{|c|}{Method} & SUGAR & DRT & LRT & SUGAR & DRT & LRT & SUGAR & DRT & LRT\\ \hline \multicolumn{3}{|c|}{$\alpha=0.05$} & 0.726 & 0.186 & 0.740 & 0.276 & 0.120 & 0.826 & 0.524 & 0.254 & 1.000\\ \hline \multicolumn{3}{|c|}{$\alpha=0.10$} & 0.726 & 0.250 & 0.798 & 0.296 & 0.162 & 0.878 & 0.528 & 0.294 & 1.000\\ \hline \multicolumn{3}{|c|}{Edge}& \multicolumn{3}{c|}{j=90, k=19} & \multicolumn{3}{c|}{j=90, k=66} & \multicolumn{3}{c|}{j=90, k=68} \\ \hline \multicolumn{3}{|c|}{Hypothesis}& \multicolumn{3}{c|}{$\mathcal{H}_1$} & \multicolumn{3}{c|}{$\mathcal{H}_1$} & \multicolumn{3}{c|}{$\mathcal{H}_1$} \\ \hline \multicolumn{3}{|c|}{Method} & SUGAR & DRT & LRT & SUGAR & DRT & LRT & SUGAR & DRT & LRT\\ \hline \multicolumn{3}{|c|}{$\alpha=0.05$} & 0.084 & 0.026 & 0.320 & 0.528 & 0.042 & 0.438 & 0.604 & 0.078 & 0.378\\ \hline \multicolumn{3}{|c|}{$\alpha=0.10$}& 0.112 & 0.042 & 0.426 & 0.536 & 0.074 & 0.502 & 0.606 & 0.124 & 0.464\\ \hline \end{tabular}} \end{table} \begin{table}[t!] \centering \caption{Results for model \eqref{eqn:sim-nonlinear} with $d=150, \zeta=0.02$. The rest is the same as Table \ref{tab:nonlinear-d50}.} \label{tab:nonlinear-d150} \setlength{\tabcolsep}{1.5mm}{ \begin{tabular}{|c|c|c|c|c|c|c|c|c|c|c|c|} \hline \multicolumn{3}{|c|}{\parbox{1.5cm}{\centering Edge}} & \multicolumn{3}{c|}{\parbox{2cm}{\centering j=132, k=123}} & \multicolumn{3}{c|}{\parbox{2cm}{\centering j=135, k=69}} & \multicolumn{3}{c|}{\parbox{2cm}{\centering j=135, k=84}} \\ \hline \multicolumn{3}{|c|}{Hypothesis}& \multicolumn{3}{c|}{$\mathcal{H}_0$} & \multicolumn{3}{c|}{$\mathcal{H}_0$} & \multicolumn{3}{c|}{$\mathcal{H}_0$} \\ \hline \multicolumn{3}{|c|}{Method} & SUGAR & DRT & LRT & SUGAR & DRT & LRT & SUGAR & DRT & LRT\\ \hline \multicolumn{3}{|c|}{$\alpha=0.05$} & 0.006 & 0.018 & 0.768 & 0.068 & 0.084 & 0.472 & 0.008 & 0.010 & 0.222\\ \hline \multicolumn{3}{|c|}{$\alpha=0.10$} & 0.014 & 0.026 & 0.848 & 0.118 & 0.132 & 0.598 & 0.010 & 0.018 & 0.298\\ \hline \multicolumn{3}{|c|}{Edge} & \multicolumn{3}{c|}{j=137, k=12} & \multicolumn{3}{c|}{j=137, k=124} & \multicolumn{3}{c|}{j=140, k=44} \\ \hline \multicolumn{3}{|c|}{Hypothesis}& \multicolumn{3}{c|}{$\mathcal{H}_0$} & \multicolumn{3}{c|}{$\mathcal{H}_0$} & \multicolumn{3}{c|}{$\mathcal{H}_0$} \\ \hline \multicolumn{3}{|c|}{Method}& SUGAR & DRT & LRT & SUGAR & DRT & LRT & SUGAR & DRT & LRT\\ \hline \multicolumn{3}{|c|}{$\alpha=0.05$} & 0.014 & 0.016 & 1.000 & 0.020 & 0.038 & 0.970 & 0.002 & 0.000 & 0.194 \\ \hline \multicolumn{3}{|c|}{$\alpha=0.10$} & 0.020 & 0.024 & 1.000 & 0.044 & 0.068 & 0.986 & 0.002 & 0.002 & 0.270 \\ \hline \multicolumn{3}{|c|}{Edge} & \multicolumn{3}{c|}{j=132, k=125} & \multicolumn{3}{c|}{j=135, k=72} & \multicolumn{3}{c|}{j=135, k=81} \\ \hline \multicolumn{3}{|c|}{Hypothesis}& \multicolumn{3}{c|}{$\mathcal{H}_1$} & \multicolumn{3}{c|}{$\mathcal{H}_1$} & \multicolumn{3}{c|}{$\mathcal{H}_1$} \\ \hline \multicolumn{3}{|c|}{Method} & SUGAR & DRT & LRT & SUGAR & DRT & LRT & SUGAR & DRT & LRT\\ \hline \multicolumn{3}{|c|}{$\alpha=0.05$} & 0.678 & 0.254 & 0.936 & 0.832 & 0.742 & 0.994 & 0.842 & 0.740 & 0.876\\ \hline \multicolumn{3}{|c|}{$\alpha=0.10$} & 0.684 & 0.354 & 0.968 & 0.832 & 0.772 & 0.998 & 0.842 & 0.768 & 0.922 \\ \hline \multicolumn{3}{|c|}{Edge} & \multicolumn{3}{c|}{j=137, k=11} & \multicolumn{3}{c|}{j=137, k=123} & \multicolumn{3}{c|}{j=140, k=46} \\ \hline \multicolumn{3}{|c|}{Hypothesis}& \multicolumn{3}{c|}{$\mathcal{H}_1$} & \multicolumn{3}{c|}{$\mathcal{H}_1$} & \multicolumn{3}{c|}{$\mathcal{H}_1$} \\ \hline \multicolumn{3}{|c|}{Method} & SUGAR & DRT & LRT & SUGAR & DRT & LRT & SUGAR & DRT & LRT\\ \hline \multicolumn{3}{|c|}{$\alpha=0.05$} & 0.962 & 0.616 & 0.192 & 0.690 & 0.358 & 0.998 & 0.938 & 0.744 & 0.980\\ \hline \multicolumn{3}{|c|}{$\alpha=0.10$} & 0.962 & 0.710 & 0.262 & 0.690 & 0.412 & 0.998 & 0.938 & 0.812 & 0.992\\ \hline \end{tabular}} \end{table} \begin{table}[t!] \centering \caption{Results for model \eqref{eqn:sim-linear} with $d=50, \zeta=0.1$. The rest is the same as Table \ref{tab:nonlinear-d50}.} \label{tab:linear} \setlength{\tabcolsep}{1.5mm}{ \begin{tabular}{|c|c|c|c|c|c|c|c|c|c|c|c|} \hline \multicolumn{3}{|c|}{\parbox{1.5cm}{\centering Edge}} & \multicolumn{3}{c|}{\parbox{2cm}{\centering j=40, k=16}} & \multicolumn{3}{c|}{\parbox{2cm}{\centering j=40, k=29}} & \multicolumn{3}{c|}{\parbox{2cm}{\centering j=45, k=14}} \\ \hline \multicolumn{3}{|c|}{Hypothesis} & \multicolumn{3}{c|}{$\mathcal{H}_0$} & \multicolumn{3}{c|}{$\mathcal{H}_0$} & \multicolumn{3}{c|}{$\mathcal{H}_0$} \\ \hline \multicolumn{3}{|c|}{Method} & SUGAR & DRT & LRT & SUGAR & DRT & LRT & SUGAR & DRT & LRT \\ \hline \multicolumn{3}{|c|}{$\alpha=0.05$} & 0.034 & 0.034 & 0.120 &0.014 & 0.026 & 0.148 & 0.056 & 0.114 & 0.196 \\ \hline \multicolumn{3}{|c|}{$\alpha=0.10$}& 0.058 & 0.046 & 0.182 & 0.024 & 0.036 & 0.218 & 0.114 & 0.178 & 0.258 \\ \hline \multicolumn{3}{|c|}{Edge} & \multicolumn{3}{c|}{j=45, k=15} & \multicolumn{3}{c|}{j=50, k=14} & \multicolumn{3}{c|}{j=50, k=20} \\ \hline \multicolumn{3}{|c|}{Hypothesis} & \multicolumn{3}{c|}{$\mathcal{H}_0$} & \multicolumn{3}{c|}{$\mathcal{H}_0$} & \multicolumn{3}{c|}{$\mathcal{H}_0$} \\ \hline \multicolumn{3}{|c|}{Method} & SUGAR & DRT & LRT & SUGAR & DRT & LRT & SUGAR & DRT & LRT \\ \hline \multicolumn{3}{|c|}{$\alpha=0.05$} & 0.020 & 0.032 & 0.138 & 0.038 & 0.084 & 0.244 & 0.030 & 0.054 & 0.076 \\ \hline \multicolumn{3}{|c|}{$\alpha=0.10$} & 0.032 & 0.048 & 0.192 & 0.054 & 0.124 & 0.296 & 0.054 & 0.082 & 0.12 \\ \hline \multicolumn{3}{|c|}{Edge} & \multicolumn{3}{c|}{j=40, k=15} & \multicolumn{3}{c|}{j=40, k=28} & \multicolumn{3}{c|}{j=45, k=12} \\ \hline \multicolumn{3}{|c|}{Hypothesis} & \multicolumn{3}{c|}{$\mathcal{H}_1$} & \multicolumn{3}{c|}{$\mathcal{H}_1$} & \multicolumn{3}{c|}{$\mathcal{H}_1$} \\ \hline \multicolumn{3}{|c|}{Method} & SUGAR & DRT & LRT & SUGAR & DRT & LRT & SUGAR & DRT & LRT \\ \hline \multicolumn{3}{|c|}{$\alpha=0.05$} & 0.812 & 0.944 & 0.998 & 0.500 & 0.520 & 1.000 & 0.986 & 1.000 & 1.000 \\ \hline \multicolumn{3}{|c|}{$\alpha=0.10$} & 0.852 & 0.944 & 0.998 & 0.504 & 0.520 & 1.000 & 0.990 & 1.000 & 1.000 \\ \hline \multicolumn{3}{|c|}{Edge} & \multicolumn{3}{c|}{j=45, k=13} & \multicolumn{3}{c|}{j=50, k=13} & \multicolumn{3}{c|}{j=50, k=21} \\ \hline \multicolumn{3}{|c|}{Hypothesis} & \multicolumn{3}{c|}{$\mathcal{H}_1$} & \multicolumn{3}{c|}{$\mathcal{H}_1$} & \multicolumn{3}{c|}{$\mathcal{H}_1$} \\ \hline \multicolumn{3}{|c|}{Method}& SUGAR & DRT & LRT & SUGAR & DRT & LRT & SUGAR & DRT & LRT \\ \hline \multicolumn{3}{|c|}{$\alpha=0.05$} & 0.994 & 1.000 & 1.000 & 0.998 & 1.000 & 1.000 & 0.992 & 1.000 & 1.000 \\ \hline \multicolumn{3}{|c|}{$\alpha=0.10$} & 0.996 & 1.000 & 1.000 & 0.998 & 1.000 & 1.000 & 0.992 & 1.000 & 1.000 \\ \hline \end{tabular}} \end{table} Tables \ref{tab:nonlinear-d50}-\ref{tab:linear} report the empirical size and power, i.e., the percentage of times out of 500 data replications when the $p$-value is smaller than two nominal levels $\alpha=0.05$ and $\alpha=0.1$ respectively, for a set of pairs $(j,k), j,k=1,\ldots,d$, in the network. First of all, we have observed that our proposed test consistently outperforms the competing ones for \emph{all} pairs of edges, in that the size is well controlled if $\mathcal{H}_0$ is true, and the power is equal or larger if $\mathcal{H}_1$ is true. We have chosen 12 pairs to report in the tables, not because our method performs the best on those pairs, but because the differences between the three methods are relatively distinctive for those pairs. For instance, if the methods achieve about the same power on an edge, we do not choose that edge in the tables. It is clearly seen from the tables that the proposed test achieves a competitive performance. In particular, the test of \citet{li2019likelihood} has difficulty to control the type I error, while the double regression-based test suffers from a lower power for a number of edges in Tables \ref{tab:nonlinear-d50} to \ref{tab:nonlinear-d150}, and some inflated type I error in Table \ref{tab:linear}. These findings also agree with our analytical analysis. In terms of computing time, our testing procedure consists of two main parts: the DAG estimation in Step 2 of Algorithm \ref{alg:full}, and the rest of testing in Steps 3 to 6. The DAG estimation is the most time consuming step, but it only needs to be learnt once for all pairs of edges in the graph. We implemented the DAG estimation step on NVIDIA Tesla T4 GPU, and it took about 5 to 20 minutes when $d$ ranges from 50 to 150 for one data replication. We implemented the rest of testing on N1 standard CPU, and it took about 2 minutes for one data replication. \section{Brain effective connectivity analysis} \label{sec:realdata} We next illustrate our method with a brain effective connectivity analysis based on task-evoked functional magnetic resonance imaging (fMRI) data. The brain is a highly interconnected dynamic system, and it is of great interest in neuroscience to understand the directional relations among the neural elements through fMRI, which measures synchronized blood oxygen level dependent signals at different brain locations. The dataset we analyze is part of the Human Connectome Project \citep[HCP,][]{van2013wu}, whose overarching objective is to understand brain connectivity patterns of healthy adults. We study the fMRI scans of a group of individuals who undertook a story-math task. The task consists of blocks of auditory stories and addition-subtraction calculations, and requires the participant to answer a series of questions. An accuracy score is given at the end based on the participant's answers. We analyze two subsets of individuals with matching age and sex. One set consists of $N = 28$ individuals who scored below 65 out of 100, and the other set consists of $N = 28$ individuals who achieved the perfect score of 100. All fMRI scans have been preprocessed following the pipeline of \citet{glasser2013minimal}, which summarizes each fMRI scan as a matrix of time series data. Each row is a time series with length $T = 316$, and there are 264 rows corresponding to 264 brain regions \citep{power2011functional}. Those brain regions are further grouped into 14 functional modules \citep{Smith2009}. Each module possesses a relatively autonomous functionality, and complex brain tasks are believed to perform through coordinated collaborations among the modules. In our analysis, we concentrate on $d = 127$ brain regions from four functional modules: auditory, visual, frontoparietal task control, and default mode, which are usually believed to be involved in language processing and problem solving task domain \citep{Barch2013}. We apply the proposed test to the two datasets separately. We control the false discovery at $0.05$ using the standard Benjamini-Hochberg procedure \citep{BH1995}. Table \ref{tab:HCP} reports the number of identified significant within-module and between-module connections. We first note that, we have identified many more within-module connections than the between-module connections. The partition of the brain regions into the functional modules has been fully based on the biological knowledge, and our finding lends some numerical support to this partition. In addition, we have identified more within-module connections for the frontoparietal task control module for the high-performance subjects than the low-performance subjects, while we have identified fewer within-module connections for the default mode and visual modules for the high-performance subjects. These findings generally agree with the neuroscience literature. Particularly, the frontoparietal network is known to be involved in sustained attention, complex problem solving and working memory \citep{Menon2011}, and the high-performance group exhibits more active connections for this module. On the other hand, the default mode network is more active during passive rest and mind-wandering, which usually involves remembering the past or envisioning the future rather than the task being performed \citep{van2017mind}, and the high-performance group exhibits fewer active connections for this module. \begin{table}[t!] \centering \caption{The number of identified significant within-module and between-module connections of the four functional modules for the low-performance group (``low" with the score below 65) and the high-performance group (``high" with the perfect score of 100). The number in the parenthesis is the number of brain regions of each functional module.} \label{tab:HCP} \renewcommand\arraystretch{1.8} \setlength{\tabcolsep}{2.1mm}{ \begin{tabular}{|c|c|c|c|c|c|c|c|c|c|} \hline \multicolumn{2}{|c|}{\parbox{2.0cm}{\centering \quad}} & \multicolumn{2}{c|}{\parbox{2.5cm}{\centering Auditory \quad (13)}} & \multicolumn{2}{c|}{\parbox{2.5cm}{\centering Default mode \quad (58)}} & \multicolumn{2}{c|}{\parbox{2.5cm}{\centering Visual \qquad (31)}} & \multicolumn{2}{c|}{\parbox{2.6cm}{\centering Fronto-parietal\quad (25)}}\\ \hline \multicolumn{2}{|c|}{\parbox{2.0cm}{}} & low & high & low & high & low & high & low & high \\ \hline \multicolumn{2}{|c|}{\parbox{2.5cm}{\centering Auditory \quad (13)}} & \parbox{0.9cm}{\centering 20} & 17 & \parbox{0.9cm}{\centering 0} & 0 & \parbox{0.9cm}{\centering 0} & 1 & \parbox{0.9cm}{\centering 2} & 0 \\ \hline \multicolumn{2}{|c|}{\parbox{2.5cm}{\centering Default mode \quad (58)}} & 0 & 0 & 68 & 46 & 3 & 2 & 11 & 23 \\ \hline \multicolumn{2}{|c|}{\parbox{2.5cm}{\centering Visual \qquad (31)}} & 0 & 0 & 3 & 2 & 56 & 46 & 0 & 1 \\ \hline \multicolumn{2}{|c|}{\parbox{2.6cm}{\centering Fronto-parietal\quad (25)}} & 2 & 1 & 11 & 23 & 0 & 1 & 22 & 27 \\ \hline \end{tabular}} \end{table} \section{Extensions} \label{sec:extensions} In this section, we discuss several extensions. In addition to a given edge, we can also test a directed pathway, or a union of directional relations. Furthermore, we can extend the test to the scenario when $X_j$ is categorical and follows a generalized type model. \subsection{Testing a directed pathway} \label{sec:extpath} Suppose the goal is to test a given directed pathway, $j_1\rightarrow j_2 \rightarrow \ldots \rightarrow j_K$, where $j_1,j_2,\ldots,j_K$ are a sequence of nodes in the DAG. The problem can be formulated as the pair of hypotheses: \begin{eqnarray}\label{eqn:hypo1} \begin{split} \mathcal{H}_0: \;\; & \mathcal{H}_0(j_k,j_{k+1})\,\,\textrm{holds~for~some}~k,\,\,\,\,\,\textrm{versus}\\ \mathcal{H}_1: \;\; & \mathcal{H}_0(j_k,j_{k+1})\,\,\textrm{does~\textit{not}~hold~for~any}~k = 1, \ldots, d. \end{split} \end{eqnarray} Under this alternative, each individual null hypothesis $\mathcal{H}_0(j_k,j_{k+1})$ does not hold. Consequently, there exists such a directed pathway. The hypotheses in \eqref{eqn:hypo1} can be tested using the union-intersection principle. Specifically, let $p(j_k,j_{k+1})$ denote the $p$-value for $\mathcal{H}_0(j_k,j_{k+1})$ from the proposed test. Then it is straightforward to show that $\max_k p(j_k,j_{k+1})$ is a valid $p$-value for \eqref{eqn:hypo1}. Based on Theorems \ref{thm2} and \ref{thm3}, we can also show that such a test is consistent. \subsection{Testing a union of directional relations} \label{sec:extunion} Suppose the goal is to test a union of the hypotheses $\cup_{l \in \mathcal{L}} \mathcal{H}_0(j_l,k_l)$. We first apply the proposed test to construct two standardized measures, $\widehat{T}^{(s)}_{b,\textrm{CF}}(j_l,k_l)$ and $\widehat{T}^{(s)}_{b,\textrm{NCF}}(j_l,k_l)$, with and without cross-validation, for each $b=1,\ldots,B, s=1,2$, and $l \in \mathcal{L}$. Then for each $s$, we select the indices $\widehat{b}^{(s)}$ and $\widehat{l}^{(s)}$ that yield the largest measure $\max_{b,l}|\widehat{T}^{(s)}_{b,\textrm{NCF}}(j_l,k_l)|$ in the absolute value. We then construct the Wald type test statistic $\widehat{T}^{(s)}_{\widehat{b}^{(s)},\textrm{CF}}\left( j_{\widehat{l}^{(s)}},k_{\widehat{l}^{(s)}} \right)$. Based on Theorems \ref{thm2} and \ref{thm3}, we can establish the consistency of this test. \subsection{Extension to generalized linear models} \label{sec:extglm} We can further extend the proposed test to the following class of models: \begin{eqnarray*} {\mathbb{E}} (X_j|X_{\scriptsize{\hbox{PA}}_j}) = \phi_j\left\{ f_j(X_{\scriptsize{\hbox{PA}}_j}) \right\}, \quad \textrm{ for any } j=1, \ldots, d, \end{eqnarray*} where the link function $\phi_j$ is pre-specified while the function $f_j$ is unspecified. For instance, when $X_j$ is binary, we may set $\phi_j$ as the logistic function. Similar to Theorem \ref{thm1}, we can show that the null hypothesis in \eqref{eqn:hypothesis2} is equivalent to $I(j,k|\mathcal{M};h)=0$, for all square-integrable function $h$. Therefore, the proposed test can be applied to this class of models as well. \baselineskip=21pt \bibliographystyle{apa}
{'timestamp': '2021-06-04T02:05:20', 'yymm': '2106', 'arxiv_id': '2106.01474', 'language': 'en', 'url': 'https://arxiv.org/abs/2106.01474'}
arxiv
\section*{Acknowledgments} We are thankful to the anonymous reviewers for their helpful comments. This work is supported by Alibaba Group through Alibaba Research Fellowship Program, the National Natural Science Foundation of China (61876003), the Key Research and Development Plan of Zhejiang Province (Grant No.2021C03140), the Fundamental Research Funds for the Central Universities, and Guangdong Basic and Applied Basic Research Foundation (2019A1515010837). \bibliographystyle{acl_natbib} \section{The DIRECT Framework}\label{sec:method} \begin{figure*}[ht] \centering \includegraphics[width=16cm]{pics/model.png} \caption{An overview of the proposed DIRECT framework} \label{fig:model} \end{figure*} In this section, we will introduce the framework of the proposed DIRECT model, which includes a shared BERT encoder and three output layers: subject extraction, object extraction, and relation classification. As shown in Figure \ref{fig:model}, DIRECT is fully adjacency list oriented. The input sentence is firstly fed into the subject extraction module to extract all subjects. Then each extracted subject is concatenated with the sentence, and fed into the object extraction module to extract all objects, which can form a set of subject-object pairs. Finally, the subject-object pair is concatenated with sentence, and fed into the relation classification module to get the relations between them. For balancing the weights of sub-task losses and to improve the global task performance, three modules share the BERT encoder layer and are trained with an adaptive multi-task learning strategy. \subsection{Shared BERT Encoder} In the DIRECT framework, the encoder is used to extract the semantic features from the inputs for three modules. As aforementioned, we employ the BERT~\cite{devlin2019bert} as the shared encoder to make use of its pre-trained knowledge and attention mechanism. The architecture of the shared method is shown in Figure \ref{fig:model}. The lower embedding layer and transformers~\cite{vaswani2017attention} are shared across all the three modules, while the top layers represent the task-specific outputs. The encoding process is as follows: \begin{equation} \mathbf{h}^t = \text{BERT}(\mathbf{x}^t) \end{equation} where $\mathbf{x}^t = [w_1, ..., w_n]$ is the input text of task $t$ and $\mathbf{h}^t$ is the hidden vector sequence of the input. Due to the limited space, the detailed architecture of BERT please refer to the original paper~\cite{devlin2019bert}. \subsection{Subject and Object Extraction} The subject and object extraction modules are motivated by the Pointer-Network~\cite{vinyals2015pointer} architecture, which are widely used in Machine Reading Comprehension (MRC) \cite{rajpurkar2016squad} task. Different from MRC task that only needs to extract a single span, the subject and object extractions need to extract multiple spans. Therefore, in the training phase, we replace $softmax$ function with $sigmoid$ function for the activation function of the output layer, and replace cross entropy (CE)~\cite{goodfellow2016deep} with binary cross entropy (BCE)~\cite{luc2016semantic} for the loss function. Specifically, we will perform independent binary classifications for each token twice to indicate whether the current token is the start or the end of a span. The probability of a token to be start or end is as follows: \begin{align} p_{i,{\text{start}}}^t &= \sigma(\mathbf{W}_{\text{start}}^t \cdot h_i + \mathbf{b}_{\text{start}}^t) \\ p_{i,{\text{end}}}^t &= \sigma(\mathbf{W}_{\text{end}}^t \cdot h_i + \mathbf{b}_\text{end}^t) \end{align} where $h_i$ represents the hidden vector of the $i_{th}$ token, $t \in [s, o]$ represents subject and object extraction respectively, $\mathbf{W}^{t} \in \mathbb{R}^{h \times 1}$ represents the trainable weight, $\mathbf{b}^{t} \in \mathbb{R}^1$ is the bias and $\sigma$ is $sigmoid$ function. During inference, we first recognize all the start positions by checking if the probability $p_{i,{\text{start}}}^t > \alpha$, where $\alpha$ is the threshold of extraction. Then, we identify the corresponding end position with the largest probability $p_{i,{\text{end}}}^t$ between two neighboring start positions. Concretely, assuming $\text{pos}_{j, \text{start}}$ is the start position of the $j_{th}$ span, the corresponding end position is: \begin{equation} \text{pos}_{j, \text{end}} = \underset{\text{pos}_{j, \text{start}} <= i < \text{pos}_{j+1, \text{start}}}{\mathrm{argmax}} p_{i,{\text{end}}}^t \end{equation} Though the overall structure is similar, the inputs for subject and object extraction are different. When extracting the subject, only the original sentence needs to be input: \begin{align} \mathbf{x} &= [w_1, ..., w_n] \\ \text{input}^s &= [\text{[cls]}, \mathbf{x}, \text{[sep]}] \end{align} where $w_i$ represents the $i_{th}$ token of the original sentence. Meanwhile, the object extraction is based on the corresponding subject. To form the input, the subject $s$ and the original sentence $x$ are concatenated with $[sep]$ as follows: \begin{equation} \text{input}^o = [\text{[cls]}, s, \text{[sep]}, \mathbf{x}, \text{[sep]}] \end{equation} \subsection{Relation classification} The output layer of relation classification is relatively simple, which is a normal multi-label classification model. The $[cls]$ vector obtained by BERT encoder is used as the sentence embedding. A fully connected layer is used for the nonlinear transformation, and perform multi-label classification to predict relations of the input subject-object pair. The detailed operations of relation classification are as follows: \begin{equation} \mathbf{P}^{r} = \sigma(\mathbf{W}^{r} \cdot h_{\text{[cls]}} + \mathbf{b}^{r}) \end{equation} where $\mathbf{P}^{r} \in \mathbb{R}^c$ is the predicted probability vector of relations, $\sigma$ is $sigmoid$ function, $\mathbf{W}^{r} \in \mathbb{R}^{h \times c}$ and $\mathbf{b}^{r} \in \mathbb{R}^c$ are the trainable weights and bias, $h$ is the hidden size of encoder, $c$ is the number of relations, and $h_{\text{[cls]}}$ denotes the hidden vector of the first token $\text{[cls]}$. The input for relation classification task is as follows: \begin{equation} \text{input}^r = [\text{[cls]}, s, \text{[sep]}, o, \text{[sep]}, \mathbf{x}, \text{[sep]}] \end{equation} \begin{algorithm}[ht] \caption{Adaptive Multi-task Learning with Dynamic Loss Balancing \label{algo:mtl} \LinesNumbered Initialize model parameters $\Theta$ randomly\; Load pre-trained BERT parameters for shared encoder\; Prepare the data for each task $t$ and pack them into mini-batch: $D^t$, $t\in [s, o, r]$ \; Get the number of batch for each task: $n^t$\; Set the number of epoch for training: $epoch_{max}$\; \For{ $epoch$ in $1, 2, ..., epoch_{max}$}{ 1. Merge all the datasets: $D = D^{s} \cup D^{o} \cup D^{r}$\; 2. Shuffle D\; 3. Initialize EMA for each task $v^t=1$ and its decay $\epsilon=0.99$ \; \For{$b^t$ in $D$}{ // $b^t$ is a mini-batch of $D^t$ \; 4. Compute loss: $l^t(\Theta)$ \; 5. Update EMA: $v^t = (1-\epsilon)\cdot\sum(l^t)+\epsilon \cdot v^t$ \; 6. Calculate and normalize the weights: $w^t = (v^t/n^t) / (v^{r}/n^{r})$ \; 7. Update model $\Theta$ with gradient: $\nabla(w^t\cdot \bar{l^t})$ \; } } \end{algorithm} \subsection{Adaptive Multi-task Learning} In DIRECT, subject extraction module, object extraction module, and relation classification module can be considered as three sub-tasks. As aforementioned, if we train each module directly and separately, the error propagation problem would reduce the task performance. Meanwhile, three independent encoders would consume more memory. Therefore, we use multi-task learning to alleviate this problem, and the encoder layer is shared across three modules. However, applying multi-task learning could be challenging in DIRECT, due to the following problems: $\bullet$ The input and output of the three modules are different, which means we cannot simply sum up the loss of each task. $\bullet$ How should we balance the weights of losses for three sub-task modules? These issues can affect the final results of multi-task training~\cite{shen2019multi,sener2018multi}. In this work, based on the architecture of MT-DNN~\cite{liu2019multi}, we propose a novel adaptive multi-task learning strategy to address the above problems. The algorithm is shown as Algorithm \ref{algo:mtl}. Basically, the datasets are firstly split into mini-batches. A batch is then randomly sampled to calculate the loss. The parameters of the shared encoder and its task-specific layer are updated accordingly. Especially, the learning effect of each task $t$ is different and dynamically changing during training. Therefore, an approach of adaptively adjusting the weights of task losses is applied. The sum of sub-task's loss $\sum l^t$ is utilized to approximate its optimization effect. The adaptive weight adjusting strategy ensures that the more room a sub-task has to be optimized, the more weight its loss will receive. Furthermore, an exponential moving average (EMA) \cite{lawrance1977exponential} is maintained to avoid the drastic fluctuations of loss weights. Last but not least, to make sure that each task has enough influence on the shared encoder, the weight of the sub-task will be penalized according to the training data amount of each sub-task. \section{Introduction}\label{sec:intro} Relational fact extraction, as an essential NLP task, is playing an increasingly important role in knowledge graph construction~\cite{han2019opennre,distiawan2019neural}. It aims to extract relational triplet from the text. A relational triplet is in the form of $(subject, relation, object)$ or $(s, r, o)$~\cite{zeng2019learning}. While various prior models proposed for relational fact extraction, few of them analyze this task from the perspective of output data structure. \begin{figure}[ht] \centering \includegraphics[width=1.0\columnwidth]{pics/example_new.png} \caption{Example of exploring the relational fact extraction task from the perspective of directed graph representation method as output data structure.} \label{fig:example} \end{figure} As shown in Figure~\ref{fig:example}, the relational fact extraction can be characterized as a directed graph construction task, where graph representation flexibility and heterogeneity accompany additional benefaction. In practice, there are three common ways to represent graphs~\cite{gross2005graph}: \textbf{Edge List} is utilized to predict a sequence of triplets (edges). The recent sequence-to-sequence based models, such as NovelTagging~\cite{zheng2017joint}, CopyRE~\cite{zeng2018extracting}, CopyRL~\cite{zeng2019learning}, and PNDec~\cite{nayak2020effective}, fall into this category. Edge list is a simple and space-efficient way to represent a graph~\cite{arifuzzaman2015fast}. However, there are three problems. First, the triplet overlapping problem~\cite{zeng2018extracting}. For instance, as shown in Figure~\ref{fig:example}, for triplets (Obama, nationality, USA) and (Obama, president\_of, USA), there are two types of relations between the ``Obama'' and ``USA''. If the model only generates one sequence from the text~\cite{zheng2017joint}, it may fail to identify the multi-relation between entities. Second, to overcome the triplet overlapping problem, the model may have to extract the triplet element repeatedly~\cite{zeng2018extracting}, which will increase the extraction cost. Third, there could be an ordering problem~\cite{zeng2019learning}: for multiple triplets, the extraction order could influence the model performance. \textbf{Adjacency Matrices} are used to predict matrices that represent exactly which entities (vertices) have semantic relations (edges) between them. Most early works, which take a pipeline approach~\cite{zelenko2003kernel,zhou2005exploring}, belong to this category. These models first recognize all entities in text and then perform relation classification for each entity pair. The subsequent neural network-based models~\cite{bekoulis2018joint,dai2019joint}, that attempt to extract entities and relations jointly, can also be classified into this category. Compared to edge list, adjacency matrices have better relation (edge) searching efficiency~\cite{arifuzzaman2015fast}. Furthermore, adjacency matrices oriented models is able to cover different overlapping cases~\cite{zeng2018extracting} for relational fact extraction task. But the space cost of this approach can be expensive. For most cases, the output matrices are very sparse. For instance, for a sentence with $n$ tokens, if there are $m$ kinds of relations, the output space is $n \cdot n \cdot m$, which can be costly for graph representation efficiency. This phenomenon is also illustrated in Figure~\ref{fig:example}. \textbf{Adjacency List} is designed to predict an array of linked lists that serves as a representation of a graph. As depicted in Figure~\ref{fig:example}, in the adjacency list, each vertex $v$ (key) points to a list (value) containing all other vertices connected to $v$ by several edges. Adjacency list is a hybrid graph representation between edge list and adjacency matrices~\cite{gross2005graph}, which can balance space and searching efficiency\footnote{More detailed complexity analyses of different graph representations are provided in Appendix section~\ref{ass:cagr}.}. Due to the structural characteristic of the adjacency list, this type of model usually adopts a cascade fashion to identify subject, object, and relation sequentially. For instance, the recent state-of-the-art model CasRel~\cite{wei2020novel} can be considered as an exemplar. It utilizes a two-step framework to recognize the possible object(s) of a given subject under a specific relation. However, CasRel is not fully adjacency list oriented: in the first step, it use $subject$ as the key; while in the second step, it predicts $(relation, object)$ pairs using adjacency matrix representation. Despite its considerable potential, the cascade fashion of adjacency list oriented model may cause problems of sub-task error propagation~\cite{shen2019multi}, i.e., errors from ancestor sub-tasks may accumulate to threaten downstream ones, and sub-tasks can hardly share supervision signals. Multi-task learning~\cite{caruana1997multitask} can alleviate this problem, however, the sub-task loss balancing problem~\cite{chen2018gradnorm,sener2018multi} could compromise its performance. Based on the analysis from the perspective of output data structure, we propose a novel solution, a\textbf{D}jacency l\textbf{I}st o\textbf{R}iented r\textbf{E}lational fa\textbf{C}T extraction model (\textbf{DIRECT}), with the following advantages: $\bullet$ For efficiency, DIRECT is a fully adjacency list oriented model, which consists of a shared BERT encoder, the Pointer-Network based subject and object extractors, and a relation classification module. In Section~\ref{sec:computation}, we provide a detailed comparative analysis\footnote{Theoretical representation efficiency analysis of graph representative models are described in Appendix section~\ref{ass:gre}.} to demonstrate the efficiency of the proposed method. $\bullet$ From the performance viewpoint, to address sub-task error propagation and sub-task loss balancing problems, DIRECT employs a novel adaptive multi-task learning strategy with the dynamic sub-task loss balancing approach. In Section \ref{sec:result} and \ref{sec:aba}, the empirical experimental results demonstrate DIRECT can achieve the state-of-the-art performance of relational fact extraction task, and the adaptive multi-task learning strategy did play a positive role in improving the task performance. The major contributions of this paper can be summarized as follows: 1. We refurbish the relational fact extraction problem by leveraging an analytical framework of graph-oriented output structure. To the best of our knowledge, this is a pioneer investigation to explore the output data structure of relational fact extractions 2. We propose a novel solution, DIRECT\footnote{To help other scholars reproduce the experiment outcome, we will release the code and datasets via GitHub: https://github.com/fyubang/direct-ie.\label{ft:code}}, which is a fully adjacency list oriented model with a novel adaptive multi-task learning strategy. 3. Through extensive experiments on two benchmark datasets\textsuperscript{\ref{ft:code}}, we demonstrate the efficiency and efficacy of DIRECT. The proposed DIRECT outperforms the state-of-the-art baseline models. \section{Conclusion} In this paper, we introduce a new analytical perspective to organize the relational fact extraction models and propose DIRECT model for this task. Unlike existing methods, DIRECT is fully adjacency list oriented, which employs a novel adaptive multi-task learning strategy with dynamic sub-task loss balancing. Extensive experiments on two public datasets, prove the efficiency and efficacy of the proposed methods. \section{Related Work}\label{review} \textbf{Relation Fact Extraction}. In this work, we show that all of the relational fact extraction models can be unified into a graph-oriented output structure analytical framework. From the perspective of graph representation, the prior models can be divided into three categories. \textbf{Edge List}, this type of model usually employs sequence-to-sequence fashion, such as NovelTagging~\cite{zheng2017joint}, CopyRE~\cite{zeng2018extracting}, CopyRL~\cite{zeng2019learning}, and PNDec~\cite{nayak2020effective}. Some models of this category may suffer from the triplet overlapping problem and expensive extraction cost. \textbf{Adjacency Matrices}, many early pipeline approaches~\cite{zelenko2003kernel,zhou2005exploring,mintz2009distant} and recent neural network-based models~\cite{bekoulis2018joint,dai2019joint,fu2019graphrel}, can be classified into this category. The main problem for this type of model is the graph representation efficiency. \textbf{Adjacency List}, the recent state-of-the-art model CasRel~\cite{wei2020novel} is a partially adjacency list oriented model. In this work, we propose DIRECT that is a fully adjacency list oriented relational fact extraction model. To the best of our knowledge, few previous works analyze this task from the output data structure perspective. GraphRel~\cite{fu2019graphrel} employs a graph-based approach, but it is utilized from an encoding perspective, while we analyze it from the perspective of output structure. Our work is a pioneer investigation to analyze the output data structure of relational fact extraction. \textbf{Multi-task Learning}. Multi-task Learning (MTL) can improve the model performance. \cite{caruana1997multitask} summarizes the goal succinctly: \textit{``it improves generalization by leveraging the domain-specific information contained in the training signals of related task.''} It has two benefits~\cite{vandenhende2020multi}: (1) multiple tasks share a single model, which can save memory. (2) Associated tasks complement and constrain each other by sharing information, which can reduce overfitting and improve global performance. There are two main types of MTL: hard parameter sharing~\cite{baxter1997bayesian} and soft parameter sharing~\cite{duong2015low}. Most of the multi-task learning is done by summing the loses directly, this approach is not suitable for our case. When the input and output are different, it is impossible to get two losses in one forward propagation. MT-DNN~\cite{liu2019multi} is proposed for this problem. Furthermore, MTL is difficult for training, the magnitudes of different task-losses are different, and the direct summation of losses may lead to a bias for a particular task. There are already some studies proposed to address this problem~\cite{chen2018gradnorm,guo2018dynamic,liu2019end}. They all try to dynamically adjust the weight of the loss according to the magnitude of the loss, the difficulty of the problem, the speed of learning, etc. In this study, we adopt MT-DNN's framework, and propose an adaptive multi-task learning strategy that can dynamically adjust the loss weight based on the averaged EMA~\cite{lawrance1977exponential} of the training data amount, task difficulty, etc. \section{Experiments \subsection{Dataset and Experiment Setting} \textbf{Datasets}. Two public datasets are used for evaluation: \textbf{NYT}~\cite{riedel2010modeling} is originally produced by the distant supervision approach. There are 1.18M sentences with 24 predefined relation types in NYT. \textbf{WebNLG}~\cite{gardent2017creating} is originally created for Natural Language Generation (NLG) tasks. \cite{zeng2018extracting} adopts this dataset for relational triplet extraction task. It contains 246 predefined relation types. There are different versions of these two datasets. To facilitate comparison evaluation, we use the datasets released by~\cite{zeng2018extracting} and follow their data split rules. Besides the basic relational triplet extraction, recent studies are focusing on the relational triplet overlapping problem~\cite{zeng2018extracting,wei2020novel}. Follow the overlapping pattern definition of relational triplets~\cite{zeng2018extracting}, the sentences in both datasets are divided into three categories, namely, Normal, EntityPairOverlap (EPO), and SingleEntityOverlap (SEO). The statistics of the two datasets are described in Table~\ref{table:dataset}. \begin{table}[htbp] \centering \begin{tabular}{ccccc} \toprule[1pt] \multirow{2}*{Category} & \multicolumn{2}{c}{NYT} &\multicolumn{2}{c}{WebNLG}\\ \cline{2-3} \cline{4-5} &Train&Test&Train&Test\\ \hline Normal&37013&3266&1596&246 \\ EPO&9782&978&227&26 \\ SEO&14735&1297&3406&457 \\ \hline ALL&56195&5000&5019&703 \\ \bottomrule[1pt] \end{tabular} \caption{Statistics of Dataset NYT and WebNLG. Note that a sentence can belong to both EPO class and SEO class.} \label{table:dataset} \end{table} \textbf{Baselines}: the following strong state-of-the-art (SoTA) models have been compared in the experiments. $\bullet$ NovelTagging~\cite{zheng2017joint} introduces a tagging scheme that transforms the joint entity and relation extraction task into a sequence labeling problem. It can be considered as edge list oriented. $\bullet$ CopyRE~\cite{zeng2018extracting} is a seq2seq based model with the copy mechanism, which can effectively extract overlapping triplets. It has two variants: CopyRE$_\text{one}$ employs one decoder; CopyRE$_\text{mul}$ employs multiple decoders. CopyRE is also edge list oriented. $\bullet$ GraphRel~\cite{fu2019graphrel} is a GCN (graph convolutional networks)~\cite{kipf2017semi} based model, where a relation-weighted GCN is utilized to learn the interaction between entities and relations. It is a two phases model: GraphRel$_\text{1p}$ denotes 1st-phase extraction model; GraphRel$_\text{2p}$ denotes full extraction model. GraphRel is adjacency matrices oriented. $\bullet$ CopyRL~\cite{zeng2019learning} combines the reinforcement learning with a seq2seq model to automatically learn the extraction order of triplets. CopyRL is edge list oriented. $\bullet$ CasRel~\cite{wei2020novel} is a cascade binary tagging framework, where all possible subjects are identified in the first stage, and then for each identified subject, all possible relations and the corresponding objects are simultaneously identified by a relation specific tagger. This work recently achieves the SoTA results. As aforementioned, CasRel is partially adjacency list oriented. \textbf{Evaluation Metrics}: following the previous work~\cite{zeng2018extracting,wei2020novel}, different models are compared by using standard micro Precision (Prec.), Recall (Rec.), and F1-score\footnote{In this study, the results of baseline models are all self-reported results from their original papers. Meanwhile, the experimental results of our proposed model are the average of five runs.}. An extracted relational triplet (subject, relation, object) is regarded as correct only if the relation and the heads of both subject and object are all correct. \textbf{Implementation Details}. The hyper-parameters are determined on the validation set. To avoid the evaluation bias, all reported results from our method are averaged results for 5 runs. More implementation details are described in Appendix section~\ref{ass:id}. \begin{table*}[htbp] \centering \small \begin{tabular}{c|c|ccc|ccc} \toprule[1pt] \multirow{2}*{Method} & \multirow{2}*{Category} & \multicolumn{3}{c|}{NYT} &\multicolumn{3}{c}{WebNLG}\\ \cline{3-5} \cline{6-8} &&Prec.&Rec.&F1&Prec.&Rec.&F1\\ \hline $\text{NovelTagging}$\cite{zheng2017joint}& EL & 62.4&31.7&42.0&52.5&193.&28.3\\ $\text{CopyRE}_\text{One}$\cite{zeng2018extracting}& EL&59.4&53.1&56.0&32.2&28.9&30.5\\ $\text{CopyRE}_\text{Mul}$\cite{zeng2018extracting}&EL&61.0&56.6&58.7&37.7&36.4&37.1 \\ $\text{GraphRel}_\text{1p}$\cite{fu2019graphrel}&AM&62.9&57.3&60.0&42.3&39.2&40.7 \\ $\text{GraphRel}_\text{2p}$\cite{fu2019graphrel}&AM&63.9&60.0&61.9&44.7&41.1&42.9 \\ $\text{CopyRL}$\cite{zeng2019learning}&EL&77.9&67.2&72.1&63.3&59.9&61.6 \\ $\text{CasRel}$\cite{wei2020novel}&AL$_\text{P}$&89.7&89.5&89.6&93.4&90.1&91.8 \\ \hline $\text{DIRECT(Ours)}$ & AL$_\text{F}$& \textbf{92.3}$\pm$\textbf{0.32}& \textbf{92.8}$\pm$\textbf{0.26}&\textbf{92.5}$\pm$\textbf{0.09}& \textbf{93.6}$\pm$\textbf{0.1}&\textbf{92.7}$\pm$\textbf{0.24}& \textbf{93.2}$\pm$\textbf{0.07}\\ \bottomrule[1pt] \end{tabular} \caption{Results of different methods on NYT and WebNLG datasets. EL: Edge List; AM: Adjacency Matrices; AL$_\text{P}$: Adjacency List (Partially); AL$_\text{F}$: Adjacency List (Fully).} \label{table:res_main} \end{table*} \subsection{Results and Analysis}\label{sec:result} \textbf{Relational Triplet Extraction Performance}. The task performances on two datasets are summarized in Table~\ref{table:res_main}. Based on the experiment results, we have the following observations and discussions: $\bullet$ The proposed DIRECT model outperformed all baseline models in terms of all evaluation metrics on both datasets, which proved DIRECT model can effectively address the relational triplet extraction task. $\bullet$ The best-performed model (DIRECT) and runner-up model (CasRel) were both adjacency list oriented model. These two models overwhelmingly outperformed other models, which indicated the considerable potential of adjacency list (as the output data structure) for improving the task performance. \begin{table}[htbp] \centering \begin{tabular}{c|c|c|c} \toprule[1pt] {Method} &{Element} & NYT & WebNLG\\ \hline \multirow{3}*{CasRel}&s&93.5 &95.7 \\ &o&93.5 &95.3 \\ &r&94.9&94.0 \\ \hline \multirow{3}*{DIRECT(Ours)}&s&\textbf{95.4}&\textbf{97.3} \\ &o&\textbf{96.4}&\textbf{96.4} \\ &r&\textbf{97.8}&\textbf{97.4} \\ \bottomrule[1pt] \end{tabular} \caption{F1-score for extracting elements of relational triplets on NYT and WebNLG datasets.} \label{table:res_rte} \end{table} $\bullet$ To further compare the relation extraction ability of DIRECT and CasRel, we took a closer look at the extraction performance of relational triplet elements from these two models. As shown in Table~\ref{table:res_rte}\footnote{More detailed results with Precision and Recall are provided in Appendix section~\ref{ass:ser}.}, DIRECT outperformed CasRel in terms of all relational triplet elements on both datasets. These empirical results suggested that, for relational triplet extraction, a fully adjacency list oriented model (DIRECT) may have advantages over a partially oriented one (CasRel). \begin{figure}[h] \centering \includegraphics[width=1.0\columnwidth]{pics/overlap.png} \caption{F1 score of extracting relational triples from sentences with different overlapping patterns on NYT dataset.} \label{fig:overlap} \end{figure} \textbf{Ability in Handling The Overlapping Problem}. The relational facts in sentences are often complicated. Different relational triplets may have overlaps in a sentence. To verify the ability of our models in handling the overlapping problem, we conducted further experiments on NYT dataset. Figure~\ref{fig:overlap} illustrated of F1 scores of extracting relational triplets from sentences with different overlapping patterns. DIRECT outperformed all baseline models in terms of all overlapping patterns. These results demonstrated the effectiveness of the proposed model in solving the overlapping problem. \textbf{Ability in Handling Multiple Relation Extraction}. We further compared the model’s ability of extracting relations from sentences that contain multiple triplets. The sentences in NYT and WebNLG were divided into 5 categories. Each category contained sentences that had 1,2,3,4 or $\geq$ 5 triplets. The triplet number was denoted as $N$. As shown in Table~\ref{table:res_dnt}: $\bullet$ DIRECT achieved the best performance for all triplet categories on both datasets. These experimental results demonstrated our model had an excellent ability in handling multiple relation extraction. $\bullet$ In both NYT and WebNLG datasets, when the sentences contained more triplets, the leading advantage of DIRECT became greater. This observation indicated that DIRECT was good at solving complex relational fact extraction. \begin{table*}[htbp] \centering \small \begin{tabular}{c|ccccc|ccccc} \toprule[1pt] \multirow{2}*{Method} & \multicolumn{5}{c|}{NYT} &\multicolumn{5}{c}{WebNLG}\\ \cline{2-6} \cline{7-11} &$N=1$&$N=2$&$N=3$&$N=4$&$N\ge5$&$N=1$&$N=2$&$N=3$&$N=4$&$N\ge5$\\ \hline Count&3244&1045&312&291&108&268&174&128&89&44 \\ \hline $\text{CopyRE}_\text{One}$&66.6&52.6&49.7&48.7&20.3&65.2 &33.0&22.2&14.2&13.2 \\ $\text{CopyRE}_\text{Mul}$&67.1&58.6&52.0&53.6&30.0&59.2&42.5&31.7&24.2&30.0 \\ $\text{GraphRel}_\text{1p}$&69.1&59.5&54.4&53.9&37.5&63.8&46.3&34.7&30.8&29.4 \\ $\text{GraphRel}_\text{2p}$&71.0&61.5&57.4&55.1&41.1&66.0&48.3&37.0&32.1&32.1 \\ $\text{CopyRL}$&71.7&72.6&72.5&77.9&45.9&63.4&62.2&64.4&57.2&55.7 \\ $\text{CasRel}$&88.2&90.3&91.9&94.2&83.7&89.3&90.8&94.2&92.4&90.9 \\ \hline $\text{DIRECT(Ours)}$&\textbf{90.4}&\textbf{93.1}&\textbf{94.3}&\textbf{95.8}&\textbf{93.1}&\textbf{90.3}&\textbf{92.8}&\textbf{94.8}&\textbf{94.0}&\textbf{92.9} \\ \bottomrule[1pt] \end{tabular} \caption{F1-score of extracting relational triplets from sentences with different number (denoted as N) of triplets.} \label{table:res_dnt} \end{table*} \subsection{Ablation Study}\label{sec:aba} To validate the effectiveness of components in DIRECT, We implemented several model variants for ablation tests\footnote{Due to the length limitation, we list two main ablation experiments, the rest will be provided in the Appendix section \ref{ass:ser}.}. The results of the comparison on NYT dataset are shown in Table~\ref{table:aba}. In particular, we aim to address the following two research questions: \textbf{RQ1}: Is it possible to improve the model performance by sharing the parameters of extraction layers? \textbf{RQ2}: Did the proposed adaptive multi-task learning strategy improve the task performance? \begin{table}[htbp] \centering \begin{tabular}{c|ccc} \toprule[1pt] \multirow{2}*{Method} & \multicolumn{3}{c}{NYT} \\ \cline{2-4} &Prec.&Rec.&F1\\ \hline DIRECT$_\text{shared}$ & 92.1 & 91.6 & 91.9\\ DIRECT$_\text{equal}$ & 90.6 & 91.3 & 91.0 \\ DIRECT & \textbf{92.3} & \textbf{92.8} & \textbf{92.5}\\ \bottomrule[1pt] \end{tabular} \caption{Results of model variants for ablation tests.} \label{table:aba} \end{table} \textbf{Effects of Sharing Extraction Layer Parameters (RQ1)}. As described in Section~\ref{sec:method}, the structures of subject extraction and object extraction output layers are exactly the same. To answer RQ1, we merged the subject extraction and object extraction layers into one entity extraction layer by sharing the parameters of output layers of these two modules, denoted as \textbf{DIRECT$_\mathbf{shared}$}. From the results of Table~\ref{table:aba}, we can observe that, sharing the parameters of output layers of two extraction modules would reduce the performance of the model. A possible explanation is that, although the output of these two modules is similar, the semantics of subject and object are different. Hence, directly sharing the output parameters of two modules could lead to an unsatisfactory performance. \textbf{Effects of Adaptive Multi-task Learning (RQ2)}. As described in Section~\ref{sec:method}, the adaptive multi-task learning strategy with the dynamic sub-task loss balancing approach is proposed for improving the task performance. To answer RQ2, we replaced the adaptive multi-task learning strategy with an ordinary learning strategy. In this strategy, the losses of three sub-tasks were computed with equal weights, denoted as \textbf{DIRECT$_\mathbf{equal}$}. From the results of Table~\ref{table:aba}, we can observe that, by using adaptive multi-task learning, DIRECT was able to get a 1.5 percentage improvement on the F1-score. This significant improvement indicated that adaptive multi-task learning played a positive role in the balance of sub-task learning and can improve the global task performance. \begin{table}[htbp] \centering \begin{tabular}{c|c|cc} \toprule[1pt] Method & Category & NYT & WebNLG\\ \hline CopyRe & EL & 329 & 712 \\ MHS & AM & 57369 & 26518 \\ CasRel & AL$_\text{P}$ & 3084 & 15836 \\ \hline DIRECT& AL$_\text{F}$ & \textbf{238} & \textbf{542} \\ \bottomrule[1pt] \end{tabular} \caption{Graph representation efficiency estimation based on the predicted logits amount. EL: Edge List; AM: Adjacency Matrices; AL$_\text{P}$: Adjacency List (Partially); AL$_\text{F}$: Adjacency List (Fully).} \label{tab:logit1} \end{table} \subsection{Graph Representation Efficiency Analysis}\label{sec:computation} Based on the amount estimation of predicted logits\footnote{Numeric output $(0/1)$ of the last layer}, we conduct a graph representation efficiency analysis to demonstrate the efficiency of the proposed method\footnote{From the graph representation perspective, when a method requires fewer logits to represent the graph (set of triples), it will reduce the model fitting difficulty.}. For each graph representation category, we choose one representative algorithms. \textbf{Edge List}: CopyRE~\cite{zeng2018extracting}; \textbf{Adjacency Matrices}: MHS~\cite{bekoulis2018joint}; \textbf{Adjacency List}: CasRel (partially)~\cite{wei2020novel} and the proposed DIRECT (fully). The averaged predicted logits estimation for one sample\footnote{The theoretical analysis of predicted logits for different models are described in Appendix section \ref{ass:gre}.} of different models on two datasets are shown in Table~\ref{tab:logit1}. MHS is adjacency matrices oriented, it has the most logits that need to be predicted. Since CasRel is partially adjacency list oriented, it needs to predict more logits than DIRECT. Theoretically, as an edge list oriented, the predicted logits of CopyRE should be the least. But, as described in Section~\ref{sec:intro}, it needs to extract the entities repeatedly to handle the overlapping problem. Hence, its graph representation efficiency could be worse than our model. The structure of our model is simple and fully adjacency list oriented. Therefore, from the viewpoint of predicted logits estimation, DIRECT is the most representative-efficient model. \section{Appendix} \subsection{Implementation Details}\label{ass:id} We adopted the pre-trained BERT model [BERT-Base-Cased]\footnote{Available at: https://storage.googleapis.com/bert\_models/\\2018\_10\_18/cased\_L-12\_H-768\_A-12.zip} as our encoder, where the number of Transformer layers was 12 and the hidden size was 768. The token types of input were always set to 0. We used Adam as our optimizer and applied a triangular learning rate schedule as suggested by original BERT paper. In addition, we adopted a lazy mechanism for optimization. Different from the momentum mechanism of ordinary Adam optimizer~\cite{kingma2015adam} that updated the output layer parameters for all tasks, this lazy-Adam mechanism wouldn't update the parameters of non-current tasks. The dacay rate $\epsilon$ of EMA was set to 0.99 as default. The max sequence length was 128. The other hyper-parameters were determined on the validation set. Notably, considering our special decoding strategy, we raised the threshold of extraction to 0.9 to balance the precision and the recall. The threshold of relation classification was set to 0.5 as default. The hyper-parameter setting was listed in Table \ref{table:res_hyperpara_appendix}. Our mthod were implemented by Pytorch\footnote{https://pytorch.org/} and run on a server configured with a Tesla V100 GPU, 16 CPU, and 64G memory. \begin{table}[htbp] \centering \begin{tabular}{c|ccc} \toprule[1pt] Hyper-parameter & NYT & WebNLG \\ \hline Learning Rate & 8e-5 & 1e-4 \\ Epoch Num. & 15 & 60 \\ Batch Size & 32 & 16 \\ \bottomrule[1pt] \end{tabular} \caption{Hyper-parameter setting for NYT and WebNLG datasets. } \label{table:res_hyperpara_appendix} \end{table} \subsection{Supplementary Experimental Results}\label{ass:ser} \textbf{Ablation Study}. To validate the effectiveness of components in DIRECT, We implemented several model variants for ablation tests respectively. For experimental fairness, we kept the other components in the same settings when modifying one module. \begin{itemize} \item \textbf{DIRECT$_\mathbf{shared}$}, we merged the subject extraction and object extraction layers into one entity extraction layer by sharing the parameters of output layers of these two modules. \item \textbf{DIRECT$_\mathbf{equal}$}, we replaced the adaptive multi-task learning strategy with an ordinary learning strategy. In this strategy, the losses of three sub-tasks were computed with equal weights, denoted as \textbf{DIRECT$_\mathbf{equal}$}. \item \textbf{DIRECT$_\mathbf{threshold}$}, we simply recognized all the start and end positions of entities by checking if the probability $p_{i,{\text{start/end}}}^t > \alpha$, where $\alpha$ was the threshold of extraction. \item \textbf{DIRECT$_\mathbf{adam}$}, we used ordinary Adam as optimizer. \end{itemize} \begin{table}[h] \centering \begin{tabular}{c|ccc} \toprule[1pt] \multirow{2}*{Method} & \multicolumn{3}{c}{NYT} \\ \cline{2-4} &Prec.&Rec.&F1\\ \hline DIRECT$_\text{shared}$ & 92.1 & 91.6 & 91.9\\ DIRECT$_\text{equal}$ & 90.6 & 91.3 & 91.0 \\ DIRECT$_\text{threshold}$ & 92.8 & 92.0 & 92.4 \\ DIRECT$_\text{adam}$ & 92.1 & \textbf{92.9} & 92.5 \\ DIRECT & \textbf{92.9} & 92.1 & \textbf{92.5}\\ \bottomrule[1pt] \end{tabular} \caption{Results of model variants for ablation tests.} \label{table:aba_all} \end{table} \begin{table*}[htbp] \centering \begin{tabular}{c|c|ccc|ccc} \toprule[1pt] \multirow{2}*{Method} &\multirow{2}*{Element} & \multicolumn{3}{c|}{NYT} &\multicolumn{3}{c}{WebNLG}\\ \cline{3-5} \cline{6-8} &&Prec.&Rec.&F1&Prec.&Rec.&F1\\ \hline \multirow{3}*{CasRel}&s&94.6 &92.4&93.5 &98.7&92.8&95.7 \\ &o&94.1&93.0&93.5 &97.7&93.0&95.3 \\ &r&96.0&93.8&94.9&96.6&91.5&94.0 \\ \hline \multirow{3}*{Ours}&s&95.1&95.1&\textbf{95.1}&97.1&96.8&\textbf{96.9} \\ &o&97.2&96.3&\textbf{96.7}&96.4&96.3&\textbf{96.3} \\ &r&98.6&98.3&\textbf{98.5}&97.6&97.3&\textbf{97.4} \\ \bottomrule[1pt] \end{tabular} \caption{Results on extracting elements of relational triplets} \label{table:res_rte_all} \end{table*} \begin{table*}[htbp] \centering \begin{tabular}{c|ccc} \toprule[1pt] \multirow{2}*{Method} & \multicolumn{3}{c}{NYT} \\ \cline{2-4} &Prec.&Rec.&F1\\ \hline $\text{MHS}^*$ \cite{bekoulis2018joint}&60.7 &58.6 &59.6 \\ $\text{CopyMTL}_{one}$\cite{zeng2020copymtl} &72.7 &69.2 &70.9 \\ $\text{CopyMTL}_{mul}$\cite{zeng2020copymtl} &75.7 &68.7 &72.0 \\ WDec \cite{nayak2020effective}&88.1 &76.1 &81.7 \\ PNDec \cite{nayak2020effective}&80.6 &77.3 &78.9 \\ Seq2UMTree \cite{zhang2020minimize}& 79.1 & 75.1 & 77.1 \\ \hline DIRECT(ours) & \textbf{90.2} & \textbf{90.2} & \textbf{90.2}\\ \bottomrule[1pt] \end{tabular} \caption{Results of different methods under Exact-Match Metrics. * marks results reproduced by official implementation.} \label{table:res_exact} \end{table*} From the results of Table~\ref{table:aba_all}, we can observe that: \begin{enumerate} \item Sharing the parameters of output layers of subject and object extraction modules would reduce the performance of the model. \item Compared to ordinary multi-task learning strategy, by using adaptive multi-task learning, DIRECT was able to get a 1.5 percentage point improvement on F1-score. \item There would be a slight drop in performance, if we just used a simple threshold policy to recognize the start and end positions of an entity. \item Despite the difference in precision and recall, there was no significant difference between these two optimizers (ordinary-Adam \& lazy-Adam ) for the task. \end{enumerate} \textbf{Results on Extracting Elements of Relational Triplets}. The complete extraction performance of relational triplet elements from DIRECT and CaslRel are listed in Table~\ref{table:res_rte_all}. DIRECT outperformed CasRel in terms of all relational triplet elements on both datasets. These empirical results suggest that, for relational triplet extraction, a fully adjacency list oriented model (DIRECT) may have advantages over a partially oriented one (CasRel). \begin{table*}[htbp] \centering \begin{tabular}{ccccc} \toprule[1pt] Category & Method & Theoretical & NYT & WebNLG\\ \hline Edge List & CopyRe & $4kl+kr$ & 329 & 712 \\ Adjacency Matrices & MHS &$llr$& 57369 & 26518 \\ Adjacency List (Partially)& CasRel & $2l+2slr$ & 3084 & 15836 \\ \hline Adjacency List (Fully)& DIRECT & $2l+2sl+or$ & 238 & 542 \\ \bottomrule[1pt] \end{tabular} \caption{Graph representation efficiency based on the theoretical logits amount and the estimated logits amount on two benchmark datasets.} \label{tab:logit1_all} \end{table*} \textbf{Results of Different Methods under Exact-Match Metrics}. In experiment section, we followed the match metric from~\cite{zeng2018extracting}, which only required to match the first token of entity span. Many previous works adopted this match metric~\cite{fu2019graphrel,zeng2019learning,wei2020novel}. In fact, our model is capable of extracting the complete entities. Therefore, we collected papers that reported the results of exact-match metrics (requiring to match the complete entity span). The following strong state-of-the-art (SoTA) models have been compared: $\bullet$ CopyMTL \cite{zeng2020copymtl} is a multi-task learning framework, where conditional random field is used to identify entities, and a seq2seq model is adopted to extract relational triplets. $\bullet$ WDec \cite{nayak2020effective} fuses a seq2seq model with a new representation scheme, which enables the decoder to generate one word at a and can handle full entity names of different length and overlapping entities. $\bullet$ PNDec \cite{nayak2020effective} is a modification of seq2seq model. Pointer networks are used in the decoding framework to identify the entities in the sentence using their start and end locations. $\bullet$ Seq2UMTree \cite{zhang2020minimize} is a modification of seq2seq model, which employs an unordered-multi-tree decoder to to minimize exposure bias. The task performances on NYT dataset are summarized in Table~\ref{table:res_exact}. The proposed DIRECT model outperformed all baseline models in terms of all evaluation metrics. This experimental results further confirmed the efficacy of DIRECT for relational fact extraction task. \subsection{Complexity Analysis of Graph Representations}\label{ass:cagr} For a graph $G=(V,E)$, $|V|$ denotes the number of nodes/entities and $|E|$ denotes the number of edges/relations. Suppose there are $m$ kinds of relations, $d(v)$ denotes the number of edges from node $v$. $\bullet$ Edge List Complexity \begin{enumerate} \item[$-$] Space: $O(|E|)$ \item[$-$] Find all edges/relations from a node: $O(|E|)$ \end{enumerate} $\bullet$ Adjacency Matrices Complexity \begin{enumerate} \item[$-$] Space: $O(|V| \cdot |V| \cdot m)$ \item[$-$] Find all edges/relations from a node: $O(|V| \cdot m)$ \end{enumerate} $\bullet$ Adjacency List Complexity \begin{enumerate} \item[$-$] Space: $O(|V|+|E|)$ \item[$-$] Find all edges/relations from a node: $O(d(v))$ \end{enumerate} \subsection{Graph Representation Efficiency Analysis}\label{ass:gre} Based on the amount estimation of predicted logits\footnote{Numeric output of the last layer} $(0/1)$, we conduct a graph representation efficiency analysis to demonstrate the efficiency of proposed method\footnote{As aforementioned, from the graph representation perspective, when a method requires fewer logits to represent the graph (set of triples), it will reduce the model fitting difficulty.}. For each graph representation category, we choose one representative model algorithms. \textbf{Edge List}: CopyRE~\cite{zeng2018extracting}; \textbf{Adjacency Matrices}: MHS~\cite{bekoulis2018joint}; \textbf{Adjacency List}: CasRel (partially)~\cite{wei2020novel} and DIRECT (fully). Formally, for a sentence whose length is $l$ ($l$ tokens), there are $r$ types of relations, $k$ denotes the number of triplets. Suppose there are $s$ keys (subjects) and $o$ values (corresponding amount of object-based lists) in adjacency list. The theoretical logits amount and the estimated logits amount on two benchmark datasets (NYT and WebNLG) are shown in Table~\ref{tab:logit1_all}. From the viewpoint of predicted logits estimation, DIRECT is the most representative-efficient model.
{'timestamp': '2021-06-04T02:09:01', 'yymm': '2106', 'arxiv_id': '2106.01559', 'language': 'en', 'url': 'https://arxiv.org/abs/2106.01559'}
arxiv
\section{A Reference Architecture} \label{sec:architecture} In this section, we present a reference architecture. \myparwod{Why a Reference Architecture?} From a systems engineering perspective, a reference architecture is the materialization of a `divide and conquer' strategy that splits complex engineering problems into smaller parts. Thus, a reference architecture describes a collection of components and their interactions. In making a reference architecture concrete, we state our understanding of the problem and represent it as a concrete artifact that the community can scrutinize and improve. \subsection{Design Overview} Addressing the PPE problem requires solving a \emph{human} and a \emph{technical} problem. We present an architecture that contains components for both problems, and focus on the implementation of an engine, called \textbf{Niffler}, to address the \emph{technical} problem. The individual components are designed to tackle the different challenges discussed in previous sections. \mypar{Overview} Algorithm~\ref{algo_dod} shows how to orchestrate the reference architecture components to address the PPE problem (human components are highlighted in blue). Niffler\xspace performs offline indexing (Discovery index creation) of the tables to construct path information (to address challenge 2). This path information is made available online to the other components. In addition to this index, the PPE problem requires users to specify the input examples $\chi$. Users use the \textsc{view-specification} component to design and submit queries, which may contain noisy values (Challenge 1). The QBE-style examples and index are then considered by the \textsc{column-selection} component to shortlist a subset of the pathless table collection that contains input example values (lines~\ref{dodline3}-\ref{dodline7}). This component can run with or without human guidance. When guidance is available, it helps to narrow down the candidate columns and tables relevant for the desired view. \textsc{Column-selection} outputs a collection of tables and respective columns that contain input examples (\textsc{Cand}). The candidate columns are then processed by the \textsc{join- graph-search} component (line~\ref{dodline8}) to enumerate and materialize candidate views (addresses Challenge 3). Due to the noise of datasets and input query, the \textsc{join-graph-search} component may generate many candidate PJ-views ({Challenge 4}). Designing ranking criteria for the views is hard because of users' differing criteria and quality of join path information. The \textsc{signal-generation} component (line~\ref{dodline9}) identifies different properties of candidate views---called \emph{signals}---that help in two ways: i) they reduce the size of the candidate views; ii) they guide the search for the desired output, which takes place within the \textsc{view-presentation} stage. The engine could \emph{rank} candidate PJ-views and return the top-1, concluding query processing. A challenge is in finding a relevant ranking criteria given the variety of user needs. Instead, our architecture introduces a \textsc{signal-generation} component and a \textsc{view-presentation} stage (lines~\ref{dodline10}-\ref{dodline13}); both geared towards generating and using information efficiently to identify PJ-views. Niffler\xspace focuses on the technical challenges of identifying signals and does not explore different ways to interact with the user. \begin{figure}[t] \centering \includegraphics[width=\linewidth]{figures/Architecture_digital.pdf} \caption{ Reference Architecture. Niffler implements green components, reuses yellow ones and adapts shaded yellow and green ones. Arrows indicate data flow direction. The bidirectional arrow means there is an interaction between components.} \label{fig:architecture} \end{figure} \subsection{Component Description} We follow the lifecycle of query processing using the architecture in \mbox{Fig.\hspace{0.25em}}\ref{fig:architecture} that shows the \emph{human} components on the right-hand side and the engine's components in the enclosed dashed rectangle. \mypar{\textsc{View Specification} (human)} Users and programs use this component to define and submit queries to the system. Interfaces include Spreadsheet-style, API, natural language, and combinations of these. For QBE-based interfaces, the output of this stage is a set of example attributes and values. This specification can help reduce ambiguity in the search process by interacting with a knowledgeable user. \mypar{\textsc{Column Selection} (technical)} A component that analyzes the input query and identifies filter criteria to select a subset of relevant datasets from all available ones. This component must be designed to identify relevant data even when the input query is noisy, addressing \textbf{Challenge 1} above. The output of this component is a collection of candidate tables and columns. \mypar{\textsc{Discovery Index Creation} (technical) and \textsc{Engine} (technical)} The index creation works \emph{offline} to build discovery indexes over pathless table collections. This component must identify useful discovery indexes on pathless table collection. In particular, it needs to identify join paths (addressing \textbf{Challenge 2}) and other indexes used by the \textsc{column-selection} component. The Discovery engine provides \emph{online} access to the discovery indexes. \mypar{\textsc{Join Graph Search} (technical)} Given a set of candidate tables and an input query, this component identifies all possible join graphs that, when materialized, produce a candidate PJ-view. The main goal of this component is to address the large join path space (\textbf{Challenge 3}). To materialize candidate PJ-views, the join graph search component uses a \textsc{Materializer}, which is a data processing component with the capacity to execute PJ queries. \mypar{\textsc{Signal generation} (technical)} The engine produces many \emph{signals} while processing a query. The role of the \textsc{signal-generation} component is to collect, package, and offer these \emph{signals} to the \textsc{view- presentation} stage, hence helping reduce the number of candidate PJ-views, facilitating the presentation's job and thus addressing \textbf{Challenge 4}. \mypar{\textsc{View Presentation} (human)} The goal of view presentation is to help users select an adequate PJ-view. There are many possible implementations of the \textsc{view-presentation} component~\cite{kraska2018northstar,wongsuphasawat2017voyager,vartak2014seedb}. Niffler does not implement this component, but provides it with signals from \textsc{signal-generation}. \section{Pathless Data Discovery Overview} \label{sec:background} In this section, we define the problem of constructing \textbf{P}J-views over \textbf{P}athless table collections by \textbf{E}xample (PPE) (Section~\ref{subsec:problemdefinition}). We discuss the origin of pathless table collections in Section~\ref{subsec:pathless}, and the challenges they introduce in Section~\ref{subsec:challenges}. \subsection{Definitions and Problem Statement} \label{subsec:problemdefinition} $\mathcal{R}(A_1,\ldots,A_m)$ is a relation schema over $m$ attributes, where $A_i$ denotes the $i^{th}$ attribute. A structured table $D$ comprises a schema $\mathcal{R}(A_1,\ldots,A_m)$ and a set of tuples $T$ where each tuple $t\in T$ is a specific instance of the schema. In practice, tables do not look like the ideal defined above because they may lack header information, have ambiguous names and contain dirty and noisy data. More formally, \begin{definition}[Noisy structured data] A noisy dataset $D$ collected from a pathless table collection is characterized by an incomplete schema information $\mathcal{R}(A_1,\ldots,A_m)$ where $A_i=\phi$ for missing header values and tuples $T$ such that each tuple $t\in T$ contains at most $m$ values. \end{definition} In addition, a pathless collection may contain datasets with contradictory values, e.g.,\ two census tables with different population counts for the same states of the country. \begin{definition}[Pathless Table Collection ] A pathless table collection over sources $\mathcal{S}$ contains a set of noisy structured tables $\mathcal{D} = \{D_1,\ldots, D_n\}$ where each $D_i$ is a noisy structured table generated by a source $S_i\in \mathcal{S}$, and datasets $D_i, D_j$ may contain contradictory values. \end{definition} Sources may contain overlapping tables and have varied degrees of quality---some sources generating accurate data while others containing noisy, ambiguous, and incorrect values. \smallskip \noindent \textbf{PJ-example-query} A PJ-query (hereafter called query) contains example tuples of the desired output. In an ideal setting, an expert is aware of the output and provides accurate examples to query the system. However, larger table collections make it hard for an individual to specify accurate examples that are present in the collection. \begin{definition}[Noisy query] The input query $q$ is a noisy structured table consisting of $l$ example tuples, $\chi=\{\chi_1,\ldots, \chi_l\}$ where each $\chi_i$ is a noisy tuple denoting example values that are expected to be present in the desired output. The different columns in the examples $\chi$ are denoted by $\chi.A_i, \forall i\in\{1,\ldots, \tau \}$. \end{definition} The user's table requirements are more complex than the input examples $\chi$ and depending on user's knowledge, some examples may be incorrect. Given a query $q$, there may be many tables in the data collection that contain the input examples, and many combinations of these may satisfy $q$, resulting in a large number of candidate PJ-views. \begin{problem}[Project-Join View Discovery over Pathless Table Collections\label{prob:exploration}] Consider a Pathless Table Collection\ $\mathcal{D}$ and a query $q$ that contains a set of examples $\chi$. The goal is to construct a minimal candidate set of PJ-views $\mathcal{D}'$ that satisfy the user requirements. \end{problem} The user requirements vary based on the application and we do not make any assumptions. For example, a stringent user may demand all examples $\chi$ to appear in the final output while another user may want to identify instead all PJ-views that contain any of the input examples for the data exploration task. Formalizing different types of user requirements is outside the scope of this work. \subsection{What is a Pathless Table Collection?} \label{subsec:pathless} Pathless table collections arise in many scenarios: \noindent \textbf{Multi-source data integration.} Organizations use multiple databases to accomplish their goals, e.g.,\ human resources, product, marketing, etc. While each individual database may be well designed and contain a rich schema, there is no join path information across databases, and combining disparate databases is a demand of modern workloads. For example, consider an ML engineer who wants to combine data from the product database with the marketing database to assemble a training dataset. When attempting to do so, the ML engineer faces a PPE problem: understanding what tables to use and how to combine them is challenging. \input{sections/new-sota-table} \noindent \textbf{Data lakes and cloud storage.} To facilitate access to datasets, many organizations use data lakes, which serve as central repositories. Cheap storage means there is a tendency to hoard datasets in the lakes if they hold any promise to be useful in the future. These datasets do not have join path information, and data lakes do not have a discovery function. As a result, despite the potential upsides, finding relevant datasets in data lakes becomes a bottleneck. This challenge explains the rise of data discovery solutions~\cite{halevy2016goods, aurum,tableUnionSearch, zhang2019juneau, auctus}. \noindent \textbf{Open data repositories.} Recently, many government websites like data.gov in the United States, data.gov.uk in the UK have openly shared datasets. Web data commons (WDC) has also shared a corpus of around 200M web tables crawled from more than 15M web domains. The datasets available from these different sources use different naming conventions and have varied representations. For example, date in the UK vs US date format. Furthermore, these datasets are usually created by independent agencies and pushed to the repository, so naturally there is no join path information, and that leads to PPE problem. \subsection{Challenges of Pathless Table Collections} \label{subsec:challenges} In this section, we present the challenges that PPE problem statement (Problem~\ref{prob:exploration}) introduces, while summarizing how state-of-the-art work approaches those challenges. \mypar{Challenge 1: Noise in input examples} The input examples provided by the user are a demonstration of the desired output. As the user may not be aware of the different tables available in the repository, not all provided examples need to be present in the same table in the repository. Additionally, some values provided by the user may be outdated or incorrect. Although there are mechanisms to help users ameliorate noise in their input query---such as by interacting with partial results---building a general QBE-over-pathless system requires addressing the challenge of noise in the input queries. The capability of handling example noise of previous approaches is shown in the \textit{Handles Example Noise} column of Table~\ref{tab:comparison} . Query reverse engineering approaches identify a SQL query that produces the exact user-provided examples. Consequently, these approaches are incompatible with noisy input examples. In contrast, QBE systems are designed to find the output that contains the input. When strictly applied, they will not work well with noisy input queries. Finally, approaches that rank output views approximately based on the input-output match are more appropriate (e.g.,\ S4 \cite{s4}). \mypar{Challenge 2: Pathless table collections} Without join path information we cannot find PJ-views. With large volumes of data and lack of domain knowledge, we cannot ask humans to provide join path information manually. An alternative is to compute join paths automatically. This is challenging due to the following reasons. Automatic join discovery algorithms rely on detecting candidate keys and then candidate inclusion dependencies between those candidate keys. Because data is noisy, candidate key detection is a noisy process. Because of the scale of the problem, approximate inclusion dependency methods may be more appropriate than exact methods. Even if exact methods are possible, inclusion dependencies are an approximation to real join paths, so more noise will be naturally introduced. As a consequence, automatically extracted join path information will include spurious join paths. Query-By-Example systems \cite{squid,duoquest,s4,shen14,mweaver} and Query-Reverse-Engineering systems \cite{hao, paleo, qbo,view_definition} are designed to perform on a database with well-defined path information and integrity constraint as indicated in the \textit{Supports Pathless} column of Table~\ref{tab:comparison}. They explore join paths between tables via primary key/foreign key relationship and all join paths are ensured to be correct. Spurious join paths are not considered in their techniques. When introducing wrong join path information to their algorithms, they could generate incorrect queries. Bonifati et al. \cite{bonifati} focus on helping users learn join predicate without assuming any integrity constraint, which is similar to the pathless table collection setting. However, this approach needs to perform a Cartesian product on relevant tables, which introduces a scalability challenge. \mypar{Challenge 3: Join Path Space} Noisy query input (\textbf{Challenge 1}) and join path information (\textbf{Challenge 2}) mean that to find an appropriate PJ-view the engine needs to 'cast a wide net' over any potentially relevant table, and consider all possible join paths. Many candidate PJ-views will be inadequate for at least two different reasons: i) they are combined using a wrong join path (\textbf{Challenge 2}); ii) they lead to a semantically different output than required by the user and it is not possible to disambiguate automatically due to the noisy query input (\textbf{Challenge 1}). Because we cannot tell what join paths are correct before identifying them, \textbf{Challenge 3} consists of dealing with the resulting large join path space. Existing approaches like S4 \cite{s4} and MWeaver \cite{s4} utilize user examples to prune candidate join paths or apply early termination in the process of materializing PJ-views. However, the correctness of pruning is based on the "high-quality" of user-given examples. When user examples are noisy, example-overlap based pruning can cause the missing of right views. \mypar{Challenge 4. The multiplicity of views} A direct consequence of \textbf{Challenge 3} is that a QBE-over-pathless system may produce a large number of PJ-views. A naive strategy presents the user with each of the PJ-views, one by one, until the user selects the right one. But users' knowledge is noisy, and they may not be able to tell the difference between two large PJ-views. At the same time, after going over the entire process of using a user query to find a collection of candidate PJ-views, the engine has a lot of information about these PJ-views that may help users identify an adequate view. \textbf{Challenge 4} consists of exploiting this knowledge to create signals, use the signals to reduce the size of the candidate PJ-views, and expose candidates and signals to downstream components, hence easing the effort of navigating the candidate results. Prior techniques deal with the multiplicity of views through returning a list of top-k queries and their corresponding outputs. Queries are typically ranked by their overlap score with input examples. However, when there is noise in user examples \textbf{(Challenge 1)} and many join paths are spurious \textbf{(Challenge 2)}, ranking models based on overlap become unreliable. For example, there could be many views generated through wrong join paths that have a high overlap with user examples. \subsection{QS: Analysis of existing QBE systems} \label{subsec:comparisons} Existing QBE systems were not designed for pathless table collections so we cannot compare them directly to Niffler. Still, we report here a qualitative study describing the challenges of running QBE systems on pathless table collections. \noindent\textbf{SQuID} does not scale to pathless table scenarios. \textit{SQuID} precomputes an abduction-ready database ($\alpha$DB) that requires human input to select the pairs of table key and attributes of interest from other tables. Without human input the number of combinations grows large, especially given that in pathless table collections some join path information will be wrong. Given that the size of $\alpha$DB can be as large as the original table---for example, \emph{component\_sequences} of ChEMBL is 5.9M and results in an $\alpha$DB size of 8.1M---the storage footprint would multiply. Therefore, we were only able to test \textit{SQuID} on a dataset containing a handful of tables. Without a deep understanding of the input dataset---which we lack in pathless table collections---we can only provide limited information to the system to compute the $\alpha$DB, thus resulting in poor query performance. A more reasonable use of \textit{SQuID} is to employ it as a downstream component to Niffler, where the input is a narrowed-down version of candidate PJ-views. \mypar{Duoquest} \textit{Duoquest} uses \textit{dual-specification} which lets the user specify both a natural language query (NLQ) and an input table containing example tuples and additional information about the attributes (Table Sketch Query). It outputs candidate SQL queries ordered from highest to lowest confidence based on the user's input queries. The user can then preview the query result and select the query they prefer. However, in pathless table collections, manually going through each candidate query may present challenges to the user, since the candidate query may consist of incorrect join tables or keys due to noise in data, or the result of one query can have contradictory information with another query. Therefore, it is difficult for the user to manually inspect the query results and find which queries are correct. An additional presentation phase is necessary to navigate the user among the candidate queries. A more reasonable use of \textit{Duoquest} is to employ it as an implementation of the \textsc{view-specification} component, giving users alternative ways of describing their queries. \section{Conclusions} We presented a reference architecture for the discovery of PJ-views over pathless table collections, and a system, Niffler, that addresses the technical aspects of the problem. Niffler efficiently addresses the challenges of pathless table collections by using a \textsc{column-selection}, \textsc{join- graph-search}, and \textsc{signal-generation} component, which, together, produce small sets of candidate PJ-views. \section{Evaluation} \label{sec:evaluation} In this section, we address four points including the main research questions of the paper \textbf{RQ1} and \textbf{RQ2}: \begin{myitemize} \item \textbf{Qualitative Study (QS).} State-of-the-art QBE systems over pathless table collections \item \textbf{RQ1}: Do \textsc{column-selection} and \textsc{join-graph-search} find relevant PJ-views given a noisy input query over pathless table collections? \item \textbf{RQ2}: Are the 4C-based signals useful for reducing the view choice space? \item \textbf{Microbenchmarks.} We explore the effect of various query and data parameters on Niffler's performance. \end{myitemize} Niffler is built to solve the technical problem and not the human problem of PPE. Consequently, the research questions focus on measuring the degree to which the engine helps identify relevant PJ-views over pathless table collections given a notion of PJ-view. \subsection{Experimental Setup} \subsubsection{Noisy User Workload} The workload consists of a collection of 2-column, 3-row example queries and we experiment with varying number of rows and columns in Section~\ref{subsec:microbenchmarks}. To generate the workload, we first find a PJ-query that produces a result we call the \emph{ground truth PJ-view}. Columns in the \emph{ground truth PJ-view} are called \emph{ground truth columns}. Then, we generate the $2\times 3$ input queries according to three strategies, \emph{Zero Noise}, \emph{Medium Noise}, and \emph{High Noise}. \emph{Zero noise} means we sample values from the \emph{ground truth columns}. In \emph{Medium noise} we sample $\frac{2}{3}$ values from the \emph{ground truth columns} and $\frac{1}{3}$ from a \emph{noise column}, which is a column with a Jaccard Containment of more than 0.8 with respect to the \emph{ground truth column}. Finally, in \emph{High noise} we sample $\frac{1}{3}$ values from the \emph{ground truth column} and $\frac{2}{3}$ from the \emph{noise columns}. \subsubsection{Datasets and Workload} We use 2 real-world large-scale datasets in the end-to-end evaluation. Detailed statistics of these two datasets are shown in Table~\ref{tab:datasets}. \begin{table}[ht] \begin{center} \begin{tabular}{||c c c c c||} \hline Dataset & \#Tables & \#Columns & \specialcell{\#Approx.\\Joinable\\ Columns} & \specialcell{Avg\\ \#Rows }\\ [0.5ex] \hline\hline ChEMBL & 70 & 446 & 435 & 2 million\\ \hline WebTable & 10000 & 39939 & 11.6 million & 14\\ \hline \end{tabular} \caption{Characteristics of Datasets} \label{tab:datasets} \end{center} \end{table} \begin{myitemize} \item \textbf{ChEMBL}: ChEMBL~\cite{ChEMBL} is a database of bioactive molecules with drug-like properties. ChEMBL is large in terms of total data size. However, it has a relatively small number of tables and joinable columns. \item \textbf{Web Tables}~\cite{wdc} data collection is a subset of the WDC corpus containing 10K tables crawled from the web. It has more than 10 million pairs of joinable columns. \end{myitemize} We generate 5 ground truth queries by sampling join paths from the ground truth views of each dataset, 5 noisy user queries (consisting of example values) for each ground truth view and for each of the 3 noise levels. This results in a total of 150 noisy user queries across both datasets and noise levels. \subsubsection{Setup} We run all experiments on a CentOS server with 128GB memory and an Intel(R) Xeon(R) CPU with 12 cores and 2.3GHz speed each. We built the reference implementation using python3.6. The reference implementation uses Aurum as the implementation of the \textsc{Discovery-Index-Construction} and \textsc{Discovery Engine}. Niffler uses Aurum's Jaccard Containment via the \textsc{Neighbors(threshold)} function with a threshold of 0.8---we experiment with other thresholds in Section~\ref{subsec:microbenchmarks}. When searching for join paths, Niffler uses by default a maximum of two hops. \input{sections/comparison} \input{sections/rq1} \input{sections/rq3} \input{sections/sota-components} \input{sections/microbenchmarks} \subsection{Datasets, and Setup} \label{subsec:setup} \subsubsection{Setup} We run all experiments on a CentOS server with 128GB memory and a Intel(R) Xeon(R) CPU with 12 cores and 2.3GHz speed each. We built the reference implementation using python3.6. The reference implementation requires configuring several parameters: \begin{myitemize} \item \textbf{Similarity metric and threshold} The similarity metric and threshold needs to be set in Aurum to build the discovery index. We choose overlap similarity and set the threshold to be 0.8 in the evaluation. In \autoref{schema-quality}, we also experiment with modifying this threshold to study \textbf{RQ3}. \item \textbf{Maximum join hops} In the view search stage, we need to set the parameter $max\_hop$, which is the maximum number of join hops between tables. We set $max\_hop = 2$ on ChemBL and $max\_hop = 1$ on WDC, which suits the discovery needs well in practice. \zz{?} \item \textbf{Percentile for computing score threshold} We set the percentile, $p$, to be the 25-th percentile for computing the score threshold, $\tau$, during view presentation. \end{myitemize} \section{Engine Implementation} \label{sec:dod} In this section, we explain the implementation details of Niffler\xspace. Our design follows the reference architecture and we propose novel algorithms for the different components of the architecture. \sg{Add overall pseudo code for Niffler\xspace} \subsection{Discovery Engine} We use Aurum \cite{aurum}, an open-source data discovery platform as our discovery engine. Aurum reads relations from data sources such as databases, lakes, and files in filesystems, and produces a discovery index. The discovery index is logically a hypergraph where the nodes correspond to columns and edges represent relationships (content similarity or inclusion dependency) between columns. Based on this hypergraph, Aurum provides useful discovery APIs that can help upstream applications query the data. Next, we will introduce three Aurum APIs that will be used in our implementation. \mypar{search\_content(\textit{keyword})} search the full-text-search index and return all columns that contain the input keyword. \mypar{content\_similar\_to(\textit{col})} Users can configure a similarity metric (e.g. overlap similarity) and a threshold in Aurum. In the process of building the discovery index, columns that have a similarity larger than the threshold will be connected. This API returns all columns that are similar to the input column w.r.t the pre-configured similarity metric. \mypar{paths(\textit{table1}, \textit{table2}, \textit{max\_hop})} query the discovery index and retrieve all join paths between table1 and table2 w.r.t the maximum number of hops. \subsection{Column Selection} In the column selection stage, users are given a spreadsheet-style interface where they can specify a set of examples for each attribute they want. When defining a view, users are trying to indicate DoD what datasets and columns are relevant. The crux of the column retrieval problem is to identify relevant columns based on user-given examples. \textbf{Example 1} (Column Selection Strategy) Consider a user who wants to find columns representing COVID-19 vaccination facilities and provides the examples \{Walmart, Walgreens, UChicago Hospital\}. Niffler\xspace first searches for columns matching each example using Aurum and lists results containing at least one example in \autoref{fig:example1}. \autoref{tab:columns} shows the information of each column including the table it belongs to, its name and the number of examples contained in it. \begin{figure}[ht] \centering \includegraphics[width=0.8\linewidth]{figures/example1.png} \caption{Tables that contain at least one user example} \label{fig:example1} \end{figure} \begin{table}[h] \centering \begin{tabular}{||c c c c||} \hline \# & table name & column name & \# Example \\ \hline 1 & covid19\_vaccine\_locations & facility & 2 \\ \hline 2 & flu\_vaccine\_locations & name & 3 \\ \hline 3 & pharmacy\_status & name & 2 \\ \hline 4 & chicago\_pharmacy\_2013 & name & 2 \\ \hline \end{tabular} \caption{column information table} \label{tab:columns} \end{table} Many existing systems consider a column as relevant only if it contains all user-given examples(or contains the most number of examples) because \emph{they assume users have perfect knowledge}. Based on this strategy, only \textit{Column 2} will be selected in Example 1. However, this approach clearly misses the ground truth column, \textit{Column 1}. Normally, users do not exactly know what examples would yield the column of interest, and thus there tends to be noise in users' examples. Making decisions for users by only considering columns that contains all input examples could miss many relevant columns and hence missing right views. Additionally, tables in data lakes have many similar columns and semantic ambiguity, which further increase the difficulty of locating relevant columns for users. Another approach adopted by many systems is to consider one column as relevant as long as it contains one input example. In this case, \textit{Column 1, 2, 3, 4} will all be selected. However, this approach tends to include many irrelevant columns like \textit{Column 3, 4} in the Example 1. In scenarios with many datasets, the number of columns that fulfill at least one example becomes large, leading to many join paths, lots of spurious views, and hence low performance. \sg{To add for future: We choose this clustering algorithm because it is highly efficient. Aurum gives nearest neighbors and this algorithm works well in practice. I can try to show tht this is similar to k-center algorithm.} In summary, existing approaches either select too many columns which lead to poor system performance or select too few columns which could miss relevant columns. Additionally, no approaches let users check whether the system finds the right columns they want. Users can only see the generated views in the final presentation stage at which users can hardly tell which one is his/her desired view because there are too many similar views. However, directly presenting all columns that match at least one user example leaves users an impractical choice space. To tackle this problem, we propose a clustering-based algorithm. After grouping similar columns into clusters, we can reduce the space of options users need to consider and improve the possibility of finding relevant columns. \textbf{Clustering-based Column Retrieval} In the clustering-based column retrieval approach, we cluster similar columns because similar columns are likely to refer to the same entity. In other words, we not only select relevant columns based on example matching number but also consider columns that match less examples but refer to the same entity. Retrieving columns based on clusters can select more columns that are potentially relevant and thus be more noise-tolerant and robust. The clustering-based column retrieval approach is described in \autoref{algo_column_retrieval}. The first step is to find all columns that contain at least one example (line2-5). Then, we will cluster these candidate columns based on the similarity metric provided by Aurum as described in \autoref{algo_cluster}(line6). For each matching column, DoD finds its nearest neighbors based on Aurum API \textit{content\_similar\_to} (line 10) and then add the matching column and its neighbor columns to one cluster. Additionally, If two clusters intersect, DoD merges them into one cluster, improving recall (line 13, 16). After getting all clusters, each cluster will be assigned a score as described in \autoref{algo_score}(line7). The score of one cluster is the maximum number of examples contained in any column in that cluster. Finally, we select clusters that have the maximum score and all columns in them will be considered as relevant. (line 8-12) In Example 1, the final content-based clusters are \{\textit{Column 1, 2}\}, \{\textit{Column 3, 4}\}. The score of each cluster is 3, 2 correspondingly. Our column retrieval stage supports both \textit{automatic mode} and \textit{human-in-the-loop mode}. In the \textit{automatic mode}, clusters with the highest score are selected and all columns in these clusters will be considered as relevant. In the \textit{human-in-the-loop mode}, users have access to the clusters and can choose a different one if they know which is correct. But when they do not know which one is correct, the clustering-method helps steer the search process. Looking at clusters help users gain better knowledge of the data (e.g. concrete attributes they want, more accurate samples). \IncMargin{1em} \begin{algorithm}\SetKwFunction{Union}{Union} \SetKwInOut{Input}{input}\SetKwInOut{Output}{output} \Input{$examples$: a list of examples of one column} \Output{$candidate\_cols$: candidate columns relevant to $examples$} \BlankLine candidate\_cols $\leftarrow$ list[] \tcp*[h]{all columns containing at least one example} all\_cols $\leftarrow$ list[] \For{example $\in$ examples} { \tcp*[h]{get all columns containing the example} cols $\leftarrow$ aurum\_api.search\_content(example) UNION(all\_cols, cols) } clusters $\leftarrow$ cluster\_similar\_columns(all\_cols) cluster\_score $\leftarrow$ assign\_cluster\_score(clusters) max\_score = max(cluster\_score.values()) \For{cluster, score in cluster\_score}{ \If(){score == max\_score}{ candidate\_cols.merge(cluster) } } \Return candidate\_cols \caption{Column Retrieval} \label{algo_column_retrieval} \end{algorithm} \DecMargin{1em} \IncMargin{1em} \begin{algorithm} \SetKwFunction{Union}{Union} \SetKwInOut{Input}{input}\SetKwInOut{Output}{output} \Input{$cols$: a set of candidate columns} \Output{$clusters$: Column Clusters} \BlankLine clusters $\leftarrow$ list[list[]] column\_cluster $\leftarrow$ map() idx $\leftarrow$ 0 \ForEach{col in cols} { \If() {col in column\_clusters}{ \tcp*[h]{has been assigned a cluster} continue } cluster $\leftarrow$ set() cluster.add(col) cluster\_id $\leftarrow$ idx neighbors $\leftarrow$ aurum\_api.content\_similar\_to(col) \ForEach{neighbor in neighbors}{ \If(){neighbor in column\_cluster}{ \tcp*[h]{merge into the existing cluster} cluster\_id $\leftarrow$ column\_cluster[neighbor] } cluster.add(neighbor) } \ForEach{column in cluster}{ column\_cluster[column] $\leftarrow$ cluster\_id } idx $\leftarrow$ idx + 1 } \tcp*[h]{construct clusters} \For{(column, cluster\_id) in column\_cluster}{ clusters[cluster\_id] = column } \Return clusters \caption{Cluster Similar Columns} \label{algo_cluster} \end{algorithm} \DecMargin{1em} \IncMargin{1em} \begin{algorithm} \SetKwData{Left}{left}\SetKwData{This}{this}\SetKwData{Up}{up} \SetKwFunction{Union}{Union}\SetKwFunction{ContentSimilarTo}{ContentSimilarTo} \SetKwInOut{Input}{input}\SetKwInOut{Output}{output} \Input{$clusters$: Columns clusters} \Output{$cluster\_score$: a map between cluster and its score} \BlankLine cluster\_score $\leftarrow$ map() \ForEach{cluster in clusters} { max\_example\_num $\leftarrow$ 0 \ForEach{column in cluster}{ example\_num $\leftarrow$ the number of examples contained in the column \If(){example\_num > max\_example\_num}{ max\_example\_num += 1 } } cluster\_score[cluster] $\leftarrow$ max\_example\_num } \Return cluster\_score \caption{Assign Cluster Score} \label{algo_score} \end{algorithm} \DecMargin{1em} \subsection{Join Graph Search and Materialize} \yg{todo: paraphrase the texts from arxiv paper} \yg{todo: add pesudocode for explore join graphs} In this component, we want to combine relevant columns obtained in the Column Retrieval stage. To achieve this goal, we organize the Join Graph Search and Materialize stage into four steps as described in \autoref{algo_view_search}. First, find all groups of tables that include as many user-wanted columns as possible (line 2). Second, check if a group of tables fulfilling a user's requirement is joinable or not. If it is joinable, explore all possible join graphs between tables (line 3-5). Thirdly, since we decide join graphs based on approximate inclusion dependency and content similarity, join graphs that we have explored in step 3 have various qualities. Thus, we need to sort them based on a scoring model and prioritize materializing "high-quality" ones (line 6). Last, materialize join graphs and produce candidate views (line 7). \subsubsection{\textbf{Find Candidate Groups}} A candidate group is a group of columns that covers as many attributes in the input view as possible. Each column is represented by a tuple (table, column\_name). Thus, each candidate group consists of two parts: a set of tables that covers users' input attributes and a set of columns indicating which column to project in the table after materializing the view. As described in \autoref{find_candidate_groups}, we first get all combinations of candidate columns obtained in the Column Retrieval stage (line 2). Then we iterate every combination to get its corresponding tables and columns (line 5-7). A set of tables and a set of columns can uniquely decide a candidate group. Note that a candidate group cannot be identified only by a set of tables because the columns to be projected could be different. \subsubsection{\textbf{Explore Join Graphs}} After getting all candidate groups, the next step is to select joinable group and explore join graphs among them. A joinable group is a candidate group in which all the tables contained can be combined into one single table through the relational join operation. There may be multiple ways of joining the tables of a joinable group. This can happen if there exists more than one inclusion dependency between a pair of tables, or there are different intermediate tables that can be used to join two tables. Each strategy to join such tables is called a join graph. A joinable group, then, is a candidate group for which there is at least one existing join graph. For each candidate group, DoD must find all join graphs that permit combining all tables. It is necessary to find all join graphs because some may be using a wrong inclusion dependency (leading to a wrong view) or one that is correct, but incompatible with the user’s intent—when there are different semantic views that fulfill the query view. To find all the join graphs, DoD first finds all the join paths between every pair of tables in the group. Then, it combines join paths together to form join graphs that permit joining all tables in the group. DoD discards duplicate join graphs—those that join the same tables on the same attributes—as well as join graphs that do not join every table in the group. In order to identify a join path between a pair of tables, DoD uses Aurum API \textit{paths(table1, table2, max\_hop)}, which returns all join paths between two tables given a maximum number of hops, by querying its discovery index. \subsubsection{\textbf{Sort Join Graphs}} Since we are using approximate inclusion dependency instead of strict PK/FK relationship, some generated join paths will use wrong attributes, or will lead to semantically different views. Because evaluating a join graph is expensive, materializing all join graphs at once without any ranking strategy on a large dataset can take a few minutes, leading to poor user experience. Hence, we devise a scoring model that prioritizes materializing "high-quality" join graphs. A "high-quality" join graph is defined as having "high-quality" join operations and involves less number of tables. "high-quality" join operation means join performed on keys that are more likely to be PK/FK. To measure this property, we calculate and store the uniqueness score \footnote{$uniqueness\_score(column) = \frac{len(set(column))}{len(column)}$} of each column. For a join operation on column a and b, the score of this join is defined as the maximum uniqueness score between a and b. The final scoring formula considers both the quality of each join and the number of joins. \begin{equation}\nonumber Score(join\_graph) = \frac{avg(score(join \in join\_graph))}{1 + ln(1+ln(\#tables))} \end{equation} DoD sorts all join graphs based on this scoring model and passes them to the materialization stage. Then, join graphs of "high-quality" and that are easy to compute will be materialized and presented to users first. \subsubsection{\textbf{Materialize a Join Graph}} A join graph contains the information necessary to join a set of N tables. The join graph nodes represent the tables, and an edge between two nodes indicates that the two tables can be joined together. Each node contains the attribute on which the table should be joined. To materialize a join graph, joins are performed from the leaf nodes to inner ones. A leaf node is one that is connected to only another one. Every time a join is performed, its node and edge are removed. The procedure repeats N-1 times, until the resulting joined table is obtained. \begin{algorithm} \SetKwFunction{AllCombinationOf}{AllCombinationOf} \SetKwInOut{Input}{input}\SetKwInOut{Output}{output} \Input{$attribute\_candidates$: each attribute in the view and its corresponding candidate columns,\\ $offset$: the expected number of output pj-views } \Output{$pj\_views$: list of candidate pj-views} \BlankLine all\_join\_graphs $\leftarrow$ list[] G $\leftarrow$ find\_candidate\_groups(attribute\_candidates) \ForEach{candidate\_group in G} { join\_graphs $\leftarrow$ explore\_join\_graphs(candidate\_group) all\_join\_graphs.append(join\_graphs) } sorted\_graphs $\leftarrow$ sort\_join\_graphs(all\_join\_graphs) pj\_views $\leftarrow$ materialize\_views(sorted\_graphs[0:offset]) \Return pj\_views \caption{Join Graph Search and Materialize} \label{algo_view_search} \end{algorithm} \begin{algorithm} \SetKwFunction{AllCombinationOf}{AllCombinationOf} \SetKwInOut{Input}{input}\SetKwInOut{Output}{output} \Input{$attribute\_candidates$: each attribute in the view and its corresponding candidate columns} \Output{$G$: a list of candidate groups} \BlankLine G $\leftarrow$ list() \ForEach{group in \AllCombinationOf(attribute\_candidates)} { candidate\_group\_table $\leftarrow$ set() candidate\_group\_column $\leftarrow$ set() \ForEach{column in group}{ candidate\_group\_table.append(column[table]) candidate\_group\_column.append(column) } candidate\_group $\leftarrow$ (candidate\_group\_table, candidate\_group\_column) G.append(candidate\_group) } \Return G \caption{Find Candidate Groups} \label{find_candidate_groups} \end{algorithm} \begin{algorithm} \SetKwFunction{AllCombinationOf}{AllCombinationOf} \SetKwInOut{Input}{input}\SetKwInOut{Output}{output} \Input{$candidate\_group$: a candidate group consisting of relevant tables \\ $max\_hop$: maximum join hops between every pair of tables} \Output{$join\_graphs$: join graphs to combine tables in the $candidate\_group$} \BlankLine all\_join\_graphs $\leftarrow$ list[] G $\leftarrow$ find\_candidate\_groups(attribute\_candidates) \ForEach{candidate\_group in G} { join\_graphs $\leftarrow$ explore\_join\_graphs(candidate\_group) all\_join\_graphs.append(join\_graphs) } sorted\_graphs $\leftarrow$ sort\_join\_graphs(all\_join\_graphs) pj\_views $\leftarrow$ materialize\_views(sorted\_graphs[0:offset]) \Return pj\_views \caption{Explore Join Graphs} \label{algo_explore_graphs} \end{algorithm} \subsection{View Presentation} \notera{we likely want to explain 4C first to conceptualize the mental mdoel we have to think of views that come from the same input definition. Then we can use 4C as part of the presentation framework} \zz{yes we need formal definitions of the 4 groups (along with the candidate key), how it's suitable for the data lake setting, and then explain how it's incorporated into the presentation framework.} \notera{can you add the formal definitions? you can start with what's in the dod-arxiv paper and improve on that.} \notera{the algos could have the same formatting as those in the previous sections} \notera{give a top-bottom explanation of view presentation. First, what's its goal. Second, how is that goal achieved, what are the components of the solution. Last, explain in detail the components of the solutions---here's where the algorithms may help a lot} Given a set of output views, the goal of view presentation stage is to reduce the view choice space and help users and software identify their preferred view by presenting the results in an informative way. Although we can prioritize which joins paths to materialize, users may still be left with a large view choice space, given that the number of candidate tables or potential join paths can be extremely large. Moreover, the output views can contain may contain many noises or conflicting information due to incorrect join paths that makes it difficult for users \zz{and software?} to identify their preferred view. We introduce the two major components of view presentation stage to address these two challenges: \zz{come up with a different name? This component can be used alone (for the automatic mode)} \subsubsection{\textbf{4c method}} \zz{explain the motivation behind 4c: 1. reduces the size of view choice space 2. generates signals that can be used as questions during human-in-the loop mode} In order to reduce the size of view choice space, we designed a novel method, called \textit{4C}, that classifies the output views into four categories: \textit{Compatible}, which means that views are identical; \textit{Contained}, which means that the values of one view subsume others; \textit{Complementary}, which means that the set difference of tuples of views is not empty; and \textit{Contradictory}, which means that certain tuples are incompatible across views. Whether a pair of view is \textit{complementary} or \textit{contradictory} depend upon the candidate key it's comparing to. More formally: \begin{definition}[Output view] An output view, $v_i$, contains a set of rows, $R_i$, that can be retrieved with the function $f$, $f(v_i) = R_i$. \end{definition} \begin{definition}[Candidate key] \zz{?they might not be 100\% unique if we limit the candidate key size} A candidate key, $k$, is a set of attributes in an output view, $v_i$, that can uniquely identify each row in $R_i$. We can refer to a row, $r_i \in R_i$, with its candidate key value, $k_i$, which we can use to obtain the row; $k(R_i, k_i) = r_i$. There can be multiple candidate keys in $v_i$ that satisfy this property. \end{definition} \begin{definition}[Compatible views] Two candidate views, $v_1$ and $v_2$, are compatible if they have the same cardinality $|R1| = |R2|$, and their set of tuples is exactly the same: $|(R_1 \setminus R_2)| = 0$ and $|(R_2 \setminus R_1)| = 0$, where the symbol $\setminus$ indicates the set difference operation. \end{definition} \begin{definition}[Contained views] A view, $v_1$, contains another view, $v_2$, when $|(R_1 \setminus R_2)| > 0$ and $|(R_2 \setminus R_1)| = 0$, that is, when all rows of $v_2$ are contained in $v_1$. \end{definition} \begin{definition}[Complementary views] Two views, $v_1$ and $v_2$ are complementary if the two views have the same candidate key, $k$, and $|(K_1 \setminus K_2)| > 0$ and $|(K_2 \setminus K_1)| > 0$, where $K_1$ and $K_2$ are the set of candidate key values for $v_1$ and $v_2$ respectively. That is, each view has candidate key values not contained in the other view. \end{definition} \begin{definition}[Contradictory views] Two views, $v_1$ and $v_2$ are contradictory if the two views have the same candidate key, $k$, and a key value that exists in both views, $k_i \in K_1, K_2$, yields distinct rows, $k(R_1; k_i) \neq k(R_2; k_i)$. Two rows are distinct when any value of any of their attributes is different. \end{definition} Note that although the description above refers to two views, the 4C method classifies multiple views into each of the above categories. For example, a view can be compatible with other views, contains other views, and be complementary or contradictory to other views on a candidate key, all at the same time. Next, we present the algorithm we use to classify the output views into the four above categories. \begin{algorithm} \SetAlgoLined \SetKwInput{KwInput}{Input} \SetKwInput{KwOutput}{Output} \KwInput{$V$, collection of output views} \KwOutput{$G$, views classified per class and schema type} \BlankLine $S \leftarrow classify\_per\_schema(V)$\; \label{4c_main:classify_per_schema} \For{$s \in S$}{ \label{4c_main:loop_schema} $C1 \leftarrow identify\_c1(V)$\; \label{4c_main:c1} $SC1 \leftarrow select\_representative\_c1(C1)$\; \label{4c_main:select_representative_c1} $C2, C34 \leftarrow identify\_c2\_and\_candidate\_c3c4(SC1)$\; \label{4c_main:c2} $C3, C4 \leftarrow identify\_c3\_and\_c4(candidate\_C3C4)$\; \label{4c_main:c3_c4} $G[s] \leftarrow (C1, C2, C3, C4)$\; } \Return $G$\; \caption{Main 4C} \label{4c_main} \end{algorithm} The main body of the algorithm is shown in \autoref{4c_main}. Because 4C works on views with the same schema (attributes in this case), the first step is to separate the output views into groups according to their schema (\autoref{4c_main:classify_per_schema}). Then, the algorithm runs the 4C classification for each group (\autoref{4c_main:loop_schema}), leading to the classification of views into the four categories: \textit{compatible} ($C1$), \textit{contained} ($C2$), \textit{complementary} ($C3$), and \textit{contradictory} ($C4$). It will first identify quickly the compatible and contained views. Then, it identifies complementary and contradictory views among the remaining ones. \begin{algorithm} \SetAlgoLined \SetKwInput{KwInput}{Input} \SetKwInput{KwOutput}{Output} \KwInput{$V$, collection of output views} \KwOutput{$C1$, collection of lists, each list contains $v \in V$ that are compatible} \BlankLine $g \leftarrow map()$\; \For{$v_i \in V$}{ $hv_i \leftarrow hash(v_i)$\; \label{4c_compatible:hash} $add(g, hv_i, v_i)$\; } $C1 \leftarrow g.values()$\; \Return $C1$\; \caption{identify\_c1} \label{4c_compatible} \end{algorithm} \mypar{Identify compatible views} \zz{copied from dod paper} The next step is to identify groups of views that are compatible ($C1$) with each other. The main idea is to hash each view (\autoref{4c_compatible:hash}), and insert the view on a map that is keyed on the hash value. A view hash is the sum of its rows hashes, and a row hash is the sum of its cells hashes. With this hashing method, compatible views are guaranteed to have the same hash value, so this is an efficient way of identifying groups of compatible views fast. Because all compatible views are identical, in the Main 4C algorithm, we select one only to continue the classification (\autoref{4c_main:select_representative_c1}). The selected views are then given to a function in charge of identifying contained groups ($C2$), as well as groups that may be either complementary or contradictory ($C34$), see \autoref{4c_main:c2}. \begin{algorithm} \SetAlgoLined \SetKwInput{KwInput}{Input} \SetKwInput{KwOutput}{Output} \KwInput{$SC1$, collection of output views} \KwOutput{$C2$, list of tuples $(v_C, [vc])$; $v_C$ contains all $[v_c]$. $C34$, list of tuples $(v_i, v_j, I_i, I_j )$; $I_{i,j}$ are the sets of row indices in which $v_i$ and $v_j$ disagree} \BlankLine $(gc2, gc34) \leftarrow (map(), map())$\; \For{$(v_i, v_j) \in pair(SC1)$}{ \label{4c_contained:loop} $(h\_list_i, h\_list_j) \leftarrow (hash\_rows(v_i), hash\_rows(v_j))$\; $(h\_set_i, h\_set_j) \leftarrow (set(h \_list_i), set(h\_list_j))$\; \eIf{$len(h\_set_i) \geq len(h \_set_j)$} { \label{4c_contained:if_start} \If{$(h\_set_j \setminus h\_set_i) = 0$}{ $add(gc2, v_i, v_j)$\; } \label{4c_contained:if_end} } { \label{4c_contained:else_start} $s_{ij} \leftarrow h\_set_i \setminus h\_set_j$\; $s_{ji} \leftarrow h\_set_j \setminus h\_set_i$\; \If{$s_{ij} \geq 0 \land s_{ji} \geq 0$}{ $I_i \leftarrow indices(h\_list_i, s_{ij})$\; $I_j \leftarrow indices(h\_list_j, s_{ji})$\; $add(gc34, v_i, v_j, I_i, I_j)$\; } } \label{4c_contained:else_end} } $(C2, C34) \leftarrow (unpack(gc2), unpack(gc34))$\; \Return $(C2, C34)$\; \caption{identify\_c2\_and\_candidate\_c3c4} \label{4c_contained} \end{algorithm} \mypar{Identify contained views} \zz{copied from dod paper} The function to finding contained views is shown in \autoref{4c_contained}. For each pair of views (\autoref{4c_contained:loop}), the algorithm obtains the list and the set of hashes of each view respectively. The list will be used to identify indexes of rows (because it maintains the order), while the sets are used to quickly tell whether the views are contained or may be complementary. \autoref{4c_contained:if_start}--\autoref{4c_contained:if_end} checks whether the hashes of one view are completely contained on the first, in which case the view is contained in the first and this is recorded in the variable $gc2$. Note that because the loop enumerates pairs of views in both directions, it is not necessary to check for containment in both directions here. If the views are not contained, the algorithm tries to decide if they are candidates for the complementary and contradictory group. This decision is done in \autoref{4c_contained:else_start}--\autoref{4c_contained:else_end}. The algorithm computes the set difference of rows in both directions and checks whether it is non-empty in both cases. When it is, this indicates that each view has hashes not contained in the other view. This can be caused for two different reasons: either one view has rows that are non existent in the other (a case of complementarity), or the values of certain rows differ in some values, which would also lead to different hashes and indicate a contradiction. The algorithm returns the identified groups of contained views as well as those that may be complementary or contradictory. \begin{algorithm} \SetAlgoLined \SetKwInput{KwInput}{Input} \SetKwInput{KwOutput}{Output} \KwInput{$C34$, list of tuples $(v_i, v_j, I_i, I_j)$; $I_{i,j}$ are the sets of row indices in which $v_i$ and $v_j$ disagree} \KwOutput{$C3$, list of tuples $(v_i, v_j, k, K_i, K_j)$, $K_{i,j}$ are the sets of key values of candidate key $k$ in $v_i$ and $v_j$ that are complementary. $C4$, list of tuples $(v_i, v_j, k, K)$, $K$ is the set of key values of candidate key $k$ in which $v_i$ presents a contradiction with respect to $v_j$} \BlankLine $(C3;C4) \leftarrow (set(), set())$\; \For{$(v_i, v_j, I_i, I_j) \in C34$}{ \label{4c_contra_compl:loop} $vsel_i \leftarrow select(v_i, I_i)$\; \label{4c_contra_compl:select_i} $vsel_j \leftarrow select(v_j, I_j)$\; \label{4c_contra_compl:select_j} $k\_list \leftarrow find\_candidate\_keys(v_i, v_j)$\; \label{4c_contra_compl:find_keys} \For{$k \in k\_list$}{ \label{4c_contra_compl:for_key} $KV_i \leftarrow project(vsel_i, k)$\; \label{4c_contra_compl:project_i} $KV_j \leftarrow project(vsel_j, k)$\; \label{4c_contra_compl:project_j} $K\_intersect \leftarrow KV_i \cap KV_j$\; \label{4c_contra_compl:k_intersect} $K \leftarrow find\_contr(vsel_i, vsel_j, K\_intersect)$\; \label{4c_contra_compl:find_contr} $add(C4, v_i, v_j, k, K)$\; \If{$len(K) = 0$}{ $K\_compl \leftarrow (KV_i \cup KV_j ) \setminus K\_intersect$\; \label{4c_contra_compl:k_compl} $(K_i, K_j) \leftarrow find\_compl(vsel_i, vsel_j, K\_compl)$\; \label{4c_contra_compl:find_compl} $add(C3, v_i, v_j, k, K_i, K_j)$\; } } } \Return $(C3, C4)$\; \caption{identify\_c3\_and\_c4} \label{4c_contra_compl} \end{algorithm} \mypar{Identify complementary and contradictory views} The last part of the algorithm is to identify which pairs of views in C34 are complementary and which are contradictory. This corresponds to \autoref{4c_main:c3_c4} in the main body of \autoref{4c_main}. The body of this function is shown in more detail in \autoref{4c_contra_compl}. For each pair of views (\autoref{4c_contra_compl:loop}), it checks whether the different values (hashes) identified between this pair are due to complementarity or contradictions. For that, it first selects the relevant rows from each view (\autoref{4c_contra_compl:select_i}--\autoref{4c_contra_compl:select_j}) and obtains all possible candidate keys, $k\_list$ of the two views (\autoref{4c_contra_compl:find_keys}. Then for each candidate key (\autoref{4c_contra_compl:for_key}), it projects the attributes of that key into the selection (\autoref{4c_contra_compl:project_i}--\autoref{4c_contra_compl:project_j}). This produces $KV_i$ and $KV_j$ , which are the sets of key values that correspond to the distinct hashes of each view. At this point, the intersection of these two sets, $K\_intersect$, corresponds to the contradictory examples (\autoref{4c_contra_compl:k_intersect}--\autoref{4c_contra_compl:find_contr}), while the rest of values, $K\_compl$, correspond to the complementary ones (\autoref{4c_contra_compl:k_compl}--\autoref{4c_contra_compl:find_compl}). \zz{this is just based on the current implementation} Two views are only complementary if no contradictions exist. Therefore, each candidate key of a pair of views corresponds either contradictory or complementary relationship. \smallskip Once finished, all views will be classified into the four categories. By applying the \textit{4C} method, we are able to prune a portion of the output views; e.g. we can discard \textit{compatible} views, leaving only one view in each group, and choose the view with the highest cardinality among each group of \textit{contained} views \zz{since ... (need reasons)}. The user still has to choose among the rest of the views. The most naive approach would be letting the user look through all the rest of views and choose their preferred one, but this approach can be very ineffective and tedious for the user since the amount of views left may still be very large and and views can be noisy and spurious. To leverage the \textit{complementary} or \textit{contradictory} relationships we obtained using the \textit{4C} method, we designed a \textit{human-in-the-loop} presentation framework that reduces user's effort and guide them towards their preferred view with minimal amount of interactions by asking them questions strategically. \zz{Add applying S4 ranking to the views here, so we can use the ranking alone without proceeding to the next step. But don't know how to make the transition.} \zz{maybe instead mention S4 ranking in evaluation?} \subsubsection{\textbf{Human-in-the-loop}} We now introduce the human-in-the-loop presentation framework. Intuitively, we can present each pair of complementary or contradictory views with their corresponding candidate keys at each interaction; to help user distinguish between the two views, we can present only the complementary or contradictory rows to highlight the differences between the two views. At every interaction, the user selects between each pair of views, pruning out the view they don't like, and ultimately finds the view they want either by going through every pair until there is no more pair left to present, or stopping early since they already found their preferred view among the views that have been shown to them. However, this method has two limitations: (1) the number of complementary or contradictory view pairs can be enormous, and the user has to go through all the pairs to explore all views at least once; in the worst case, if all output views are either complementary or contradictory to each other, the number of view pairs to present grows exponentially based on the total number of views. (2) since the user may only have limited domain knowledge and they can be uncertain of which view is the exact one they want, they may need more interactions to explore more views and build up confidence as of the views they choose. Thus pruning out views directly can potentially discard views users actually want. \zz{second point needs rephrasing -- just trying to show why we need a scoring model} To tackle theses two limitations, we designed an \textit{uncertainty framework} \zz{better name?} that is able to (1) let user's selections influence more than just a pair of views at each interaction, thus reducing the number of interactions they would need to explore all the views \zz{very subtle here. Although we still have exponential number of pairs, we don't have to go through all of them in order to explore all views. how to phrase it more nicely?}, and (2) assign scores to each view and re-rank them at each interaction instead of pruning out views directly, so user can make a more informed decision of which view they prefer based on the view scores. And most importantly, the \textit{uncertainty framework} presents questions strategically, in a way that reduces\zz{? maybe not use the word minimize without clear definition} the number of interactions user needed in order to find their preferred view. We now formally define the \textit{complementary set} and \textit{contradictory set} that we designed to address the first point from above. \begin{definition}[Complementary set] \zz{?} Two sets of views, $s_1 \subseteq V$ and $s_2 \subseteq V$, form a \textit{complementary set}, if they all share the same candidate key, $K$, and there exists two key values, $k_i \in K_i$ and $k_j \in K_j$ where $k_i \neq k_j$, such that for all the views $v_i \in s_1$, the row $r_1 = k(R_i, k_i)$ is the same; for all the views $v_j \in s_2$, the row $r_2 = k(R_j; k_j)$ is the same. Finally, $k_i \notin K_j, k_j \notin K_i$. That is, $r_1$ and $r_2$ is complementary with each other, and $r_1$ is not contained in any of the views in $s_2$, $r_2$ is not contained in any of the views in $s_1$. \end{definition} \begin{definition}[Contradictory set] \zz{?} Two sets of views, $s_1 \subseteq V$ and $s_2 \subseteq V$, form a \textit{contradictory set}, if they all share the same candidate key, $K$, and there exists a key value, $k$, such that for all the views $v_i \in s_1$, the row $r_1 = k(R_i; k)$ is the same; for all the views $v_j \in s_2$, the row $r_2 = k(R_j; k)$ is the same. Finally, $r_1 \neq r_2$, meaning $r_1$ and $r_2$ is contradictory on the key value $k$, which is present in all the views in both $s_1$ and $s_2$. \end{definition} \begin{algorithm} \SetAlgoLined \SetKwInput{KwInput}{Input} \SetKwInput{KwOutput}{Output} \KwInput{$M$, double-nested map where the first key is the view pair $(v_i, v_j)$ that exist in $C3$ or $C4$, and the second key is its candidate key $k$, the corresponding value is either $(K_i, K_j)$, meaning it is complementary, or $K$, meaning it is contradictory. $sample\_size$, maximum number of contradictory or complementary rows in a signal} \KwOutput{$(S\_compl, S\_contra)$, lists of complementary and contradictory signals consisting of tuple $(k, S_1, S_2, R_1, R_2)$.} \BlankLine \ForEach{$(v_i, v_j)$ in $M$}{ \ForEach{$k$ in $M[(v_i, v_j)]$}{ $(S_1, S_2) \leftarrow (set(), set())$\; $(R_1, R_2) \leftarrow (set(), set())$\; \eIf{$is\_compl(M[(v_i, v_j)][k])$}{ $(K_i, K_j) \leftarrow M[(v_i, v_j)][k]$\; $(SK_i, SK_j) \leftarrow sample(K_i, K_j, sample\_size)$\; \label{generate_signals:sample_compl} \For{$(k_i, k_j) \in (SK_i, SK_j)$}{ $r_1 \leftarrow k(R_i, k_i)$\; $r_2 \leftarrow k(R_j, k_j)$\; $(s_1, s_2) \leftarrow get\_compl\_set(r_1, r_2)$\; \label{generate_signals:get_compl_set} $add(S_1, s_1)$\; \label{generate_signals:combine_compl_start} $add(S_2, s_2)$\; $add(R_1, r_1)$\; $add(R_2, r_2)$\; \label{generate_signals:combine_compl_end} } $add(S\_compl, k, S_1, S_2, R_1, R_2)$\; } { $K \leftarrow M[(v_i, v_j)][k]$\; $SK \leftarrow sample(K, sample\_size)$\; \label{generate_signals:sample_contra} \For{$k_i \in SK$}{ $r_1 \leftarrow k(R_i, k_i)$\; $r_2 \leftarrow k(R_j, k_i)$\; $(s_1, s_2) \leftarrow get\_contra\_set(r_1, r_2)$\; \label{generate_signals:get_contr_set} $add(S_1, s_1)$\; \label{generate_signals:combine_contra_start} $add(S_2, s_2)$\; $add(R_1, r_1)$\; $add(R_2, r_2)$\;\label{generate_signals:combine_contra_end} } $add(S\_contra, k, S_1, S_2, R_1, R_2)$\; } } } \Return $(S\_compl, S\_contra)$\; \caption{generate\_signals} \label{generate_signals} \end{algorithm} For each pair of view, we can then generate \textit{complementary signals} and \textit{contradictory signals} to present through the procedure in \autoref{generate_signals}. \zz{I tried to properly define the signal but don't know how to, instead I just explained it through the algorithm. May still need to define it} Depending on the candidate key of each pair of view, we sample certain number of complementary or contradictory rows (\autoref{generate_signals:sample_compl} and \autoref{generate_signals:sample_contra}), and obtain the corresponding complementary or contradictory set for each sampled row (\autoref{generate_signals:get_compl_set} and \autoref{generate_signals:get_contr_set}). We then combine them together so that each signal contains multiple rows along with the combined complementary or contradictory set (\autoref{generate_signals:combine_compl_start}--\autoref{generate_signals:combine_compl_end} and \autoref{generate_signals:combine_contra_start}--\autoref{generate_signals:combine_contra_end}). \zz{may need to restructure this paragraph} By changing from presenting complementary or contradictory view pairs to complementary or contradictory signals, we allow the user to explore multiple views by examining only a few pair of complementary or contradictory rows. At each interaction, the presentation framework presents a signal, which consists of the candidate key, $k$, two sets of complementary or contradictory rows, $R_1$ and $R_2$, that correspond to $k$, and their respective combined complementary or contradictory set, $S_1$ and $S_2$. Thus the signal presents two options, $R_1$ and $R_2$. The user chooses which set of rows they prefer; depending on their choice, the presentation framework increments the scores of views in the corresponding complementary or contradictory set. Optionally, the user can choose to select neither options, and in this case all views that are present in both sets will be decremented \zz{reason?}. In addition to updating view scores, the presentation framework also maintains a scoring model for all candidate keys across different signals. It increments the score of the current candidate key if the user selects an option since their action implies the candidate key and the complementary or contradictory values it yields are good enough for the user to make a decision; otherwise, if the user does not select any option, it decrements its score. The candidate key scores are used to determine the subset of signals the framework will consider; at each interaction, it will consider the signals with the candidate key that has the highest score. Choosing the best candidate key can help preventing presenting signals with schema (list of attributes) that the user prefer less, and instead present signals with associated complementary or contradictory relationships that the user agrees on. \mypar{Uncertainty framework} One crucial aspect of the presentation framework is about picking which signal signal to present at each interaction. As our goal is to reduce user's effort of finding their preferred view, we should prioritize presenting signals that delivers more information about the output views and helps the user converge on the view they prefer the most in fewer amount of interactions. We first define the \textit{score threshold} and the \textit{information gain} of a signal as follows: \begin{definition}[score threshold] Given a percentile, $p$, the score threshold is the $p$-th percentile of the current scores of all views in the scoring model. \end{definition} \begin{definition}[Information gain of a signal] The information gain of a signal describes the expected \textit{uncertainty removed}; that is, the expected number of views we are able to update with new information. Given a score threshold, $\tau$, we first obtain the new sets of views, $NS_1$ and $NS_2$, which are the subset of views in $S_1$ and $S_2$ of the signal with scores greater than $\tau$. Then, we quantify the information gain of a signal as : \[ G = N - \sum_i p_i \cdot n_i \] where $N$ is the total number of views in $NS_1$ and $NS_2$, $p_i$ is the probability of updating the views in $NS_i$ \zz{this is really just $n_i/N$}, and $n_i$ is the number of views in $NS_i$. \end{definition} \begin{algorithm} \SetAlgoLined \SetKwInput{KwInput}{Input} \SetKwInput{KwOutput}{Output} \KwInput{$V$, collection of output views. $sample\_size$, maximum number of contradictory or complementary rows in a signal. $p$, percentile for computing score threshold $\tau$.} \KwOutput{$view\_scores$, list of tuples $(v_i, score_i)$, $v_i$ is the output view $v_i \in V$, and $score_i$ is the final score of $v_i$ of the last interaction} \BlankLine $G \leftarrow main\_4c(V)$\; \tcc{discard compatible views, leaving only one view in each group} $prune\_compatible\_views(G)$\; \tcc{keep the view with the highest cardinality among each group of contained views} $prune\_contained\_views(G)$\; \tcc{transform the pruned 4C views into the map $M$ which is the input to $generate\_signals$} $M \leftarrow transform(G)$\; $(S\_compl, S\_contra) \leftarrow generate\_signals(M, sample\_size)$\; $view\_scores \leftarrow initialize\_view\_scores()$\; $key\_scores \leftarrow initialize\_key\_scores()$\; \While{user continues interacting}{ $k \leftarrow get\_best\_key(key\_scores)$\; $\tau \leftarrow compute\_threshold(view\_scores, p)$\; $signal \leftarrow pick\_next\_signal(S\_compl, S\_contra, k, \tau)$\; $(k, S_1, S_2, R_1, R_2) \leftarrow signal$\; \eIf{$is\_contradictory(signal)$}{ $present\_complementary\_signal(k, S_1, S_2, R_1, R_2)$\; $pop(S\_compl, signal)$\; } { $present\_contradictory\_signal(k, S_1, S_2, R_1, R_2)$\; $pop(S\_contra, signal)$\; } $selection \leftarrow get\_user\_response()$\; \eIf{$selection \neq \emptyset$}{ \tcc{increment the scores of views in the set that corresponds to user's selection} $increment\_view\_scores(view\_scores, selection)$\; $increment\_key\_scores(key\_scores, k)$\; }{ \tcc{decrement the scores of all views in $S_1$ and $S_2$} $decrement\_view\_scores(view\_scores, S_1, S_2)$\; $decrement\_key\_scores(key\_scores, k)$\; } } \Return $view\_scores$\; \caption{View Presentation} \label{view_presentation} \end{algorithm} Consequently, at every interaction, the presentation framework computes the current score threshold, $\tau$, and picks the signal that has the highest information gain with respect to $\tau$ among the subset of signals with the candidate key that has the highest score. By considering views that have scores above the threshold when computing the information gain, the presentation framework is able to pick the most informative signal that allows the user to explore more views among the subset of views which they have a stronger preference on. The overall algorithm of the presentation framework is outlined in \autoref{view_presentation} \zz{there isn't any need to go over the algorithm line by line?}. The interaction model continues until the user is satisfied with their selections and decides to settle with the current view scores. They may decide to pick the view with the highest score as their final view, or they can choose among the $top-k$ views. \smallskip By dividing the end-to-end pipeline into three inter-connecting stages: view specification, view search and view presentation, DoD is able to navigate the user through different stages and find their preferred views efficiently and effectively. \section{Introduction} At the beginning of many data management tasks, there is a dataset produced by a Project-Join query over a collection of tables that may originate from the combination of disparate databases~\cite{dataintegration}, from data lakes~\cite{datalake}, open data portals~\cite{opendata}, and cloud repositories~\cite{lakehouse} or any combination of the above. These datasets, henceforth called Project-Join views (PJ-views), may be the training dataset that machine learning engineers need to train a new model, or the dataset that citizen journalists want to find in open data repositories to answer a question of interest, or the combination of tables from different databases a data analyst wants to feed into a business intelligence tool to build a new dashboard for the organization. Discovering the right PJ-view is crucial to the performance of these tasks, but hard for two reasons: i) large data volumes make it difficult to determine which tables are relevant; ii) these collections of tables are \emph{pathless}, i.e.,\ lack join paths, so it is hard to combine tables with each other. Query-by-example (QBE) approaches identify PJ-views over tables without requiring schema knowledge to produce the examples. But QBE systems are designed for scenarios where the underlying join paths are known, and they do not work well over pathless table collections. Many data discovery approaches are designed to find relevant data in pathless table collections. Systems and approaches such as Aurum~\cite{aurum}, Goods~\cite{halevy2016goods}, Auctus~\cite{auctus}, Juneau~\cite{zhang2019juneau}, Josie~\cite{zhu2019josie}, Table-Union~\cite{tableUnionSearch}, D3L~\cite{d3l} and libraries such as LSHEnsemble~\cite{zhu2016lsh}, Lazo~\cite{fernandez2019lazo} and others help with identifying data that satisfies some relevance criteria. However, none of these approaches implement a QBE interface, which has been shown to be useful to navigate collections of tables when the schema is not known to the users~\cite{zloof1975query, qbo}. In summary, QBE systems help when the schema is not known to the users but the system knows the correct join paths. Data discovery approaches help navigate pathless table collections but do not provide a QBE interface. Discovering a relevant PJ-view over pathless table collections requires solving a \emph{human} problem and a \emph{technical} problem. Solving the human problem involves understanding what users need, and assisting them in taming ambiguity in the results, e.g.,\ selecting between `\emph{work address}' and `\emph{home address}'. We do not address the human problem in this paper. The technical problem consists of retrieving relevant data among the many existing tables, identifying strategies to combine those tables into PJ-views, and sort through the candidates to reduce the number of candidate PJ-views. In this paper, we introduce a reference architecture to discover PJ-views over pathless table collections using user-provided examples (PPE). The architecture divides the problem into components geared towards addressing the human problem, and components to address the technical problem. The explicit separation divides the problem into smaller challenges for which we can engineer new solutions and adapt existing ones. Our main contribution is an engine, \textbf{Niffler}, that implements the components necessary to deal with the technical challenge. Niffler is the first QBE system specifically designed to work over pathless table collections. Niffler implements four components. First, it uses a discovery system to find approximate paths in pathless table collections. Paths are approximate because we cannot identify correct join paths without human intervention and the scale of the problem makes human intervention too expensive. Second, the engine performs efficient column selection, identifying a set of candidate tables relevant to the input query. Third, it identifies strategies to combine the candidate tables together based on the approximate join paths, a process that may lead to many candidate PJ-views because some join paths will be unavoidably wrong and, even if correct, they may not fit the user's relevance criteria. The engine alone cannot determine which PJ-views used a correct join path and match the user's relevance criteria, so instead of choosing, it produces all of them. To help navigate the candidate PJ-views (fourth), Niffler implements a \textsc{signal-generation} component that post-processes the views according to a 4C (\emph{compatible}, \emph{contained}, \emph{complementary}, \emph{contradictory}) classification that helps reduce the size of the candidate PJ-views, hence facilitating the job of downstream consumers. In summary, the contributions of our paper are as follows. We discuss four challenges of the PPE problem that prevent prior QBE strategies to identify the relevant PJ-view (Section~\ref{sec:background}). We propose a reference architecture to \emph{divide-and-conquer} the challenges, providing the flexibility to plug-in prior techniques for each sub-problem (Section~\ref{sec:architecture}). We describe Niffler, a scalable engine implementation to solve the technical component of the problem (Section~\ref{sec:engine}). A \emph{non-goal of our paper} is to address the human problem. Our experimental results (Section~\ref{sec:evaluation}) demonstrate the new reference architecture tackles much larger problems than other QBE techniques over pathless table collections. \subsection{Microbenchmarks} \label{subsec:microbenchmarks} In this section, we investigate the effect of varying the inputs to our system. First, the effect of varying the quality of the inferred schema. Next, the effect of varying the number of rows and columns provided in the input queries. \subsubsection{\textbf{Varying Discovery Index Quality}} The quality of the discovery indexes built by the Discovery Index Construction component has an effect on the set of candidate PJ-views generated by Niffler (\textbf{Challenge 2}). We study its effect by modifying the default threshold Aurum uses to compute the hypergraph. In particular, we use thresholds 0.8 (the default), 0.7, 0.6, and 0.5. These thresholds lead to 435, 582, 2143, and 2947 joinable column pairs, respectively. As the thresholds lower, the schema quality worsens, leading to more spurious join paths. These configurations evaluate the effect of schema quality on the discovery of PJ-views over pathless table collections, i.e.,\ \textbf{Challenge 2}. As expected, \mbox{Fig.\hspace{0.25em}}~\ref{fig:diff_threshold} shows that the number of join graphs increase as the schema quality worsens. As shown in the previous section, this leads to a higher number of join graphs, and consequently, higher runtimes. \begin{figure}[!ht] \centering \includegraphics[width=0.85\linewidth]{figures/end_to_end/diff_thresholds.pdf} \caption{Number of join graphs under different $t$ on ChEMBL. Aurum produces 435 (0.8), 582 (0.7), 2143 (0.6), and 2947 (0.5) joinable column pairs.} \label{fig:diff_threshold} \end{figure} \mypar{Conclusion} When no join path information is available in the schema, inferring the join paths automatically leads to noisy and incorrect ones, which in turn, has an effect on the scalability of the problem (\textbf{Challenge 2}). In conclusion, i) discovering PJ-views on pathless table collections is strictly more difficult than on settings with perfect schemas and; ii) investment in better join path discovery algorithms would highly benefit this problem as well. \subsubsection{\textbf{Vary the number of Rows}} In this experiment, we increase the number of rows inside one query view and observe its effect on the number of candidate groups, join graphs and views (i.e. the search space). As shown in \mbox{Fig.\hspace{0.25em}}~\ref{fig:diff_sample_size}, the relationship between the number of rows and the search space is not monotonous. Increasing the number of rows in a query view can cause the search space to shrink or grow. This is because there are two factors affecting the search space conversely when the number of rows in a query increases. \begin{figure} \centering \includegraphics[width=\linewidth]{figures/end_to_end/diff_sample_size.pdf} \caption{Number of candidate group, join graphs, generated views of different sample size queries} \label{fig:diff_sample_size} \end{figure} \mypar{Enlarge the search space} \mbox{Fig.\hspace{0.25em}}~\ref{fig:diff_sample_info} shows that the total number of columns before clustering increase as the number of rows increase and the number of clusters will increase as well. \mypar{Shrink the search space} \mbox{Fig.\hspace{0.25em}}~\ref{fig:diff_sample_info} indicates that the number of clusters that \textsc{column-selection} selects will decrease as the number of examples increases. This is because the score of the ground truth column and its corresponding cluster increases. \begin{figure} \centering \includegraphics[width=\linewidth]{figures/end_to_end/diff_sample_info.pdf} \caption{Number of columns, clusters, selected clusters and selected columns of different sample size queries} \label{fig:diff_sample_info} \end{figure} \mypar{Conclusion} Intuitively, more rows should lead to fewer candidate PJ-views at the end, and previous work has demonstrated this when schemas are well-formed. But in pathless table collections this is not the case as demonstrated here. \subsubsection{\textbf{Vary the number of Columns}} We study the effect of increasing the number of columns in the input query. We choose query with 2, 3 and 4 columns on ChemBL. Unlike varying the number of rows, the results of this experiment are intuitive: higher number of columns in the input lead to higher number of join graphs, candidate PJ-views, and runtime. \section{Engine Implementation} \label{sec:engine} In this section, we introduce Niffler\xspace, which we use to make the reference architecture precise and evaluate it later. Thus, in implementing Niffler\xspace, we reuse components and techniques from the literature when possible and explain novel design and implementation decisions when relevant. \subsection{Discovery Index Construction} This component identifies approximate join paths on pathless table collections, and through a \textsc{Discovery Engine} (see \mbox{Fig.\hspace{0.25em}}\ref{fig:architecture}) retrieves data that satisfies a query filter. In this paper, we use Aurum~\cite{aurum}, which we briefly introduce here for completeness. During an offline stage, Aurum reads each $D\in \mathcal{D}$ and produces a \emph{profile} for each column in $D$. The profile includes common statistics as well as sketches, constructed specifically to identify relationships between columns and tables. After reading the data once, Aurum produces a full-text search index over attributes and data values, and a hypergraph. In the hypergraph, nodes represent columns, hyperedges represent columns of the same table. Edges are directed and weighted. Each relationship is represented with a different edge type. The hypergraph is constructed efficiently (e.g.,\ no all-pairs comparison are involved) using LSH-based indexes for the relationships of interest, which in this paper are \emph{content-similarity}, and \emph{inclusion-dependency}~\cite{fernandez2019lazo}. The \textsc{Discovery Engine} provides the following primitives: \mypar{\textsc{Search-Keyword(target, fuzzy)}} Given an input string, it returns columns that contain the string in either the attribute name, or in the values, as specified by \textsc{target}. The match can be exact or fuzzy, after specifying a maximum Levenshtein distance. \mypar{\textsc{Neighbors(threshold)}} Given an input column, it returns all neighbors with a Jaccard containment above the input \textsc{threshold}. \mypar{\textsc{Generate-Join-Paths}} Given two tables, $t1$, $t2$ as input, it returns all paths connecting any column in $t1$ with any column in $t2$, via inclusion dependencies. Paths have a maximum number of hops, $\theta$. \subsection{Column Selection} Given a column of example values as input ($\chi.A_i$), this component generates a small set of columns $\textsc{Cand}(A_i)$ that contain these values. Our implementation supports textual and categorical columns. Many QBE systems~\cite{squid,duoquest} follow the strict assumption that only the columns containing all example values are considered as candidates for subsequent stages of the pipeline (\textit{exact containment}). However, the noisy QBE-style query may not contain all values from the ground truth PJ-view (Challenge 1), thereby affecting its ability to identify adequate PJ-views. In contrast, a relaxed approach to construct $\textsc{Cand}(A_i)$ is to enumerate all columns that have a non-empty overlap with the input examples (\textit{non-empty containment}). This approach ensures that the ground truth view is always present in $\textsc{Cand}(A_i)$ but is highly inefficient when a token is present in several tables. Our \textsc{column-selection} algorithm provides the flexibility to vary the strictness of the assumption by grouping columns identified by relaxed methodology and selecting the top $\theta$ (an input parameter) clusters for the subsequent components. Varying the value of $\theta$ simulates varying degrees of strictness. For example, $\theta=1$ is equivalent to considering the cluster that contains the column having maximum overlap with the input example whereas $\theta=\infty$ considers all columns that have non-empty overlap with the input examples. The identified clusters help to summarize the set of candidate columns $\textsc{Cand}$ and prioritize the clusters in non-increasing overlap with input examples. Through clustering similar columns and selecting relevant columns based on clusters, our \textsc{column-selection} is more error-tolerant than methods based on \textit{exact containment} and more efficient than methods based on \textit{non-empty containment}. Algorithm~\ref{algo_column_retrieval} presents the pseudo-code of our \textsc{column-selection} algorithm. As a first step, it identifies all columns that have a non-empty overlap with the input examples (lines~\ref{crline2}-\ref{crline4}). These columns are then clustered by identifying connected components over the hypergraph constructed by the \textsc{discovery engine} (line~\ref{crline5}). To identify the connected components, it uses the \textsc{Neighbors} subroutine, exposed by the discovery index. Each cluster is then assigned a score, which is equal to the maximum number of examples contained in any column in the cluster (line~\ref{crline7}). This stage supports both \textit{automatic mode} and \textit{interactive mode}. In the \textit{automatic mode}, top-$\theta$ clusters are selected based on their scores (line~\ref{crline8}). \mypar{Rationale} Isolating this component in the architecture has two advantages: i) it detects ill-specified queries that lead to too many retrieved columns and that would place the burden on the engine without helping users; ii) it offers a point of interaction with \textsc{view-specification} to help users select the right column clusters. Identifying interactive policies to present clusters is outside the scope of this work; we focus on providing the mechanism. \IncMargin{1em} \begin{algorithm}\SetKwFunction{Union}{Union} \SetKwInOut{Input}{Input}\SetKwInOut{Output}{Output} \Input{Example value set $\chi.A_i$ for a column $A_i$, Discovery Index $I$, Clustering threshold $\theta$ } \Output{$\mathcal{C}(A_i)$ Candidate columns and scores.} \BlankLine $\textsc{Cand}(A_i) \leftarrow \phi$ \tcc*[f]{\small Initialize candidates}\\ \For{ $e\in \chi.A_i$ \label{crline2}} { $\textsc{Cand}(e) \leftarrow \textsc{Search-Keyword}(e)$\\ $\textsc{Cand}(A_i) \leftarrow \textsc{Cand}(A_i) \cup \textsc{Cand}(e)$\label{crline4} } $ \mathcal{C} \leftarrow \textsc{Connected-Component}(\textsc{Cand}(A_i), I)$\label{crline5}\\ \For{ $Cluster\in \mathcal{C}$ }{ $\textsc{Score}(Cluster) = \max_{col\in Cluster} (col \cap \chi.A_i) \label{crline7} $ \tcc*[f]{\small Score each cluster based on overlap with input examples}\\ } $\mathcal{C}'\leftarrow$ top-$\theta$ clusters in $\mathcal{C}$ based on $\textsc{Score}$\label{crline8}\\ $\textsc{Cand}(A_i) \leftarrow \bigcup_{T\in \mathcal{C}'} T$\\%\tcc*[f]{\small Combine all columns in top-$\theta$ clusters}\\ \Return $\textsc{Cand}(A_i)$ \caption{\textsc{Column-Selection}} \label{algo_column_retrieval} \end{algorithm} \subsection{Join Graph Search and Materializer} Our \textsc{join-graph-search-and-materializer} component joins the tables identified in the \textsc{column-selection} stage to construct candidate PJ-views. Algorithm~\ref{algo_view_search} presents the pseudo-code of our join graph enumeration algorithm. It operates in two steps. First, \textbf{ Join Path enumeration} (lines~\ref{vsline1}-\ref{vsline10}) enumerates all tables returned by \textsc{column-selection} and identifies joinable groups of tables. In the second step, the \textbf{Ranking and Materialization} (lines~\ref{vsline11}-\ref{vsline12}) component ranks these join paths based on their quality estimated by the \textsc{discovery engine} and materializes top-k join paths. \noindent1)Join Path enumeration enumerates all possible combinations of the columns returned by \textsc{column-selection}. These candidates are then processed to iteratively remove the combination which can not be constructed by joining tables through the constructed index. Note that if columns $c_i$ and $c_j$ can not join then any combination of columns involving $c_i$ and $c_j$ can not be joined. This phase uses this optimization along with a cache to efficiently prune out incorrect combinations. \noindent2) Ranking and Materialization ranks the join graphs based on the join score generated by the \textsc{discovery engine} and then materializes the top-$\gamma$ views. The intuition of the scoring model in \textsc{discovery engine} is that a good join graph needs to have join keys that are more likely to be PK/FK and involves fewer tables. Our \textsc{discovery engine} collects data of these two criteria and assigns a score to each join graph. Note that our ranking strategy is efficient since it can be calculated without materializing the views. Given the ranking information, we can materialize the top-$\gamma$ views. Besides, we also support materializing join graphs in \textit{batch} mode. Through avoiding materializing all the views at once, we alleviate the scalability issue when the number of join graphs is large. The materializer is built on top of Pandas~\cite{pandas} and could use an embedded database~\cite{sqlite, duckdb} or a processing engine with the \emph{external table} feature~\cite{redshiftexternal} to achieve better performance. \begin{algorithm} \SetKwFunction{AllCombinationOf}{AllCombinationOf} \SetKwInOut{Input}{Input}\SetKwInOut{Output}{Output} \Input{QBE-style query $\chi$, candidate columns $\textsc{Cand}$, expected number of output views $\gamma$ } \Output{$\mathcal{V}_{PJ}$: list of candidate PJ-views} \tcc*[h]{Step 1: Join Path enumeration}\\ $\tau\leftarrow |\textsc{Columns}(\chi)|$\label{vsline1}\\%\tcc*[f]{Number of columns in input examples} $\Gamma\leftarrow \{(c_1,\ldots, c_\tau): \forall c_i\in \textsc{Cand}(A_i)\}$ \\%\tcc*[f]{Construct all combinations of columns} \\%\zz{reviewer3 D4: I'm not sure I get the notation in Line 2 of Algorithm 3, is that correct?}\\ $\Gamma_{join}\leftarrow \phi$\\ \For{ $r\equiv (c_1,\ldots, c_\tau) \in \Gamma$} { $P\leftarrow \textsc{Generate-Join-Paths}(r,2)$\\%\tcc*[f]{Generate 2-hop join paths between column pairs}\\ \If{$\exists c_i,c_j \in r \mid P(c_i,c_j) = \phi$}{ Remove all candidates $r\in \Gamma$ containing columns $c_i$ and $c_j$ such that $P(c_i,c_j)=\phi$ \\%\tcc*[f]{Prune out combinations that do not have a join path}\\ Continue\\ }\Else{ $\Gamma_{join}\leftarrow \Gamma_{join} \cup P$\label{vsline10} } } \tcc*[h]{Step 2: Ranking and Materialization}\\ $\Gamma_{join}'\leftarrow $ Select top $\gamma$ join candidates based on join score generated by the discovery engine.\label{vsline11}\\ $\mathcal{V}_{PJ}\leftarrow \textsc{materialize-views}(\Gamma_{join}')$\label{vsline12}\\ \Return $\mathcal{V}_{PJ}$ \caption{\textsc{Join-Graph-Search}} \label{algo_view_search} \end{algorithm} \subsection{Signal Generation} The goal of the \textsc{signal-generation} component is to collect and generate \emph{signals} that help \textsc{view-presentation} choose the right candidate PJ-view. Collected signals include column headers, source of constituent tables, join paths, and their similarity with input examples. In addition, the \textsc{signal-generation} component generates a class of novel signals, called \textit{4C}, that help reduce the size of the candidate PJ-views. \mypar{4C Signals} The 4C signals first classify the output views with the same schema into four categories: \textit{Compatible}, which means that views are identical; \textit{Contained}, which means that the values of one view subsume others; \textit{Complementary}, which means that the set difference of tuples of views is not empty; and \textit{Contradictory}, which means that tuples from different tables with same key disagree on at least one of their attributes' values. Depending on the chosen key, two views may be \emph{complementary} or \emph{contradictory}. We consider all columns that uniquely define rows as candidate keys for a view. To define these signals, we refer to a view $V_i$ as a set of tuples in the dataset with $k(V_i)$ denoting the set of values corresponding to its candidate key. \begin{definition}[Candidate key] A candidate key, $k$, is a set of attributes in an output view, $V_i$, that can uniquely identify each row in $R_i$. We can refer to a row, $r_i \in R_i$, with its candidate key value, $k_i$, which we can use to obtain the row; $k(R_i, k_i) = r_i$. There can be multiple candidate keys in $V_i$ that satisfy this property. \end{definition} \begin{definition}[Compatible views] Two candidate views, $V_1$ and $V_2$, are compatible if they have the same set of tuples $(V_1 \cap V_2) = V_1=V_2$. \end{definition} \begin{definition}[Contained views] A view, $V_1$, contains another view, $V_2$, when $V_2\subseteq V_1$, that is, when all rows of $V_2$ are contained in $V_1$. \end{definition} \begin{definition}[Complementary views] Two views, $V_1$ and $V_2$ are complementary if the two views have the same candidate key, $k$, and $|(K_1 \setminus K_2)| > 0$ and $|(K_2 \setminus K_1)| > 0$, where $K_1$ and $K_2$ are the set of candidate key values for $V_1$ and $V_2$ respectively. That is, each view has candidate key values not contained in the other view. \end{definition} \begin{definition}[Contradictory views] Two views, $V_1$ and $V_2$ are contradictory if the two views have the same candidate key, $k$, and a key value that exists in both views, $k_i \in K_1, K_2$, yields distinct rows, $k(V_1; k_i) \neq k(V_2; k_i)$. Two rows are distinct when any value of any of their attributes is different. \end{definition} Using this formalism, our \textit{4C} classification algorithm iteratively partitions pairs of candidate views into the four categories. To avoid cell-level comparison of values and efficient comparison of views, we construct a hash for each row. Since the contradictory views are inherently discriminative, we construct \textit{contradictory signals} from the contradictory views by leveraging the \textit{transitive} relationships of contradictory rows among those views. For each pair of contradictory views, we generate \textit{contradictory signals} consisting of rows with contradictory values and their respective \textit{contradictory sets}. For example, suppose the candidate PJ-views have the attributes \textit{name} and \textit{address}, where \textit{name} is a valid candidate key. A contradictory signal may contain two contradictory rows corresponding to one candidate key value \textit{Alice}, one has Alice's work address, while the other has Alice's home address. Then, all candidate PJ-views that share the same candidate key, \textit{name}, will be grouped into two contradictory sets consisting of PJ-views that contain the row with Alice's work address and Alice's home address respectively. A contradictory signal includes one or multiple contradictory rows, which are sampled from pairs of contradictory views. Using this approach, each contradictory signal can involve many views on each side, thus further reduce the view choice space. \mypar{Using 4C signals to reduce candidate PJ-view space}\label{subsec:chosenstrategy} We explain how to use the 4C signals to reduce the size of the candidate PJ-view space. Compatible views are summarized into one. When there is a group of contained views, the view with the largest cardinality pervades. When views are complementary, they are unioned. Finally, it is not possible to make an automated decision for contradictory views. Contradictory views usually arise for two reasons: i) view was produced using a wrong join path; ii) the original data is contradictory, i.e.,\ due to semantic ambiguity. A user may be able to tell apart the right view, thus selecting a join path \emph{a posteriori}. Without a user, we cannot automatically make a decision on which contradictory value in each contradictory signal is correct, but it is possible to determine if the signal is useful or not, based on how discriminative it is, and consequently decide whether to send it downstream or not---with the intention of avoiding sending non-discriminatory and hence useless signals. Contradictory signals can be sorted according to their degree of discrimination, which is defined as the expected number of views in a contradictory set it would prune after a selection of its respective contradictory rows is made. \section{Related Work} \label{sec:relatedwork} \mypar{Reference architectures in data management} Reference architectures help conceptualize problems and have been influential in advancing the field. For example, \cite{rdbms} for disk-based relational databases and \cite{inmemoryrdbms} for in-memory databases. In data integration problems, the OpenII system~\cite{openii}, the Orchestra system~\cite{orchestra}, Data Civilizer~\cite{datacivilizer} and Big Gorilla~\cite{biggorilla} have presented architectures as well. We believe that presenting architectures let other researchers criticize and improve components for the ever-changing challenges of discovery and integration problems in data management. \mypar{Data Lake Exploration} Several lines of work complement our reference architecture for the exploration of pathless table collection. Many of these works refer to the problem as 'data lake exploration'. For example, work on identifying data transformations can help with increasing the joinability of tables~\cite{transform1, transform2, transform3}. Improvements to discovery engines~\cite{aurum, d3l, zhang2019juneau, tableUnionSearch}, and key detection approaches~\cite{key1, key2} help with inferring higher quality schemas. There is a lot of work on designing effective visualizations to assist users in exploring pathless data collections~\cite{hu2019viznet,bikakis2016exploration} and view recommendations~\cite{zhang2019viewseeker,zhang2020interactive}. These techniques can be useful to implement the human components of Niffler\xspace. Table~\ref{tab:components} summarizes some representative techniques. \mypar{QBE and QRE} The table in Section~\ref{sec:background} presents only the most relevant work to Niffler. Table~\ref{tab:components} presents a summary of representative data discovery, QBE, QRE and view presentation systems along with their respective assumptions for the different components. There is more literature on using QBE interfaces, but either they assume a different data format, such as knowledge bases~\cite{kgqbe1}, or their contribution is complementary to our work, such as \emph{exemplar queries} in \cite{exemplar, exemplar2, exemplar3,pimplikar2012answering} that defines a more general notion of queries that query-by-example. \subsection{RQ1: Column Selection and Join Graph Search} \label{subsec:specandsearch} \mypar{Column Selection Baselines} \textsc{Select-All.} This baseline (implemented from \textit{S4}~\cite{s4}) selects any column that contains at least an example from the input query. \textsc{Select-Best} This baseline selects the column that contains the highest number of examples from the input query. This is the selection strategy implemented by \textit{SQuID}~\cite{squid}. Our implementation of this component is labelled \textsc{column-selection}. After running each of these configurations, we feed the candidate columns to the join-graph-search component that finds the candidate join paths, identifies join graphs, and materializes them to produce the set of candidate PJ-views. \begin{figure} \centering \includegraphics[width=0.85\linewidth]{figures/end_to_end/agg_hits.pdf} \caption{Ground truth hit ratio over 150 queries in input workload split by noise level in the input query} \label{fig:agg_hits} \end{figure} \begin{figure} \centering \includegraphics[width=\linewidth]{figures/end_to_end/chembl_plots_in_one.pdf} \caption{Number of candidate groups, join graphs and generated views on ChEMBL} \label{fig:chembl_view_search_info} \end{figure} \mypar{Experiment and Metrics} We obtain the output set of candidate PJ-views for each of the 150 input queries in the workload. We consider two metrics. First, whether the \emph{ground truth view} is part of the candidate PJ-views, i.e.,\ the system finds the required view. In particular, we measure the \emph{Ground Truth Hit Ratio} that determines the ratio of input queries for which the system finds the \emph{ground truth view}. Second, we measure the size of the set of candidate PJ-views. Given two systems that find the \emph{ground truth view}, we prefer the one producing the smaller set of candidate PJ-views. Smaller candidate PJ-views indicate lower runtime (as we will demonstrate later) and more importantly, facilitates the job of the view presentation stage, e.g.,\ consider a human who needs to look at each view in the candidate set to select the right one. \mypar{Results} Figure~\ref{fig:agg_hits} shows the \emph{Ground Truth Hit Ratio} across the 150 queries, for each baseline, and grouped by different input query noise levels in the \textsc{X}-axis. When there is no noise in the input query, that is, when the query perfectly reflects the data in the repository, then all baselines perform well and find the \emph{ground truth view}. As the noise in the input query increases, however, the \textsc{Select-Best} strategy crumbles because of its over-reliance on columns that contain all values in the input query. This result demonstrates that in pathless table collections, when input queries contain noise, the \textsc{Select-Best} strategy is not adequate. \begin{figure} \centering \includegraphics[width=\linewidth]{figures/end_to_end/wdc_plots_in_one.pdf} \caption{Number of candidate groups, join graphs and generated views on WDC} \label{fig:wdc_view_search_info} \end{figure} With both \textsc{Select-All} and \textsc{column-selection} consistently finding the \emph{ground truth view}, the next question is at what cost. \mbox{Fig.\hspace{0.25em}}~\ref{fig:chembl_view_search_info} and \mbox{Fig.\hspace{0.25em}}~\ref{fig:wdc_view_search_info} show results for ChEMBL and WDC respectively. Each $3\times 3$ grid shows the size of the set of candidate PJ-views at the top for the three noise levels. The results clearly indicate that for all queries across both datasets and noise levels, the set of the candidate PJ-views is always significantly larger in the case of \textsc{Select-All} than in the case of \textsc{column-selection}. Since both baselines find the \emph{ground truth view}, the smaller sets are preferred. The \textsc{Select-All} retrieval strategy selects many columns and produces much larger candidate groups than necessary (see \textit{No. of Candidate Groups} in \mbox{Fig.\hspace{0.25em}}~\ref{fig:chembl_view_search_info} and \mbox{Fig.\hspace{0.25em}}~\ref{fig:wdc_view_search_info}). Larger candidate groups, in turn, lead to a larger number of join paths--sometimes up to $4\times$ more, see \textit{No. of Join Graphs} in \mbox{Fig.\hspace{0.25em}}~\ref{fig:chembl_view_search_info} and \mbox{Fig.\hspace{0.25em}}~\ref{fig:wdc_view_search_info})--which results in more candidate PJ-views. \begin{figure} \centering \includegraphics[width=\linewidth]{figures/end_to_end/vs_run_time.pdf} \caption{Run time of \textsc{column-selection} + \textsc{join-graph-search-materialize on ChEMBL and WDC}} \label{fig:vs_run_time} \end{figure} \mbox{Fig.\hspace{0.25em}}\ref{fig:vs_run_time} shows that larger sets of candidate PJ-views leads to higher runtime. The runtime of \textsc{column-selection} + \textsc{join-graph-search} is an order of magnitude lower than the \textsc{Select-All} strategy. \mypar{Conclusion} \textsc{Select-Best} is not robust to input query noise, which is expected in pathless table collections where users will not have full knowledge of the data they need. Both \textsc{Select-All} and \textsc{column-selection} are robust to noisy input queries (addressing \textbf{Challenge 1}), but Niffler produces a smaller candidate set of PJ-views and is much faster than the other baseline, addressing \textbf{Challenge 3}. \subsection{RQ2: Effect of Pathless Schema Quality} \label{schema-quality} \subsection{RQ2: Signal Generator} \label{subsec:presentation} In this section, we evaluate the ability of the 4C-signals to reduce the size of the set of candidate PJ-views after using the strategy offered in Section~\ref{subsec:chosenstrategy}. The ability depends on data characteristics. Along with the quantitative results, we offer examples to illustrate the insights brought by the signals. \begin{table}[] \centering \begin{center} {\centering \begin{tabular}{|c|c|c|c|c|c|c|} \hline Query & \begin{tabular}[c]{@{}l@{}}Noise\\ level\end{tabular} & Original & $C_1$ & $C_2$ & \begin{tabular}[c]{@{}l@{}}$C_3$\\ worst\\ case\end{tabular} & \begin{tabular}[c]{@{}l@{}}$C_3$\\ best\\ case\end{tabular} \\ \hline \multirow{3}{*}{\begin{tabular}[c]{@{}c@{}}ChEMBL\\ Q1\end{tabular}} & Zero & {\ApplyGradient{38}}&\ApplyGradient{36} & \ApplyGradient{36} & \ApplyGradient{13} & \ApplyGradient{7} \\ \cline{2-7} & Mid & \ApplyGradient{20} & \ApplyGradient{18} & \ApplyGradient{18} & \ApplyGradient{5} & \ApplyGradient{1} \\ \cline{2-7} & High & \ApplyGradient{33} & \ApplyGradient{31} & \ApplyGradient{31} & \ApplyGradient{9} & \ApplyGradient{3} \\ \hline \multirow{3}{*}{\begin{tabular}[c]{@{}c@{}}ChEMBL\\ Q2\end{tabular}} & Zero & \ApplyGradient{59} & \ApplyGradient{58} & \ApplyGradient{54} & \ApplyGradient{25} & \ApplyGradient{7} \\ \cline{2-7} & Mid & \ApplyGradient{32} & \ApplyGradient{32} & \ApplyGradient{30} & \ApplyGradient{16} & \ApplyGradient{3} \\ \cline{2-7} & High & \ApplyGradient{41} & \ApplyGradient{38} & \ApplyGradient{35} & \ApplyGradient{17} & \ApplyGradient{3} \\ \hline \multirow{3}{*}{\begin{tabular}[c]{@{}c@{}}ChEMBL\\ Q3\end{tabular}} & Zero & \ApplyGradient{58} & \ApplyGradient{33} & \ApplyGradient{29} & \ApplyGradient{16} & \ApplyGradient{4} \\ \cline{2-7} & Mid & \ApplyGradient{44} & \ApplyGradient{21} & \ApplyGradient{17} & \ApplyGradient{8} & \ApplyGradient{3} \\ \cline{2-7} & High & \ApplyGradient{44} & \ApplyGradient{21} & \ApplyGradient{17} & \ApplyGradient{8} & \ApplyGradient{3} \\ \hline \multirow{3}{*}{\begin{tabular}[c]{@{}c@{}}ChEMBL\\ Q4\end{tabular}} & Zero & \ApplyGradient{23} & \ApplyGradient{17} & \ApplyGradient{14} & \ApplyGradient{13} & \ApplyGradient{7} \\ \cline{2-7} & Mid & \ApplyGradient{83} & \ApplyGradient{74} & \ApplyGradient{69} & \ApplyGradient{41} & \ApplyGradient{8} \\ \cline{2-7} & High & \ApplyGradient{83} & \ApplyGradient{74} & \ApplyGradient{69} & \ApplyGradient{41} & \ApplyGradient{8} \\ \hline \multirow{3}{*}{\begin{tabular}[c]{@{}c@{}}ChEMBL\\ Q5\end{tabular}} & Zero & \ApplyGradient{24} & \ApplyGradient{18} & \ApplyGradient{15} & \ApplyGradient{14} & \ApplyGradient{8} \\ \cline{2-7} & Mid & \ApplyGradient{64} & \ApplyGradient{57} & \ApplyGradient{52} & \ApplyGradient{28} & \ApplyGradient{8} \\ \cline{2-7} & High & \ApplyGradient{33} & \ApplyGradient{23} & \ApplyGradient{20} & \ApplyGradient{19} & \ApplyGradient{13} \\ \hline \multirow{3}{*}{\begin{tabular}[c]{@{}c@{}}WDC\\ Q2\end{tabular}} & Zero & \ApplyGradient{44} & \ApplyGradient{39} & \ApplyGradient{25} & \ApplyGradient{8} & \ApplyGradient{4} \\ \cline{2-7} & Mid & \ApplyGradient{42} & \ApplyGradient{37} & \ApplyGradient{23} & \ApplyGradient{5} & \ApplyGradient{3} \\ \cline{2-7} & High & \ApplyGradient{39} & \ApplyGradient{34} & \ApplyGradient{20} & \ApplyGradient{6} & \ApplyGradient{5} \\ \hline \multirow{2}{*}{\begin{tabular}[c]{@{}c@{}}WDC\\ Q3\end{tabular}} & Zero & \ApplyGradient{20} & \ApplyGradient{20} & \ApplyGradient{20} & \ApplyGradient{20} & \ApplyGradient{1} \\ \cline{2-7} & Mid & \ApplyGradient{15} & \ApplyGradient{15} & \ApplyGradient{15} & \ApplyGradient{15} & \ApplyGradient{1} \\ \hline \end{tabular} } \end{center} \caption{Original number of views, followed by number of views left after pruning compatible views, contained views, and union complementary views in the worst case and best case. We excluded queries that have less than 10 original number of views.} \label{tab:num_views_left} \end{table} \subsubsection{\textbf{Compatible and Contained (C1 and C2)}} Each group of compatible views is reduced to a single view. When views are contained, we keep the larger one. The $C_1$ and $C_2$ columns in Table~\ref{tab:num_views_left} show the number of views left after pruning compatible views and contained views. \mypar{Insights of C1} Approximately 50\% of candidate PJ-views in Q3 of ChEMBL are compatible. There are two reasons: 1) compatible views are materialized using the same join tables and join keys, but the two projected columns are in opposite order, and since the two attributes actually represent the same entity, they are projected interchangeably. 2) different but equivalent join keys are used. For example, one pair of compatible views are being materialized using the same join tables: \textit{assays} and \textit{cell\_dictionary}, but one view's join key is \textit{cell\_name} and the other's join key is \textit{cell\_description}; since there is a one-to-one mapping between \textit{cell\_name} and \textit{cell\_description}, the views they produced are identical. \mypar{Insights of C2} Q2 of WDC pruned 14 contained views for each noise level. The majority of the output views in the output share same attributes: \textit{State} and \textit{Newspaper Title}. We found that each pair of contained views are joined using different tables but the same join key, \textit{State}. The join key values of one join path are subsumed by the join key values of other join paths, thus the resulting view is contained in another view. \subsubsection{\textbf{Complementary (C3)}} We union all complementary views. The complementarity of views depends on their key, as explained in Section~\ref{sec:engine}. In this experiment we consider the key that leads to the least reduction (worst case) and the key that leads to the largest reduction (best key). Table~\ref{tab:num_views_left} shows that in the best case, all the queries have many complementary views that can be unioned together, thus dramatically reducing the size of view choice space. In the worst case, all WDC queries, except Q2, do not have complementary views that can be unioned together, since the corresponding candidate key only yields contradictory views; the ChEMBL queries, however, can union a significant portion of complementary views irrespective of the candidate key. \mypar{Insights of C3} The reason WDC Q2 can union many complementary views even in the worst case is that all candidate PJ-views that share the same list of attributes, \textit{State} and \textit{Newspaper Title}, are joined by two tables using the join key \textit{State}; one join table containing the attribute \textit{Newspaper Title} is the same for all the views, while the other containing the attribute \textit{State} is different for each view. The join tables that are different have different coverage of \textit{State} values. Therefore, a lot of candidate PJ-views are complementary based on the candidate key \textit{State} (the worst case). For ChEMBL queries, typically one pair of views does not share their contradictory rows with any other pair of views, so no matter which candidate key we choose, it can always lead to many unionable complementary views since the contradictory relationships are not transitive across views. \subsubsection{\textbf{Contradictory (C4)}} Given a contradictory signal, we do not have an automated way of choosing a view---this is a task that \emph{view presentation} stage would implement. However, we calculate the value of the signals by measuring the worst case and best case reduction in the candidate set size after \emph{signal selection}. We sort signals in descending order according to their degree of discrimination--the number of views that agree with one side of the contradiction. Then, we select the signals sequentially and consider two cases: (a) where the selection leads to the largest reduction of the views (best-case) and (b) where it leads to the least reduction of the views (worst-case). \begin{figure} \centering \includegraphics[width=\linewidth]{figures/presentation/num_views_left.pdf} \caption{Number of views left at each step after pruning views using contradictory signals.} \label{fig:num_views_left} \end{figure} \mbox{Fig.\hspace{0.25em}}~\ref{fig:num_views_left} shows the number of remaining views after each step (for a maximum of 10 steps) for a selection of queries that present discriminative and non-discriminative signals. As expected, when signals are not discriminative, the reduction is limited, such as in mid/high noise queries of ChEMBL Q4 in the worst case. However, there are cases where signals are quite discriminative and the signal proves effective in reducing the set size, such as in the worst case queries of WDC Q3. \mypar{Insights of C4} In ChEMBL the output of Q4 mid/high noise queries contains many candidate PJ-views that are joined by varied join tables and keys. The contradictions in candidate views are mainly due to wrong join paths. For example, one view that is partly joined by the two tables \textit{component\_sequences} and \textit{component\_class} on the shared attribute \textit{component\_id}, while the other view is joined by the two tables \textit{component\_sequences} on attribute \textit{description} and \textit{target\_dictionary} on attribute \textit{pref\_name}, when projecting the final attributes, \textit{organism} and \textit{pref\_name}, these two views have contradictions. \textit{component\_id} is a better join key than \textit{description}. However, as we do not know the join information of the input data, we can only perform join operations using all the attributes that are being considered as valid join keys by the discovery engine. Then we use additional signals, such as the contradictory signals to help distinguish spurious views joined by wrong join keys from the views that are joined correctly. Moreover, since the contradictions in ChEMBL mainly arise due to different join paths, they typically do not share the same contradictions across multiple views. Each contradictory signal only contains two views. Therefore, the maximum number of views we prune at each step is 1. For WDC queries, however, we are able to prune multiple views in Q3, since the contradictory views have many shared contradictory rows, thus each contradictory signal contains many views. And since we prioritize presenting the more discriminatory signals first, we prune multiple views even in the worst case. \mypar{Conclusion} In the process of searching for a PJ-view, Niffler mines information that is useful to reduce the size of the candidate PJ-views before delivering them to the \textsc{view-presentation} stage. The 4C-signals help even without prior information about the correct join paths, and the correct view: they are useful to navigate pathless table collections. \subsection{View Specification Evaluation} We want to answer the following key questions through the evaluation of view specification stage. \begin{itemize} \item Does the view spec stage achieve the goal of finding relevant columns thoroughly and precisely? \item Does the view spec stage save user efforts? \item How does the view spec stage affect view search? \end{itemize} We evaluate and compare the following three algorithms. \begin{itemize} \item \textbf{\textit{Select-All}} Choose all columns that contain at least one user example as relevant. \textit{Select-All} is equivalent to how S4 \cite{s4} decides relevant columns. \item \textbf{\textit{Select-Best}} Only consider columns that contain the most number of examples as relevant. \textit{Select-Best} is equivalent to how Squid \cite{squid} chooses relevant columns. \item \textbf{\textit{Select-Cluster}} First find all matching columns that contain at least one user example, then cluster them as described in Algorithm 1. Last, choose clusters that have the highest score. \end{itemize} \subsubsection*{\textbf{Q1: Does Select-Cluster find relevant columns thoroughly and precisely?}} \subsubsection*{\textbf{Dataset and Groundtruth}} We use the dataset and ground truth from \cite{tableUnionSearch}. They collect 1405 tables from Canadian and UK Open Data and synthesize a ground truth indicating what columns are unionable. Unionable columns are columns that refer to the same entity. We adapt their ground truth through only keeping unionable columns that have overlap with each other because DoD only considers set similarity. \yg{TODO: Explain how i generate samples} \subsubsection*{\textbf{DoD Setup}} The major parameters in \textit{Select-Cluster} are the similarity metric and similarity threshold. These two parameters can be configured in Aurum. In this section, we set the similarity metric as overlap similarity \footnote{overlap(A, B) = $\frac{|A \cup B|}{min(|A|, |B|)}$} and the similarity threshold as 0.8. \subsubsection*{\textbf{Metric}} \begin{itemize} \item \textbf{Recall} $\frac{TP}{TP + FN}$, measures how many correct columns you can find. Low recall will decrease the possibility for users to find their desired views. \item \textbf{Precision} $\frac{TP}{TP + FP}$, measures how many found columns are correct. Low precision will increase noise and overhead to the view search and presentation stage. \item \textbf{F1 score} $\frac{2*Precision*Recall}{Precision + Recall}$ \end{itemize} The evaluation result on Open data is shown in \autoref{fig:q1}. Our \textit{Select-Cluster} method achieves higher recall and precision than \textit{Select-All}. On the other hand, \textit{Select-Cluster} has a much higher recall and a comparable precision with \textit{Select-Best}. Our \textit{Select-Cluster} method achieves the highest F1 score. \begin{figure}[ht] \centering \includegraphics[width=0.7\linewidth]{figures/view-spec-q1.png} \caption{view specification result on Open data} \label{fig:q1} \end{figure} \subsubsection*{\textbf{Q2: Does the view spec stage save user efforts?}} In \textit{Select-Cluster}, we first cluster similar columns, then select clusters with the highest score. User interaction can be integrated into $Select-Cluster$ naturally. Instead of let DoD choose clusters based on cluster score, we could show clusters to users and let them make the decision. In this section, we will look into if user interaction is introduced to view specification, how much user efforts will be needed. To estimate user efforts, we come up with the following two metrics. \begin{myitemize} \item \textbf{Number of clusters} The less the number of clusters is, the less user effort is needed. \item \textbf{Purity of each cluster} The purity of one cluster measures how well one cluster contains a single class (relevant or irrelevant). If most clusters have high purity scores, DoD can show users a random candidate inside one cluster instead of showing the entire cluster, which further reduces user effort. \end{myitemize} \autoref{fig:q2} shows the relation between the number of columns and the number of clusters. Generally speaking, the number of clusters increases as the number of candidate columns increases. However, the number of clusters remains relatively low compared to the number of columns. This suggests that if we involve user interaction in the view specification stage, users will only need to go through a small number of clusters. \begin{figure}[ht] \centering \includegraphics[width=\linewidth]{figures/view-spec-q2.png} \caption{the number of columns and the number of clusters} \label{fig:q2} \end{figure} \autoref{fig:purity} shows most clusters have a high purity score. More than 76\% of the clusters have purity scores large than 0.8 and more than 71\% of the clusters have purity scores large than 0.9. \begin{figure}[ht] \centering \includegraphics[width=\linewidth]{figures/view-spec-purity.png} \caption{Histogram: purity scores of clusters} \label{fig:purity} \end{figure}
{'timestamp': '2021-07-27T02:02:20', 'yymm': '2106', 'arxiv_id': '2106.01543', 'language': 'en', 'url': 'https://arxiv.org/abs/2106.01543'}
arxiv
\section{Tree Induction Algorithm Based on Syntactic Distance} \label{sec:appendix:tree_induction} The following algorithm is proposed in \citep{shen2018neural} to create a parse tree based on a given syntactic distance. \begin{algorithm}[h] \SetAlgoLined \KwData{Sentence $W = w_1 w_2 ... w_n$, syntactic distances $d_t = d(w_{t-1}, w_t \, | \, c_t)$, $2 \le t \le n$} \KwResult{A parse tree for $W$} Initialize the parse tree with a single node $n_0 = w_1 w_2 ... w_n$\; \While{$\exists$ leaf node $n = w_i w_{i+1} ... w_j$ where $i < j$}{ Find $k \in \argmax_{i+1 \le k \le j} d_k$ \; Create the left child $n_l$ and the right child $n_r$ of $n$ \; $n_l \leftarrow w_i w_{i+1} ... w_{k-1}$ \; $n_r \leftarrow w_k w_{k+1} ... w_j$ \; } \Return The parse tree rooted at $n_0$. \caption{Tree induction based on syntactic distance} \label{alg:tree_induction} \end{algorithm} \section{ON-LSTM Intuition} \label{sec:appendix:shen2019intuition} See Figure \ref{fig:shen2019intuition} below, which is excerpted from \citep{shen2018ordered} with minor adaptation to the notation. \begin{figure*}[ht] \centering \includegraphics[width=16cm]{figures/shen2019intuition_adapted.png} \caption{Relationship between the parse tree, the block view, and the ON-LSTM. Excerpted from \citep{shen2018ordered} with minor adaptation to the notation. } \label{fig:shen2019intuition} \end{figure*} \newpage \section{Examples of parsing transitions} \label{sec:appendix:parsing_transitions_examples} Table \ref{table:transition_based_parsing_example} below shows an example of parsing the sentence ``\textit{I drink coffee with milk}" using the set of transitions given by Definition \ref{def:adjoin}, which employs the parsing framework of \citep{dyer2016recurrent}. The parse tree of the sentence is given by \vspace{-8mm} { \small \begin{center} \begin{tabular}{c} \Tree [.S [.NP [.N I ] ] [.VP [.V drink ] [.NP [.NP [.N coffee ] ] [.PP [.P with ] [.N milk ] ] ] ] ] \end{tabular} \end{center} } \vspace{-6mm} \begin{table*}[ht] \centering \begin{tabular}{lll} \hline \textbf{Stack} & \textbf{Buffer} & \textbf{Action}\\ \hline & \textit{I drink coffee with milk} & \verb|NT(S)| \\ (S & \textit{I drink coffee with milk} & \verb|NT(NP)| \\ (S \(|\) (NP & \textit{I drink coffee with milk} & \verb|NT(N)| \\ (S \(|\) (NP \(|\) (N & \textit{I drink coffee with milk} & \verb|SHIFT| \\ (S \(|\) (NP \(|\) (N \(|\) \textit{I} & \textit{drink coffee with milk} & \verb|REDUCE| \\ (S \(|\) (NP (N \textit{I})) & \textit{drink coffee with milk} & \verb|NT(VP)| \\ (S \(|\) (NP (N \textit{I})) \(|\) (VP & \textit{drink coffee with milk} & \verb|NT(V)| \\ (S \(|\) (NP (N \textit{I})) \(|\) (VP \(|\) (V & \textit{drink coffee with milk} & \verb|SHIFT| \\ (S \(|\) (NP (N \textit{I})) \(|\) (VP \(|\) (V \(|\) \textit{drink} & \textit{coffee with milk} & \verb|REDUCE| \\ (S \(|\) (NP (N \textit{I})) \(|\) (VP \(|\) (V \textit{drink}) & \textit{coffee with milk} & \verb|NT(NP)| \\ (S \(|\) (NP (N \textit{I})) \(|\) (VP \(|\) (V \(|\) \textit{drink}) \(|\) \\ \quad (NP & \textit{coffee with milk} & \verb|NT(NP)| \\ (S \(|\) (NP (N \textit{I})) \(|\) (VP \(|\) (V \textit{drink}) \(|\) \\ \quad (NP \(|\) (NP & \textit{coffee with milk} & \verb|NT(N)| \\ (S \(|\) (NP (N \textit{I})) \(|\) (VP \(|\) (V \textit{drink}) \(|\) \\ \quad (NP \(|\) (NP \(|\) (N & \textit{coffee with milk} & \verb|SHIFT| \\ (S \(|\) (NP (N \textit{I})) \(|\) (VP \(|\) (V \textit{drink}) \(|\) \\ \quad (NP \(|\) (NP \(|\) (N \(|\) \textit{coffee} & \textit{with milk} & \verb|REDUCE| \\ (S \(|\) (NP (N \textit{I})) \(|\) (VP \(|\) (V \textit{drink}) \(|\) \\ \quad (NP \(|\) (NP (N \textit{coffee})) & \textit{with milk} & \verb|NT(PP)| \\ (S \(|\) (NP (N \textit{I})) \(|\) (VP \(|\) (V \textit{drink}) \(|\) \\ \quad (NP \(|\) (NP (N \textit{coffee})) \(|\) (PP & \textit{with milk} & \verb|NT(P)| \\ (S \(|\) (NP (N \textit{I})) \(|\) (VP \(|\) (V \textit{drink}) \(|\) \\ \quad (NP \(|\) (NP (N \textit{coffee})) \(|\) (PP \(|\) (P & \textit{with milk} & \verb|SHIFT| \\ (S \(|\) (NP (N \textit{I})) \(|\) (VP \(|\) (V \textit{drink}) \(|\) \\ \quad (NP \(|\) (NP (N \textit{coffee})) \(|\) (PP \(|\) (P \(|\) \textit{with} & \textit{milk} & \verb|REDUCE| \\ (S \(|\) (NP (N \textit{I})) \(|\) (VP \(|\) (V \textit{drink}) \(|\) \\ \quad (NP \(|\) (NP (N \textit{coffee})) \(|\) (PP \(|\) (P \textit{with}) & \textit{milk} & \verb|NT(N)| \\ (S \(|\) (NP (N \textit{I})) \(|\) (VP \(|\) (V \textit{drink}) \(|\) \\ \quad (NP \(|\) (NP (N \textit{coffee})) \(|\) (PP \(|\) (P \textit{with}) \(|\) (N & \textit{milk} & \verb|SHIFT| \\ (S \(|\) (NP (N \textit{I})) \(|\) (VP \(|\) (V \textit{drink}) \(|\) \\ \quad (NP \(|\) (NP (N \textit{coffee})) \(|\) (PP \(|\) (P \textit{with}) \(|\) (N \(|\) \textit{milk} & & \verb|REDUCE| \\ (S (NP (N \textit{I})) (VP (V \textit{drink}) \\ \quad (NP (NP (N \textit{coffee})) (PP (P \textit{with}) (N \textit{milk}))))) & & \\ \hline \end{tabular} \caption{\label{table:transition_based_parsing_example} Transition-based parsing of the sentence ``\textit{I drink coffee with milk}". } \end{table*} \section{Conclusion} \label{sec:conclusion} In this work, we considered the representational power of two frameworks for constituency parsing prominent in the literature, based on learning a syntactic distance and learning a sequence of iterative transitions to build the parse tree --- in the sandbox of PCFGs. In particular, we show that if the context for calculating distance/deciding on transitions is limited at least to one side (which is typically the case in practice for existing architectures), there are PCFGs for which no good distance metric/sequence of transitions can be chosen to construct the maximum likelihood parse. This limitation was already suspected in \citep{htut2018grammar} as a potential failure mode of leading neural approaches like \citep{shen2018neural,shen2018ordered} and we show formally that this is the case. The PCFGs with this property track the intuition that bounded context methods will have issues when the parse at a certain position depends heavily on latter parts of the sentence. The conclusions thus suggest re-focusing our attention on methods like \citep{kim2019compound} which have enjoyed greater success on tasks like unsupervised constituency parsing, and do not fall in the paradigm analyzed in our paper. A question of definite further interest is how to augment models that have been successfully scaled up (e.g. BERT) in a principled manner with syntactic information, such that they can capture syntactic structure (like PCFGs). The other question of immediate importance is to understand the interaction between the syntactic and semantic modules in neural architectures --- information is shared between such modules in various successful architectures, e.g. \citep{dyer2016recurrent, shen2018neural, shen2018ordered, kim2019compound}, and the relative pros and cons of doing this are not well understood. Finally, our paper purely focuses on representational power, and does not consider algorithmic and statistical aspects of training. As any model architecture is associated with its distinct optimization and generalization considerations, and natural language data necessitates the modeling of the interaction between syntax and semantics, those aspects of considerations are well beyond the scope of our analysis in this paper using the controlled sandbox of PCFGs, and are interesting directions for future work. \section{Representational Power of Neural Syntactic Distance Methods} \label{sec:distance} In this section we formalize the results on syntactic distance-based methods. Since the tree induction algorithm always generates a binary tree, we consider only PCFGs in Chomsky normal form (CNF) (Definition \ref{def:cnf}) so that the max likelihood parse of a sentence is also a binary tree structure. To formalize the notion of ``representing'' a PCFG, we introduce the following definition: \begin{definition}[Representing PCFG with syntactic distance] \label{def:pcfg_rep} Let $G$ be any PCFG in Chomsky Normal Form. A syntactic distance function $d$ is said to be able to {\bf $p$-represent} $G$ if for a set of sentences in $L(G)$ whose total probability is at least $p$, $d$ can correctly induce the tree structure of the max likelihood parse of these sentences without ambiguity. \end{definition} \begin{remark} Ambiguities could occur when, for example, there exists $t$ such that $d_t = d_{t+1}$. In this case, the tree induction algorithm would have to break ties when determining the local structure for $w_{t-1} w_t w_{t+1}$. We preclude this possibility in Definition \ref{def:pcfg_rep}. \end{remark} In the least restrictive setting, the whole sentence $W$, as well as the position index $t$ can be taken into consideration when determining each $d_t$. We prove that under this setting, there is a syntactic distance measure that can represent any PCFG. \begin{theorem}[Full context] \label{thm:tree_given_position_aware} Let $c_t = (W, t)$. For each PCFG $G$ in Chomsky normal form, there exists a syntactic distance measure $d_t = d(w_{t-1}, w_t \, | \, c_t)$ that can 1-represent $G$. \end{theorem} \begin{proof} For any sentence $s = s_1 s_2 ... s_n \in L(G)$, let $T$ be its max likelihood parse tree. Since $G$ is in Chomsky normal form, $T$ is a binary tree. We will describe an assignment of $\{d_t: 2 \le t \le n \}$ such that their order matches the level at which the branches split in $T$. Specifically, $\forall t \in [2, n]$, let $a_t$ denote the lowest common ancestor of $w_{t-1}$ and $w_t$ in $T$. Let $d'_t$ denote the shortest distance between $a_t$ and the root of $T$. Finally, let $d_t = n - d'_t$. As a result, $\{d_t: 2 \le t \le n \}$ induces $T$. \end{proof} \begin{remark} Since any PCFG can be converted to Chomsky normal form \citep{hopcroft2006book}, Theorem \ref{thm:tree_given_position_aware} implies that given the whole sentence and the position index as the context, the syntactic distance has sufficient representational power to capture any PCFG. It does not state, however, that the whole sentence and the position are the minimal contextual information needed for representability nor does it address training (i.e. optimization) issues. \end{remark} On the flipside, we show that restricting the context even mildly can considerably decrease the representational power. Namely, we show that if context is bounded \emph{even in a single direction} (to the left or to the right), there are PCFGs on which any syntactic distance will perform poorly \footnote{In Theorem \ref{thm:left_inf_right_finite} we prove the more typical case, i.e. unbounded left context and bounded right context. The other case, i.e. bounded left context and unbounded right context, can be proved symmetrically.}. (Note in the implementation \citep{shen2018neural} the context only considers a bounded window to the left.) \begin{theorem}[Limitation of left-to-right parsing via syntactic distance] \label{thm:left_inf_right_finite} Let $w_0 = \langle S \rangle$ be the sentence start symbol. Let the context $$c_t = (w_0, w_1, ..., w_{t+L'}).$$ $\forall \epsilon > 0$, there exists a PCFG $G$ in Chomsky normal form, such that any syntactic distance measure $d_t = d(w_{t-1}, w_t \, | \, c_t)$ cannot $\epsilon$-represent $G$. \end{theorem} \begin{proof} Let $m > 1/\epsilon$ be a positive integer. Consider the PCFG $G_{m,L'}$ in Definition \ref{def:difficult_grammar}. For any $k \in [m]$, consider the string $l_k \in L(G_{m,L'})$. Note that in the parse tree of $l_k$, the rule $S \rightarrow A_k B_k$ is applied. Hence, $a_k$ and $a_{k+1}$ are the unique pair of adjacent non-terminals in $a_1 a_2 ... a_{m+1}$ whose lowest common ancestor is the closest to the root in the parse tree of $l_k$. Then, in order for the syntactic distance metric $d$ to induce the correct parse tree for $l_k$, $d_k$ must be the unique maximum in $\{ d_t: 2 \le t \le {m+1} \}$. However, $d$ is restricted to be in the form $$d_t = d(w_{t-1}, w_t \, | \, w_0, w_1, ..., w_{t+L'}).$$ Note that $\forall 1 \le k_1 < k_2 \le {m}$, the first $m+1+L'$ tokens of $l_{k_1}$ and $l_{k_2}$ are the same, which implies that the inferred syntactic distances $$\{ d_t: 2 \le t \le {m+1} \}$$ are the same for $l_{k_1}$ and $l_{k_2}$ at each position $t$. Thus, it is impossible for $d$ to induce the correct parse tree for both $l_{k_1}$ and $l_{k_2}$. Hence, $d$ is correct on at most one $l_k \in L(G_{m,L'})$, which corresponds to probability at most $1/m < \epsilon$. Therefore, $d$ cannot $\epsilon$-represent $G_{m,L'}$. \end{proof} \begin{remark} In the counterexample, there are only $m$ possible parse structures for the prefix $a_1 a_2 ... a_{m+1}$. Hence, the proved fact that the probability of being correct is at most $1/m$ means that under the restrictions of unbounded look-back and bounded look-ahead, the distance cannot do better than random guessing for this grammar. \end{remark} \begin{remark} The above Theorem \ref{thm:left_inf_right_finite} formalizes the intuition discussed in \citep{htut2018grammar} outlining an intrinsic limitation of only considering bounded context in one direction. Indeed, for the PCFG constructed in the proof, the failure is a function of the context, not because of the fact that we are using a distance-based parser. \end{remark} Note that as a corollary of the above theorem, if there is no context ($c_t = \verb|null|$) or the context is both bounded and unidirectional, i.e. $$c_t = w_{t-L} w_{t-L+1} ... w_{t-1} w_t,$$ then there is a PCFG that cannot be $\epsilon$-represented by any such $d$. \section{Introduction} \label{sec:intro} Neural approaches have been steadily making their way to NLP in recent years. By and large however, the neural techniques that have been scaled-up the most and receive widespread usage do not explicitly try to encode discrete structure that is natural to language, e.g. syntax. The reason for this is perhaps not surprising: neural models have largely achieved substantial improvements in \emph{unsupervised} settings, BERT \citep{devlin-etal-2019-bert} being the de-facto method for unsupervised pre-training in most NLP settings. On the other hand unsupervised \emph{syntactic} tasks, e.g. unsupervised syntactic parsing, have long been known to be very difficult tasks \citep{htut2018grammar}. However, since incorporating syntax has been shown to improve language modeling \citep{kim2019unsupervised} as well as natural language inference \citep{chen-etal-2017-enhanced, pang2019improving, he-etal-2020-enhancing}, syntactic parsing remains important even in the current era when large pre-trained models, like BERT \citep{devlin-etal-2019-bert}, are available. Arguably, the breakthrough works in unsupervised constituency parsing in a neural manner were \citep{shen2018neural, shen2018ordered}, achieving F1 scores 42.8 and 49.4 on the WSJ Penn Treebank dataset \citep{htut2018grammar, shen2018ordered}. Both of these architectures, however (especially \citealp{shen2018neural}) are quite intricate, and it's difficult to evaluate what their representational power is (i.e. what \emph{kinds} of structure can they recover). Moreover, as subsequent more thorough evaluations show \citep{kim2019unsupervised, kim2019compound}, these methods still have a rather large performance gap with the oracle binary tree (which is the best binary parse tree according to F1-score) --- raising the question of \emph{what is missing} in these methods. We theoretically answer both questions raised in the prior paragraph. We quantify the representational power of two major frameworks in neural approaches to syntax: \emph{learning a syntactic distance} \citep{shen2018neural, shen2018straight, shen2018ordered} and \emph{learning to parse through sequential transitions} \citep{dyer2016recurrent, chelba1997structured}. To formalize our results, we consider the well-established sandbox of \emph{probabilistic context-free grammars} (PCFGs). Namely, we ask: \emph{When is a neural model based on a syntactic distance or transitions able to represent the max-likelihood parse of a sentence generated from a PCFG?} We focus on a crucial ``hyperparameter'' common to practical implementations of both families of methods that turns out to govern the representational power: the amount and type of context the model is allowed to use when making its predictions. Briefly, for every position $t$ in the sentence, syntactic distance models learn a distance $d_t$ to the previous token --- the tree is then inferred from this distance; transition-based models iteratively construct the parse tree by deciding, at each position $t$, what operations to perform on a partial parse up to token $t$. A salient feature of both is the \emph{context}, that is, \emph{which tokens is }$d_t$ \emph{a function of} (correspondingly, which tokens can the choice of operations at token $t$ depend on)? We show that when the context is either \emph{bounded} (that is, $d_t$ only depends on a bounded window around the $t$-th token) or \emph{unidirectional} (that is, $d_t$ only considers the tokens to the left of the $t$-th token), there are PCFGs for which no distance metric (correspondingly, no algorithm to choose the sequence of transitions) works. On the other hand, if the context is \emph{unbounded in both directions} then both methods work: that is, for any parse, we can design a distance metric (correspondingly, a sequence of transitions) that recovers it. This is of considerable importance: in practical implementations the context is either bounded (e.g. in \citealp{shen2018neural}, the distance metric is parametrized by a convolutional kernel with a constant width) or unidirectional (e.g. in \citealp{shen2018ordered}, the distance metric is computed by a LSTM, which performs a left-to-right computation). This formally confirms a conjecture of \citet{htut2018grammar}, who suggested that because these models commit to parsing decision in a left-to-right fashion and are trained as a part of a language model, it may be difficult for them to capture sufficiently complex syntactic dependencies. Our techniques are fairly generic and seem amenable to analyzing other approaches to syntax. Finally, while the existence of \emph{a particular} PCFG that is problematic for these methods doesn't necessarily imply that the difficulties will carry over to real-life data, the PCFGs that are used in our proofs closely track linguistic intuitions about difficult syntactic structures to infer: the parse depends on words that come much later in the sentence. \section{Representational Power of the Ordered Neuron Architecture} \label{sec:on-lstm} In this section, we formalize the results characterizing the representational power of the ON-LSTM architecture. The master forget gates of the ON-LSTM, $\{\tilde{f}_t\}_{t=2}^n$ in which each $\tilde{f}_t \in [0, 1]^D$, encode the hierarchical structure of a parse tree, and \citet{shen2018ordered} proposes to carry out unsupervised constituency parsing via a reduction from the gate vectors to syntactic distances by setting: \begin{equation} \label{eqn:on-lstm_to_distance} \hat{d}_t^f = D - \sum_{j=1}^{D} \tilde{f}_{t,j} \text{ for } t = 2..n \end{equation} First we show that the gates in ON-LSTM \emph{in principle} form a lossless representation of any parse tree. \begin{theorem}[Lossless representation of a parse tree] \label{thm:on-lstm_lossless} For any sentence $W = w_1 w_2 ... w_n$ with parse tree $T$ in any PCFG in Chomsky normal form, there exists a dimensionality $D \in \mathbb{Z}_+$, a sequence of vectors $\{\tilde{f_t}\}_{t=2}^n$ in which each $\tilde{f_t} \in [0, 1]^D$, such that the estimated syntactic distances via \eqref{eqn:on-lstm_to_distance} induce the structure of $T$. \end{theorem} \begin{proof} By Theorem \ref{thm:tree_given_position_aware}, there is a syntactic distance measure $\{d_t\}_{t=2}^n$ that induces the structure of $T$ (such that $\forall t, d_t \neq d_{t+1}$). For each $t = 2..n$, set $\hat{d_t} = k$ if $d_t$ is the $k$-th smallest entry in $\{d_t\}_{t=2}^n$, breaking ties arbitrarily. Then, each $\hat{d_t} \in [1, n-1]$, and $\{\hat{d_t}\}_{t=2}^n$ also induces the structure of $T$. Let $D = n-1$. For each $t = 2..n$, let $\tilde{f_t} = (0, ..., 0, 1, ..., 1)$ whose lower $\hat{d_t}$ dimensions are 0 and higher $D - \hat{d_t}$ dimensions are 1. Then, $$\hat{d}_t^f = D - \sum_{j=1}^{D} \tilde{f}_{t,j} = D - (D - \hat{d_t}) = \hat{d_t}.$$ Therefore, the calculated $\{\hat{d}_t^f\}_{t=2}^n$ induces the structure of $T$. \end{proof} Although Theorem \ref{thm:on-lstm_lossless} shows the ability of the master forget gates to perfectly represent any parse tree, a \emph{left-to-right} parsing can be proved to be unable to return the correct parse with high probability. In the actual implementation in \citep{shen2018ordered}, the (real-valued) master forget gate vectors $\{\tilde{f_t}\}_{t=1}^n$ are produced by feeding the input sentence $W = w_1 w_2 ... w_n$ to a model trained with a language modeling objective. In other words, $\tilde{f}_{t,j}$ is calculated as a function of $w_1, ..., w_t$, rather than the entire sentence. As such, this left-to-right parser is subject to similar limitations as in Theorem \ref{thm:left_inf_right_finite}: \begin{theorem}[Limitation of syntactic distance estimation based on ON-LSTM] \label{thm:on-lstm_to_distance} For any $\epsilon > 0$, there exists a PCFG $G$ in Chomsky normal form, such that the syntactic distance measure calculated with \eqref{eqn:on-lstm_to_distance}, $\hat{d}_t^f$, cannot $\epsilon$-represent $G$. \end{theorem} \begin{proof} Since by Definition \ref{def:master_forget_gates}, $\tilde{f}_{t,j}$ is a function of $w_1, ..., w_t$, the estimated syntactic distance $\hat{d}_t^f$ is also a function of $w_1, ..., w_t$. By Theorem \ref{thm:left_inf_right_finite}, even with unbounded look-back context $w_1, ..., w_t$, there exists a PCFG for which the probability that $\hat{d}_t^f$ induces the correct parse is arbitrarily low. \end{proof} \section{Overview of Results} \label{sec:overview} We consider several neural architectures that have shown success in various syntactic tasks, most notably unsupervised constituency parsing and syntax-aware language modeling. The general framework these architectures fall under is as follows: to parse a sentence $W = w_1 w_2 ... w_n$ with a trained neural model, the sentence $W$ is input into the model, which outputs $o_t$ at each step $t$, and finally all the outputs $\{o_t\}_{t=1}^n$ are utilized to produce the parse. Given unbounded time and space resources, by a seminal result of \citet{siegelmann1992rnn}, an RNN implementation of this framework is Turing complete. In practice it is common to restrict the form of the output $o_t$ in some way. In this paper, we consider the two most common approaches, in which $o_t$ is a \emph{real number representing a syntactic distance} (Section \ref{sec:overview:distance}) \citep{shen2018neural, shen2018straight, shen2018ordered} or a \emph{sequence of parsing operations} (Section \ref{sec:overview:seq_model}) \citep{chelba1997structured, chelba2000structured, dyer2016recurrent}. We proceed to describe our results for each architecture in turn. \subsection{Syntactic distance} \label{sec:overview:distance} \emph{Syntactic distance}-based neural parsers train a neural network to learn a distance for each pair of adjacent words, depending on the context surrounding the pair of words under consideration. The distances are then used to induce a tree structure \citep{shen2018neural, shen2018straight}. For a sentence $W = w_1 w_2 ... w_n$, the syntactic distance between $w_{t-1}$ and $w_t$ ($2 \le t \le n$) is defined as $d_t = d(w_{t-1}, w_t \, | \, c_t)$, where $c_t$ is the context that $d_t$ takes into consideration \footnote{Note that this is not a conditional distribution---we use this notation for convenience.}. We will show that restricting the surrounding context either in directionality, or in size, results in a poor representational power, while full context confers essentially perfect representational power with respect to PCFGs. Concretely, if the context is full, we show: \begin{theorem*}[Informal, full context] \label{thm:distance_positive_informal} For sentence $W$ generated by any PCFG, if the computation of $d_t$ has as context the full sentence and the position index under consideration, i.e. $c_t = (W, t)$ and $d_t = d(w_{t-1}, w_t \, | \, c_t)$, then $d_t$ can induce the maximum likelihood parse of $W$. \end{theorem*} On the flipside, if the context is unidirectional (i.e. unbounded left-context from the start of the sentence, and even possibly with a bounded look-ahead), the representational power becomes severely impoverished: \begin{theorem*}[Informal, limitation of left-to-right parsing via syntactic distance] There exists a PCFG $G$ such that for any distance measure $d_t$ whose computation incorporates only bounded context in at least one direction (left or right), e.g. \vspace{-4mm} \begin{align*} c_t &= (w_0, w_1, ..., w_{t+L'}) \\ d_t &= d(w_{t-1}, w_t \, | \, c_t) \\ \end{align*} \vspace{-12mm} the probability that $d_t$ induces the max likelihood parse is arbitrarily low. \end{theorem*} In practice, for computational efficiency, parametrizations of syntactic distances fall into the above assumptions of restricted context \citep{shen2018neural}. This puts the ability of these models to learn a complex PCFG syntax into considerable doubt. For formal definitions, see Section \ref{sec:prelim:distance}. For formal theorem statements and proofs, see Section \ref{sec:distance}. Subsequently we consider ON-LSTM, an architecture proposed by \citet{shen2018ordered} improving their previous work \citep{shen2018neural}, which also is based on learning a syntactic distance, but in \citep{shen2018ordered} the distances are reduced from the values of a carefully structured master forget gate (see Section \ref{sec:on-lstm}). While we show ON-LSTM can \emph{in principle} losslessly represent any parse tree (Theorem \ref{thm:on-lstm_lossless}), calculating the gate values in a left to right fashion (as is done in practice) is subject to the same limitations as the syntactic distance approach: \begin{theorem*}[Informal, limitation of syntactic distance estimation based on ON-LSTM] There exists a PCFG $G$ for which the probability that the syntactic distance converted from an ON-LSTM induces the max likelihood parse is arbitrarily low. \end{theorem*} For a formal statement, see Section \ref{sec:on-lstm} and in particular Theorem \ref{thm:on-lstm_to_distance}. \subsection{Transition-based parsing} \label{sec:overview:seq_model} In principle, the output $o_t$ at each position $t$ of a left-to-right neural models for syntactic parsing need not be restricted to a real-numbered distance or a carefully structured vector. It can also be a combinatorial structure --- e.g. a sequence of \emph{transitions} \citep{chelba1997structured, chelba2000structured, dyer2016recurrent}. We adopt a simplification of the neural parameterization in \citep{dyer2016recurrent} (see Definition \ref{def:adjoin}). With full context, \citet{dyer2016recurrent} describes an algorithm to find a sequence of transitions to represent any parse tree, via a ``depth-first, left-to-right traversal" of the tree. On the other hand, without full context, we prove that transition-based parsing suffers from the same limitations: \begin{theorem*}[Informal, limitation of transition-based parsing without full context] There exists a PCFG $G$, such that for any learned transition-based parser with bounded context in at least one direction (left or right), the probability that it returns the max likelihood parse is arbitrarily low. \end{theorem*} For a formal statement, see Section \ref{sec:seq_model}, and in particular Theorem \ref{thm:seq_left_to_right_backtrack}. \begin{remark} There is no immediate connection between the syntactic distance-based approaches (including ON-LSTM) and the transition-based parsing framework, so the limitations of transition-based parsing does not directly imply the stated negative results for syntactic distance or ON-LSTM, and vice versa. \end{remark} \subsection{The counterexample family} \label{sec:overview:counterexample} \begin{figure*}[t] \centering \includegraphics[width=10cm]{figures/counterexample_motivation.png} \caption{The parse trees of the two sentences: ``\textit{I drink coffee with milk.}'' and ``\textit{I drink coffee with friends.}''. Their only difference occurs at their very last words, but their parses differ at some earlier words in each sentence } \label{fig:counterexample_motivation} \end{figure*} Most of our theorems proving limitations on bounded and unidirectional context are based on a PCFG family (Definition \ref{def:difficult_grammar}) which draws inspirations from natural language already suggested in \citep{htut2018grammar}: later words in a sentence can force different syntactic structures earlier in the sentence. For example, consider the two sentences: ``\textit{I drink coffee with milk.}'' and ``\textit{I drink coffee with friends.}'' Their only difference occurs at their very last words, but their parses differ at some earlier words in each sentence, too, as shown in Figure \ref{fig:counterexample_motivation}. To formalize this intuition, we define the following PCFG. \begin{definition}[Right-influenced PCFG] \label{def:difficult_grammar} Let $m \ge 2, L' \ge 1$ be positive integers. The grammar $G_{m,L'}$ has starting symbol $S$, other non-terminals $$A_k, B_k, A_k^l, A_k^r, B_k' \text{ for all } k \in \{1, 2, ..., m\},$$ and terminals $$a_i \text{ for all } i \in \{1, 2, ..., m+1+L'\},$$ $$c_j \text{ for all } j \in \{1, 2, ..., m\}.$$ The rules of the grammar are \begin{align*} S &\rightarrow A_k B_k, \forall k \in \{1,2, \dots, m\} \; \text{w. prob.} 1/m \\ A_k &\rightarrow A_k^l A_k^r \quad \text{w. prob. } 1 \\ A_k^l &\rightarrow^* a_1 a_2 ... a_k \quad \text{w. prob. } 1 \\ A_k^r &\rightarrow^* a_{k+1} a_{k+2} ... a_{m+1} \quad \text{w. prob. } 1 \\ B_k &\rightarrow^* B_k' c_k \quad \text{w. prob. } 1 \\ B_k' &\rightarrow^* a_{m+2} a_{m+3} ... a_{m+1+L'} \quad \text{w. prob. } 1 \\ \end{align*} in which $\rightarrow^*$ means that the left expands into the right through a sequence of rules that conform to the requirements of the Chomsky normal form (CNF, Definition \ref{def:cnf}). Hence the grammar $G_{m,L'}$ is in CNF. The language of this grammar is $$L(G_{m,L'}) {=} \{l_k {=} a_1 a_2 ... a_{m+1+L'} c_k : 1 \le k \le m \}.$$ \end{definition} \begin{figure*}[t] \centering \includegraphics[width=10cm]{figures/counterexample_parse.png} \caption{The structure of the parse tree of string $l_k = a_1 a_2 ... a_{m+1+L'} c_k \in L(G_{m,L'})$. Note that any $l_{k_1}$ and $l_{k_2}$ are almost the same except for the last token: the prefix $a_1 a_2 ... a_{m+1+L'}$ is shared among all strings in $L(G_{m,L'})$. However, their parses differ with respect to where $A_k$ is split. The last token $c_k$ is unique to $l_k$ and hence determines the correct parse according to $G_{m,L'}$. } \label{fig:counterexample_parse} \end{figure*} The parse of an arbitrary $l_k$ is shown in Figure \ref{fig:counterexample_parse}. Each $l_k$ corresponds to a unique parse determined by the choice of $k$. The structure of this PCFG is such that for the parsing algorithms we consider that proceed in a ``left-to-right" fashion on $l_k $, before processing the last token $c_k$, it cannot infer the syntactic structure of $a_1 a_2 ... a_{m+1}$ any better than randomly guessing one of the $m$ possibilities. This is the main intuition behind Theorems \ref{thm:left_inf_right_finite} and \ref{thm:seq_left_to_right_backtrack}. \begin{remark} While our theorems focus on the limitation of ``left-to-right" parsing, a symmetric argument implies the same limitation of ``right-to-left" parsing. Thus, our claim is that \emph{unidirectional} context (in either direction) limits the expressive power of parsing models. \end{remark} \section{Preliminaries} \label{sec:prelim} In this section, we define some basic concepts and introduce the architectures we will consider. \subsection{Probabilistic context-free grammar} First recall several definitions around formal language, especially probabilistic context free grammar: \begin{definition}[Probabilistic context-free grammar (PCFG)] \label{def:pcfg} Formally, a PCFG \citep{chomsky1956three} is a 5-tuple $G = (\Sigma, N, S, R, \Pi)$ in which $\Sigma$ is the set of terminals, $N$ is the set of non-terminals, $S \in N$ is the start symbol, $R$ is the set of production rules of the form $r = (r_L \rightarrow r_R)$, where $r_L \in N$, $r_R$ is of the form $B_1 B_2 ... B_m$, $m \in \mathbb{Z_+}$, and $\forall i \in \{1,2,...,m\}, B_i \in (\Sigma \cup N)$. Finally, $\Pi: R \mapsto [0, 1]$ is the rule probability function, in which for any $$r = (A \rightarrow B_1 B_2 ... B_m) \in R,$$ $\Pi(r)$ is the conditional probability $$P(r_R = B_1 B_2 ... B_m \, | \, r_L = A).$$ \end{definition} \begin{definition}[Parse tree] \label{def:parse_tree} Let $T_G$ denote the set of parse trees that $G$ can derive. Each $t \in T_G$ is associated with $\verb|yield(t)| \in \Sigma^*$, the sequence of terminals composed of the leaves of $t$ and $P_T(t) \in [0, 1]$, the probability of the parse tree, defined by the product of the probabilities of the rules in the derivation of $t$. \end{definition} \begin{definition}[Language and sentence] \label{def:language_and_sentence} The language of $G$ is $$L(G) = \{s \in \Sigma^*: \exists t \in T_G, \verb|yield(t)| = s\}.$$ Each $s \in L(G)$ is called a sentence in $L(G)$, and is associated with the set of parses $T_G(s) = \{t \in T_G \, | \, \verb|yield(t)| = s\}$, the set of max likelihood parses, $\argmax_{t \in T_G(s)} P_T(t)$, and its probability $P_S(s) = \sum_{t \in T_G(s)} P_T(t)$. \end{definition} \begin{definition}[Chomsky normal form (CNF)] \label{def:cnf} A PCFG $G = (\Sigma, N, S, R, \Pi)$ is in CNF \citep{chomsky1959properties} if we require, in addition to Definition \ref{def:pcfg}, that each rule $r \in R$ is in the form $A \rightarrow B_1 B_2$ where $B_1, B_2 \in N \setminus \{S\}$; $A \rightarrow a$ where $a \in \Sigma, a \ne \epsilon$; or $S \rightarrow \epsilon$ which is only allowed if the empty string $\epsilon \in L(G)$. Every PCFG $G$ can be converted into a PCFG $G'$ in CNF such that $L(G) = L(G')$ \citep{hopcroft2006book}. \end{definition} \subsection{Syntactic distance} \label{sec:prelim:distance} The Parsing-Reading-Predict Networks (PRPN) \citep{shen2018neural} is one of the leading approaches to unsupervised constituency parsing. The parsing network (which computes the parse tree, hence the only part we focus on in our paper) is a convolutional network that computes the syntactic distances $d_t = d(w_{t-1}, w_t)$ (defined in Section \ref{sec:overview:distance}) based on the past $L$ words. A deterministic greedy tree induction algorithm is then used to produce a parse tree as follows. First, we split the sentence $w_1 ...w_n$ into two constituents, $w_1 ... w_{t-1}$ and $w_t ... w_n$, where $t \in \mbox{argmax} \{d_t\}_{t=2}^n$ and form the left and right subtrees of $t$. We recursively repeat this procedure for the newly created constituents. An algorithmic form of this procedure is included as Algorithm \ref{alg:tree_induction} in Appendix \ref{sec:appendix:tree_induction}. Note that, due to the deterministic nature of the tree-induction process, the ability of PRPN to learn a PCFG is completely contingent upon learning a good syntactic distance. \subsection{The ordered neuron architecture} \label{sec:prelim:on-lstm} Building upon the idea of representing the syntactic information with a real-valued distance measure at each position, a simple extension is to associate each position with a learned vector, and then use the vector for syntactic parsing. The ordered-neuron LSTM (ON-LSTM, \citealp{shen2018ordered}) proposes that the nodes that are closer to the root in the parse tree generate a longer span of terminals, and therefore should be less frequently ``forgotten'' than nodes that are farther away from the root. The difference in the frequency of forgetting is captured by a carefully designed master forget gate vector $\tilde{f}$, as shown in Figure \ref{fig:shen2019intuition} (in Appendix \ref{sec:appendix:shen2019intuition}). Formally: \begin{definition}[Master forget gates, \citealp{shen2018ordered}] \label{def:master_forget_gates} Given the input sentence $W = w_1 w_2 ... w_n$ and a trained ON-LSTM, running the ON-LSTM on $W$ gives the master forget gates, which are a sequence of $D$-dimensional vectors $\{\tilde{f}_t\}_{t=1}^n$, in which at each position $t$, $\tilde{f}_t = \tilde{f}_t(w_1, ..., w_t) \in [0, 1]^D$. Moreover, let $\tilde{f}_{t,j}$ represent the $j$-th dimension of $\tilde{f}_t$. The ON-LSTM architectures requires that $\tilde{f}_{t,1} = 0$, $\tilde{f}_{t,D} = 1$, and $$\forall i < j, \quad \tilde{f}_{t,i} \le \tilde{f}_{t,j}.$$ \end{definition} When parsing a sentence, the real-valued master forget gate vector $\tilde{f}_t$ at each position $t$ is reduced to a single real number representing the syntactic distance $d_t$ at position $t$ (see \eqref{eqn:on-lstm_to_distance}) \citep{shen2018neural}. Then, use the syntactic distances to obtain a parse. \subsection{Transition-based parsing} \label{sec:prelim:seq_model} In addition to outputting a single real numbered distance or a vector at each position $t$, a left-to-right model can also parse a sentence by outputting a sequence of ``transitions" at each position $t$, an idea proposed in some traditional parsing approaches \citep{sagae2005classifier, chelba1997structured, chelba2000structured}, and also some more recent neural parameterization \citep{dyer2016recurrent}. We introduce several items of notation: \begin{itemize} \item $z_i^t$: the $i$-th transition performed when reading in $w_t$, the $t$-th token of the sentence $$W = w_1 w_2 ... w_n.$$ \vspace{-8mm} \item $N_t$: the number of transitions performed between reading in the token $w_t$ and reading in the next token $w_{t+1}$. \vspace{-3mm} \item $Z_t$: the sequence of transitions after reading in the prefix $w_1 w_2 ... w_t$ of the sentence. $$Z_t = \{(z_1^j, z_2^j, ..., z_{N_j}^j) \, | \, j=1..t \}.$$ \vspace{-8mm} \item $Z$: the parse of the sentence $W$. $Z = Z_n$. \end{itemize} We base our analysis on the approach introduced in the \emph{parsing} version of \citep{dyer2016recurrent}, though that work additionally proposes a \emph{generator} version. \footnote{\citet{dyer2016recurrent} additionally proposes some \emph{generator} transitions. For simplicity, we analyze the simplest form: we only allow the model to return one parse, composed of the \emph{parser} transitions, for a given input sentence. Note that this simplified variant still confers full representational power in the ``full context" setting (see Section \ref{sec:seq_model}). } \begin{definition}[Transition-based parser] \label{def:left_to_right_tree_adjoining_parser} A \emph{transition-based parser} uses a stack (initialized to empty) and an input buffer (initialized with the sentence $w_1 ... w_t$). At each position $t$, based on a context $c_t$, the parser outputs a sequence of parsing transitions $\{z_{i}^t\}_{i=1}^{N_t}$, where each $z_{i}^t$ can be one of the following transitions (Definition \ref{def:adjoin}). The parsing stops when the stack contains one single constituent, and the buffer is empty. \end{definition} \begin{definition}[Parser transitions, \citealp{dyer2016recurrent}] \label{def:adjoin} A parsing transition can be one of the following three types: \begin{itemize} \item NT(X) pushes a non-terminal X onto the stack. \item SHIFT: removes the first terminal from the input buffer and pushes onto the stack. \item REDUCE: pops from the stack until an open non-terminal is encountered, then pops this non-terminal and assembles everything popped to form a new constituent, labels this new constituent using this non-terminal, and finally pushes this new constituent onto the stack. \end{itemize} \end{definition} In Appendix Section \ref{sec:appendix:parsing_transitions_examples}, we provide an example of parsing the sentence ``\textit{I drink coffee with milk}" using the set of transitions given by Definition \ref{def:adjoin}. The different context specifications and the corresponding representational powers of the transition-based parser are discussed in Section \ref{sec:seq_model}. \section{Related Works} \label{sec:related_works} Neural models for parsing were first successfully implemented for supervised settings, e.g. \citep{vinyals2015grammar, dyer2016recurrent, shen2018straight}. Unsupervised tasks remained seemingly out of reach, until the proposal of the Parsing-Reading-Predict Network (PRPN) by \citet{shen2018neural}, whose performance was thoroughly verified by extensive experiments in \citep{htut2018grammar}. The follow-up paper \citep{shen2018ordered} introducing the ON-LSTM architecture simplified radically the architecture in \citep{shen2018neural}, while still ultimately attempting to fit a distance metric with the help of carefully designed master forget gates. Subsequent work by \citet{kim2019compound} departed from the usual way neural techniques are integrated in NLP, with great success: they proposed a neural parameterization for the EM algorithm for learning a PCFG, but in a manner that leverages semantic information as well --- achieving a large improvement on unsupervised parsing tasks.\footnote{By virtue of not relying on bounded or unidirectional context, the Compound PCFG \citep{kim2019compound} eschews the techniques in our paper. Specifically, by employing a bidirectional LSTM inference network in the process of constructing a tree given a sentence, the parsing is no longer ``left-to-right". } In addition to constituency parsing, dependency parsing is another common task for syntactic parsing, but for our analyses on the ability of various approaches to represent the max-likelihood parse of sentences generated from PCFGs, we focus on the task of constituency parsing. Moreover, it's important to note that there is another line of work aiming to probe the ability of models trained without explicit syntactic consideration (e.g. BERT) to nevertheless discover some (rudimentary) syntactic elements \citep{bisk2015probing, linzen2016assessing, choe2016parsing, kuncoro2018lstms, williams2018latent, goldberg2019assessing, htut2019attention, hewitt-manning-2019-structural, reif2019visualizing}. However, to-date, we haven't been able to extract parse trees achieving scores that are close to the oracle binarized trees on standard benchmarks \citep{kim2019unsupervised, kim2019compound}. Methodologically, our work is closely related to a long line of works aiming to characterize the representational power of neural models (e.g. RNNs, LSTMs) through the lens of formal languages and formal models of computation. Some of the works of this flavor are empirical in nature (e.g. LSTMs have been shown to possess stronger abilities to recognize some context-free language and even some context-sensitive language, compared with simple RNNs \citep{gers2001lstm, suzgun2019lstm} or GRUs \citep{weiss2018practical, suzgun2019lstm}); some results are theoretical in nature (e.g. \citet{siegelmann1992rnn}'s proof that with unbounded precision and unbounded time complexity, RNNs are Turing-complete; related results investigate RNNs with bounded precision and computation time \citep{weiss2018practical}, as well as memory \citep{merrill2019sequential, hewitt2020rnns}. Our work contributes to this line of works, but focuses on the task of syntactic parsing instead. \section{Representational Power of Transition-Based Parsing} \label{sec:seq_model} In this section, we analyze a transition-based parsing framework inspired by \citep{dyer2016recurrent, chelba2000structured, chelba1997structured}. Again, we proceed to say first that ``full context'' confers full representational power. Namely, using the terminology of Definition \ref{def:left_to_right_tree_adjoining_parser}, we let the context $c_t$ at each position $t$ be the whole sentence $W$ and the position index $t$. Note that any parse tree can be generated by a sequence of transitions defined in Definition \ref{def:adjoin}. Indeed, \citet{dyer2016recurrent} describes an algorithm to find such a sequence of transitions via a ``depth-first, left-to-right traversal" of the tree. Proceeding to limited context, in the setting of typical left-to-right parsing, the context $c_t$ consists of all current and past tokens $\{w_j\}_{j=1}^{t}$ and all previous parses $\{(z_{1}^j, ..., z_{N_j}^j)\}_{j=1}^{t}$. We'll again prove even stronger negative results, where we allow an optional look-ahead to $L'$ input tokens to the right. \begin{theorem}[Limitation of transition-based parsing without full context] \label{thm:seq_left_to_right_backtrack} For any $\epsilon > 0$, there exists a PCFG $G$ in Chomsky normal form, such that for any learned transition-based parser (Definition \ref{def:left_to_right_tree_adjoining_parser}) based on context $$c_t = (\{w_j\}_{j=1}^{t+L'}, \{(z_{1}^j, ..., z_{N_j}^j)\}_{j=1}^{t}),$$ the sum of the probabilities of the sentences in $L(G)$ for which the parser returns the maximum likelihood parse is less than $\epsilon$. \end{theorem} \begin{proof} Let $m > 1/\epsilon$ be a positive integer. Consider the PCFG $G_{m,L'}$ in Definition \ref{def:difficult_grammar}. Note that $\forall k, S \rightarrow A_k B_k$ is applied to yield string $l_k$. Then in the parse tree of $l_k$, $a_k$ and $a_{k+1}$ are the unique pair of adjacent terminals in $a_1 a_2 ... a_{m+1}$ whose lowest common ancestor is the closest to the root. Thus, different $l_k$ requires a different sequence of transitions within the first $m+1$ input tokens, i.e. $\{z_i^t\}_{i \ge 1, \, 1 \le t \le m+1}$. For each $w \in L(G_{m,L'})$, before the last token $w_{m+2+L'}$ is processed, based on the common prefix $w_1 w_2 ... w_{m+1+L'} = a_1 a_2 ... a_{m+1+L'}$, it is equally likely that $w = l_k, \forall k$, w. prob. $1/m$ each. Moreover, when processing $w_{m+1}$, the bounded look-ahead window of size $L'$ does not allow access to the final input token $a_{m+2+L'} = c_k$. Thus, $\forall 1 \le k_1 < k_2 \le {m}$, it is impossible for the parser to return the correct parse tree for both $l_{k_1}$ and $l_{k_2}$ without ambiguity. Hence, the parse is correct on at most one $l_k \in L(G)$, which corresponds to probability at most $1/m < \epsilon$. \end{proof}
{'timestamp': '2021-06-04T02:10:10', 'yymm': '2106', 'arxiv_id': '2106.01580', 'language': 'en', 'url': 'https://arxiv.org/abs/2106.01580'}
arxiv
\section{Introduction} Building a conversational agent with intelligence has drawn significant attention from both academia and industry. Most of existing methods have studied understanding conversations between two participants, aiming to return an appropriate response either in a generation-based \cite{DBLP:conf/acl/ShangLL15,DBLP:conf/aaai/SerbanSBCP16,DBLP:conf/aaai/SerbanSLCPCB17,DBLP:conf/nips/ZhangGGGLBD18,DBLP:conf/acl/ZhangSGCBGGLD20} or retrieval-based manner \cite{DBLP:conf/sigdial/LowePSP15,DBLP:conf/acl/WuWXZL17,DBLP:conf/acl/WuLCZDYZL18,DBLP:conf/wsdm/TaoWXHZY19,DBLP:conf/acl/TaoWXHZY19,DBLP:conf/cikm/GuLL19,DBLP:conf/emnlp/GuLZL19,DBLP:conf/cikm/GuLLLSWZ20}. Recently, researchers have paid more attention to a more practical and challenging scenario involving more than two participants, which is well known as multi-party conversation (MPC) \cite{DBLP:conf/emnlp/OuchiT16,DBLP:conf/aaai/ZhangLPR18,DBLP:conf/emnlp/LeHSYBZY19,DBLP:conf/ijcai/HuCL0MY19}. Table~\ref{tab-example} shows an MPC example in the Ubuntu Internet Relay Chat (IRC) channel, which is composed of a sequence of (\emph{speaker, utterance, addressee}) triples. In addition to returning an appropriate response, predicting who will be the next speaker \cite{DBLP:conf/lrec/MengMJ18} and who is the addressee of an utterance \cite{DBLP:conf/emnlp/OuchiT16,DBLP:conf/aaai/ZhangLPR18,DBLP:conf/emnlp/LeHSYBZY19} are unique and important issues in MPC. \begin{table}[t \small \centering \setlength{\tabcolsep}{2.4pt} \begin{tabular}{c|l|c} \toprule Speaker & \multicolumn{1}{c|}{Utterance} & Addressee \\ \hline \multirow{2}{*}{I.1} & How can I setup if I want add new & \multirow{2}{*}{-} \\ & server at xchat? & \\ \hline \multirow{3}{*}{I.2} & From places, network servers, work & \multirow{3}{*}{I.1} \\ & group, his computer, and then I & \\ & clicked on the shared folder. & \\ \hline I.3 & It did not allow you to see the files? & I.2 \\ \hline \multirow{3}{*}{I.2} & It prompts for authentication and I & \multirow{3}{*}{I.3} \\ & don't know what to put. I tried guest & \\ & with no password. \\ \hline I.4 & Put proper authentication in, then? & I.2 \\ \hline I.3 & I think you had kde on suse? & I.2 \\ \bottomrule \end{tabular} \caption{An MPC example in Ubuntu IRC channel. Here, ``I." is the abbreviation of ``interlocutor".} \label{tab-example} \end{table} An instance of MPC always contains complicated interactions between interlocutors, between utterances and between an interlocutor and an utterance. Therefore, it is challenging to model the conversation flow and fully understand the dialogue content. Existing studies on MPC learn the representations of interlocutors and utterances with neural networks, and their representation spaces are either separate \cite{DBLP:conf/emnlp/OuchiT16} or interactive \cite{DBLP:conf/aaai/ZhangLPR18}. However, the semantics contained in the interlocutor and utterance representations may not be effectively captured as they are from two different representation spaces. Recently, to take advantage of the breakthrough in pre-training language models (PLMs) for natural language understanding, some studies proposed to integrate the speaker \cite{DBLP:conf/cikm/GuLLLSWZ20} or topic \cite{DBLP:conf/emnlp/WangHJ20} information into PLMs. Despite of the performance improvement on response selection, these models still overlook the inherent relationships between utterances and interlocutors, such as ``address-to". Furthermore, most existing studies design models for each individual task in MPC (e.g., addressee recognition, speaker identification and response prediction) separately. Intuitively, these tasks are complementary among each other. Making use of these tasks simultaneously may produce better contextualized representations of interlocutors and utterances, and would enhance the conversation understanding, but is neglected in previous studies. On account of above issues, we propose MPC-BERT which jointly learns \emph{who} says \emph{what} to \emph{whom} in MPC by designing self-supervised tasks for PLMs, so as to improve the ability of PLMs on MPC understanding. Specifically, the five designed tasks includes \emph{reply-to utterance recognition, identical speaker searching, pointer consistency distinction, masked shared utterance restoration} and \emph{shared node detection}. The first three tasks are designed to model the interlocutor structure in MPC in a \emph{semantics-to-structure} manner. In the output of MPC-BERT, an interlocutor is described through the encoded representations of the utterances it says. Thus, the representations of utterance semantics are utilized to construct the conversation structure in these three tasks. On the other hand, the last two tasks are designed to model the utterance semantics in a \emph{structure-to-semantics} manner. Intuitively, the conversation structure influences the information flow in MPC. Thus, the structure information can also be used to strengthen the representations of utterance semantics in return. In general, these five self-supervised tasks are employed to jointly train the MPC-BERT in a multi-task learning framework, which helps the model to learn the complementary information among interlocutors and utterances, and that between structure and semantics. By this means, MPC-BERT can produce better interlocutor and utterance representations which can be effectively generalized to multiple downstream tasks of MPC. To measure the effectiveness of these self-supervised tasks and to test the generalization ability of MPC-BERT, we evaluate it on three downstream tasks including \emph{addressee recognition}, \emph{speaker identification} and \emph{response selection}, which are three core research issues of MPC. Two benchmarks based on Ubuntu IRC channel are employed for evaluation. One was released by \citet{DBLP:conf/ijcai/HuCL0MY19}. The other was released by \citet{DBLP:conf/emnlp/OuchiT16} and has three experimental settings according to session lengths. Experimental results show that MPC-BERT outperforms the current state-of-the-art models by margins of 3.51\%, 2.86\%, 3.28\% and 5.36\% on the test sets of these two benchmarks respectively in terms of the session accuracy of addressee recognition, by margins of 7.66\%, 2.60\%, 3.38\% and 4.24\% respectively in terms of the utterance precision of speaker identification, and by margins of 3.82\%, 2.71\%, 2.55\% and 3.22\% respectively in terms of the response recall of response selection. In summary, our contributions in this paper are three-fold: (1) MPC-BERT, a PLM for MPC understanding, is proposed by designing five self-supervised tasks based on the interactions among utterances and interlocutors. (2) Three downstream tasks are employed to comprehensively evaluate the effectiveness of our designed self-supervised tasks and the generalization ability of MPC-BERT. (3) Our proposed MPC-BERT achieves new state-of-the-art performance on all three downstream tasks at two benchmarks. \section{Related Work} Existing methods on building dialogue systems can be generally categorized into studying two-party conversations and multi-party conversations (MPC). In this paper, we study MPC. In addition to predicting utterances, identifying the \emph{speaker} and recognizing the \emph{addressee} of an utterance are also important tasks for MPC. \citet{DBLP:conf/emnlp/OuchiT16} first proposed the task of addressee and response selection and created an MPC corpus for studying this task. \citet{DBLP:conf/aaai/ZhangLPR18} proposed SI-RNN, which updated speaker embeddings role-sensitively for addressee and response selection. \citet{DBLP:conf/lrec/MengMJ18} proposed a task of speaker classification as a surrogate task for speaker modeling. \citet{DBLP:conf/emnlp/LeHSYBZY19} proposed a who-to-whom (W2W) model to recognize the addressees of all utterances. \citet{DBLP:conf/ijcai/HuCL0MY19} proposed a graph-structured network (GSN) to model the graphical information flow for response generation. \citet{DBLP:conf/emnlp/WangHJ20} proposed to track the dynamic topic for response selection. Generally speaking, previous studies on MPC cannot unify the representations of interlocutors and utterances effectively. Also, they are limited to each individual task, ignoring the complementary information among different tasks. To the best of our knowledge, this paper makes the first attempt to design various self-supervised tasks for building PLMs aiming at MPC understanding, and to evaluate the performance of PLMs on three downstream tasks as comprehensively as possible. \section{MPC-BERT and Self-Supervised Tasks} An MPC instance is composed of a sequence of (\emph{speaker, utterance, addressee}) triples, denoted as $\{(s_n,u_n,a_n)\}_{n=1}^N$, where $N$ is the number of turns in the conversation. Our goal is to build a pre-trained language model for universal MPC understanding. Given a conversation, this model is expected to produce embedding vectors for all utterances which contain not only the semantic information of each utterance, but also the speaker and addressee structure of the whole conversation. Thus, it can be effectively adapted to various downstream tasks by fine-tuning model parameters. \subsection{Model Overview} In this paper, BERT \cite{DBLP:conf/naacl/DevlinCLT19} is chosen as the backbone of our PLM for MPC. Thus, we name it MPC-BERT. It is worth noting that our proposed self-supervised tasks for training MPC-BERT can also be applied to other types of PLMs. We first give an overview of the input representations and the overall architectures of MPC-BERT. When constructing the input representations, in order to consider the speaker information of each utterance, \emph{speaker} embeddings \cite{DBLP:conf/cikm/GuLLLSWZ20} are introduced as shown in Figure~\ref{fig-pretrain-interlocutor}. Considering that the set of interlocutors are inconsistent in different conversations, a position-based interlocutor embedding table is initialized randomly at first and updated during pre-training, which means each interlocutor in a conversation is assigned with an embedding vector according to the order it appears in the conversation. Then, the speaker embeddings for each utterance can be derived by looking up this embedding table. The speaker embeddings are combined with standard token, position and segmentation embeddings and are then encoded by BERT. The output embeddings of BERT corresponding to different input tokens are utilized by different self-supervised tasks for further calculation. \subsection{Tasks of Interlocutor Structure Modeling} \begin{figure*}[t] \centering \includegraphics[width=15cm]{figures/pretraining_interlocutor_S.pdf} \caption{Input representations and model architectures of the three self-supervised tasks for interlocutor structure modeling, including (a) reply-to utterance recognition, (b) identical speaker searching and (c) pointer consistency distinction. } \label{fig-pretrain-interlocutor} \end{figure*} The first three tasks follow the \emph{semantics-to-structure} manner. In MPC-BERT, each interlocutor is described through the encoded representations of the utterances it says. Thus, the representations of utterance semantics are utilized to construct the conversation structure. Figure~\ref{fig-pretrain-interlocutor} shows the input representations and the model architectures of these three tasks. A \texttt{[CLS]} token is inserted at the start of each utterance, denoting its utterance-level representation. Then, all utterances in a conversation are concatenated and a \texttt{[SEP]} token is inserted at the end of the whole sequence. It is notable that these three tasks share the same form of input data. Thus, the input only needs to be encoded once by BERT while the output can be fed into three tasks, which is computation-efficient. As shown in Figure~\ref{fig-pretrain-interlocutor}, a task-dependent non-linear transformation layer is placed on top of BERT in order to adapt the output of BERT to different tasks. We will describe the details of these tasks as follows. \subsubsection{Reply-to Utterance Recognition} To enable the model to recognize the addressee of each utterance, a self-supervised task named \emph{reply-to utterance recognition (RUR)} is proposed to learn which preceding utterance the current utterance replies to. After encoded by BERT, we extract the contextualized representations for each \texttt{[CLS]} token representing individual utterances. Next, a non-linear transformation followed by a layer normalization are performed to derive the utterance representations for this specific task $\{\textbf{u}_i^{rur}\}_{i=1}^N$, where $\textbf{u}_i^{rur} \in \mathbb{R}^{d}$ and $d = 768$. Then, for a specific utterance U$_i$, its matching scores with all its preceding utterances are calculated as \begin{align} \label{equ-rur} m_{ij} = \textbf{softmax} (\textbf{u}_i^{rur\top} \cdot \textbf{A}^{rur} \cdot \textbf{u}_j^{rur}), \end{align} where $\textbf{A}^{rur} \in \mathbb{R}^{d \times d}$ is a linear transformation, $m_{ij}$ denotes the matching degree of U$_j$ being the reply-to utterance of U$_i$, and $1\leq j<i$. We construct a set $\mathbb{S}$ by sampling a certain number of utterances in a conversation and this recognition operation is performed for each utterance in $\mathbb{S}$. Meanwhile, a dynamic sampling strategy is adopted so that models can see more samples. Finally, the pre-training objective of this self-supervised task is to minimize the cross-entropy loss as \begin{equation} \label{equ-rur-loss} \mathcal{L}_{rur} = - \sum_{i \in \mathbb{S}} \sum_{j=1}^{i-1} y_{ij} ~ log(m_{ij}), \end{equation} where $y_{ij} = 1$ if U$_j$ is the reply-to utterance of U$_i$ and $y_{ij} = 0$ otherwise. \subsubsection{Identical Speaker Searching} \label{sec_iss} Having knowledge of who is the speaker of an utterance is also important for MPC. The task of \emph{identical speaker searching (ISS)} is designed by masking the speaker embedding of a specific utterance in the input representation, and aims to predict its speaker given the conversation. Since the set of interlocutors vary across conversations, the task of predicting the speaker of an utterance is reformulated as \emph{searching for the utterances sharing the identical speaker.} First, for a specific utterance, its speaker embedding is masked with a special \texttt{[Mask]} interlocutor embedding to avoid information leakage. Given the utterance representations for this specific task $\{\textbf{u}_i^{iss}\}_{i=1}^N$ where $\textbf{u}_i^{iss} \in \mathbb{R}^{d}$, the matching scores of U$_i$ with all its preceding utterances are calculated similarly with Eq.~(\ref{equ-rur}). Here, $m_{ij}$ denotes the matching degree of U$_j$ sharing the same speaker with U$_i$. For each instance in the dynamic sampling set $\mathbb{S}$, there must be an utterance in previous turns sharing the same speaker. Otherwise, it is removed out of the set. Finally, the pre-training objective of this task is to minimize the cross-entropy loss similarly with Eq.~(\ref{equ-rur-loss}). Here, $y_{ij} = 1$ if U$_j$ shares the same speaker with U$_i$ and $y_{ij} = 0$ otherwise. \subsubsection{Pointer Consistency Distinction} We design a task named \emph{pointer consistency distinction (PCD)} to jointly model speakers and addressees in MPC. In this task, a pair of utterances representing the ``\emph{reply-to}'' relationship is defined as a \emph{speaker-to-addressee pointer}. Here, we assume that the representations of two pointers directing from the same speaker to the same addressee should be consistent. As illustrated in Figure~\ref{fig-pretrain-pcd-snd} (a), speaker S$_m$ speaks U$_i$ and U$_j$ which reply to U$_{i'}$ and U$_{j'}$ from speaker S$_n$ respectively. Thus, the utterance tuples (U$_i$, U$_{i'}$) and (U$_j$, U$_{j'}$) both represent the pointer of S$_m$-to-S$_n$ and their pointer representations should be consistent.. Given the utterance representations for this specific task $\{\textbf{u}_i^{pcd}\}_{i=1}^N$ where $\textbf{u}_i^{pcd} \in \mathbb{R}^{d}$, we first capture the pointer information contained in each utterance tuple. The element-wise difference and multiplication between an utterance tuple (U$_i$, U$_{i'}$) are computed and are concatenated as \begin{align} \textbf{p}_{ii'} = [\textbf{u}_i^{pcd} - \textbf{u}_{i'}^{pcd} ; \textbf{u}_i^{pcd} \odot \textbf{u}_{i'}^{pcd}], \end{align} where $\textbf{p}_{ii'} \in \mathbb{R}^{2d}$. Then, we compress $\textbf{p}_{ii'}$ and obtain the pointer representation $\bar{\textbf{p}}_{ii'}$ as \begin{align} \bar{\textbf{p}}_{ii'} = \textbf{ReLU}( \textbf{p}_{ii'} \cdot \textbf{W}_{pcd} + \textbf{b}_{pcd} ), \end{align} where $ \textbf{W}_{pcd} \in \mathbb{R}^{2d \times d} $ and $ \textbf{b}_{pcd} \in \mathbb{R}^{d} $ are parameters. Identically, a consistent pointer representations $\bar{\textbf{p}}_{jj'}$ and an inconsistent one $\bar{\textbf{p}}_{kk'}$ sampled from this conversation are obtained. The similarities between every two pointers are calculated as \begin{align} m_{ij} = \textbf{sigmoid} (\bar{\textbf{p}}_{ii'}^{\top} \cdot \textbf{A}^{pcd} \cdot \bar{\textbf{p}}_{jj'}), \end{align} where $m_{ij}$ denotes the matching degree of pointer $\bar{\textbf{p}}_{ii'}$ being consistent with pointer $\bar{\textbf{p}}_{jj'}$. $m_{ik}$ can be derived accordingly. Finally, the pre-training objective of this task is to minimize the hinge loss which enforces $m_{ij}$ to be larger than $m_{ik}$ by at least a margin $\Delta$ as \begin{equation} \label{equ-pcd} \mathcal{L}_{pcd} = \textbf{max}\{ 0, \Delta - m_{ij} + m_{ik} \}. \end{equation} \subsection{Tasks of Utterance Semantics Modeling} \begin{figure}[t] \centering \subfigure[{Pointer consistency distinction}]{ \includegraphics[width=0.45\linewidth]{figures/pcd.pdf}} \hspace{1.5mm} \subfigure[Shared node detection]{ \includegraphics[width=0.45\linewidth]{figures/snd.pdf}} \caption{Illustrations of the self-supervised tasks of (a) pointer consistency distinction and (b) shared node detection. Rectangles denote utterances, circles denote interlocutors, a solid line denotes an utterance replying to an utterance, and a dashed line denotes an utterance from an interlocutor.} \label{fig-pretrain-pcd-snd} \end{figure} Intuitively, the conversation structure might influence the information flow, so that it can be used to strengthen the representations of utterance semantics. Thus, two self-supervised tasks following the \emph{structure-to-semantics} manner are designed. \subsubsection{Masked Shared Utterance Restoration} There are usually several utterances replying-to a shared utterance in MPC. Intuitively, a shared utterance is semantically relevant to more utterances in the context than non-shared ones. Based on this characteristic, we design a task named \emph{masked shared utterance restoration (MSUR)}. We first randomly sample an utterance from all shared utterances in a conversation and all tokens in this sampled utterance are masked with a \texttt{[MASK]} token. Then the model is enforced to restore the masked utterance given the rest conversation. Formally, assuming U$_i$ as the masked shared utterance and $l_i$ as the number of tokens in U$_i$. Given the token representations for this task $\{\textbf{u}_{i,t}^{msur}\}_{t=1}^{l_i}$ where $\textbf{u}_{i,t}^{msur} \in \mathbb{R}^{d}$, the probability distribution of each masked token can be calculated as \begin{align} \textbf{p}_{u_{i,t}} = \textbf{softmax}( \textbf{u}_{i,t}^{msur} \cdot \textbf{W}_{msur} + \textbf{b}_{msur} ), \end{align} where $ \textbf{W}_{msur} \in \mathbb{R}^{d \times V} $ is the token embedding table, $V$ denotes the vocabulary size, and $\textbf{b}_{msur} \in \mathbb{R}^{V} $ is a bias vector. Finally, the pre-training objective of this self-supervised task is to minimize the negative log-likelihood loss as \begin{equation} \mathcal{L}_{msur} = - \frac{1}{l_i} \sum_{t=1}^{l_i} log~p_{u_{i,t}}, \end{equation} where $p_{u_{i,t}}$ is the element in \textbf{p}$_{u_{i,t}}$ corresponding to the original token. \subsubsection{Shared Node Detection} A full MPC instance can be divided into several sub-conversations and we assume that the representations of sub-conversations under the same parent node tend to be similar. As illustrated in Figure~\ref{fig-pretrain-pcd-snd} (b), two sub-conversations \{U$_3$, U$_5$, U$_7$, U$_8$\} and \{U$_4$, U$_6$, U$_9$\} share the same parent node U$_2$. Thus, they should be semantically relevant. Under this assumption, we design a self-supervised task named \emph{shared node detection (SND)}, which utilizes the conversation structure to strengthen the capability of models on measuring the semantic relevance of two sub-conversations. We first construct the pre-training samples for this task. Empirically, only the sub-conversations under the top shared node in a conversation are collected in order to filter out the sub-conversations with few utterances. Given a full MPC, the two sub-conversations with the most utterances form a positive pair. For each positive pair, we replace one of its elements with another sub-conversation randomly sampled from the training corpus to form a negative pair. Formally, given two sub-conversations $c_i$ and $c_j$, utterances in each sub-conversation are first concatenated respectively to form two segments. Then, the two segments are concatenated with a \texttt{[SEP]} token and a \texttt{[CLS]} token is inserted at the beginning of the whole sequence. This sequence are encoded by BERT to derive the contextualized representation for the \texttt{[CLS]} token. A non-linear transformation with sigmoid activation is further applied to this representation for calculating the matching score $m_{ij}$, i.e., the probability of $c_i$ and $c_j$ sharing the same parent node. Finally, the pre-training objective of this task is to minimize the cross-entropy loss as \begin{equation} \label{equ-snd-loss} \mathcal{L}_{snd} = - [ y_{ij} log(m_{ij}) + (1-y_{ij})log(1-m_{ij})], \end{equation} where $y_{ij} = 1$ if $c_i$ and $c_j$ share the same parent node and $y_{ij} = 0$ otherwise. \subsection{Multi-task Learning} In addition, we also adopt the tasks of masked language model (MLM) and next sentence prediction (NSP) in original BERT pre-training \cite{DBLP:conf/naacl/DevlinCLT19}, which have been proven effective for incorporating domain knowledge \cite{DBLP:conf/cikm/GuLLLSWZ20,DBLP:conf/acl/GururanganMSLBD20}. Finally, MPC-BERT is trained by performing multi-task learning that minimizes the sum of all loss functions as \begin{equation} \begin{aligned} \mathcal{L} = \mathcal{L}_{rur} & + \mathcal{L}_{iss} + \mathcal{L}_{pcd} + \mathcal{L}_{msur} \\ & + \mathcal{L}_{snd} + \mathcal{L}_{mlm} + \mathcal{L}_{nsp}. \end{aligned} \end{equation} \section{Downstream Tasks} \subsection{Addressee Recognition} Given a multi-party conversation where part of the addressees are unknown, \citet{DBLP:conf/emnlp/OuchiT16} and \citet{DBLP:conf/aaai/ZhangLPR18} recognized an addressee of the last utterance. \citet{DBLP:conf/emnlp/LeHSYBZY19} recognized addressees of all utterances in a conversation. In this paper, we follow the more challenging setting in \citet{DBLP:conf/emnlp/LeHSYBZY19}. Formally, models are asked to predict $\{\hat{a}_n\}_{n=1}^{N}$ given $\{(s_n,u_n,a_n)\}_{n=1}^N \backslash \{a_n\}_{n=1}^{N}$, where $\hat{a}_n$ is selected from the interlocutor set in this conversation and $\backslash$ denotes exclusion. When applying MPC-BERT, this task is reformulated as finding a preceding utterance from the same addressee. Its RUR matching scores with all preceding utterances are calculated following Eq.~(\ref{equ-rur}). Then, the utterance with the highest score is selected and the speaker of the selected utterance is considered as the recognized addressee. Finally, the fine-tuning objective of this task is to minimize the cross-entropy loss as \begin{equation} \mathcal{L}_{ar} = - \sum_{i=2}^N \sum_{j=1}^{i-1} y_{ij} ~ log(m_{ij}), \end{equation} where $m_{ij}$ is defined in Eq.~(\ref{equ-rur}), $y_{ij} = 1$ if the speaker of U$_j$ is the addressee of U$_i$ and $y_{ij} = 0$ otherwise. \subsection{Speaker Identification} This task aims to identify the speaker of the last utterance in a conversation. Formally, models are asked to predict $\hat{s}_N$ given $\{(s_n,u_n,a_n)\}_{n=1}^N \backslash s_N$, where $\hat{s}_N$ is selected from the interlocutor set in this conversation. When applying MPC-BERT, this task is reformulated as identifying the utterances sharing the same speaker. For the last utterance U$_N$, its speaker embedding is masked and its ISS matching scores $m_{Nj}$ with all preceding utterances are calculated following Section \ref{sec_iss}. The fine-tuning objective of this task is to minimize the cross-entropy loss as \begin{equation} \mathcal{L}_{si} = - \sum_{j=1}^{N-1} y_{Nj} ~ log(m_{Nj}), \end{equation} where $y_{Nj} = 1$ if U$_j$ shares the same speaker with U$_N$ and $y_{Nj} = 0$ otherwise. \subsection{Response Selection} This task asks models to select $\hat{u}_N$ from a set of response candidates given the conversation context $\{(s_n,u_n,a_n)\}_{n=1}^N \backslash u_N$. The key is to measure the similarity between two segments of context and response. We concatenate each response candidate with the context and extract the contextualized representation \textbf{e}$_{\texttt{[CLS]}}$ for the first \texttt{[CLS]} token using MPC-BERT. Then, \textbf{e}$_{\texttt{[CLS]}}$ is fed into a non-linear transformation with sigmoid activation to obtain the matching score between the context and the response. Finally, the fine-tuning objective of this task is to minimize the cross-entropy loss according to the true/false labels of responses in the training set as \begin{equation} \mathcal{L}_{rs} = - [ y log(m_{cr}) + (1-y)log(1-m_{cr})] , \end{equation} where $y = 1$ if the response $r$ is a proper one for the context $c$; otherwise $y = 0$. \section{Experiments} \begin{table}[t \small \centering \setlength{\tabcolsep}{2.4pt} \begin{tabular}{c|c|c|c|c} \toprule \multicolumn{2}{c|}{Datasets} & Train & Valid & Test \\ \hline \multicolumn{2}{c|}{\citet{DBLP:conf/ijcai/HuCL0MY19}} & 311,725 & 5,000 & 5,000 \\ \hline \multirow{3}{*}{\citet{DBLP:conf/emnlp/OuchiT16}} & Len-5 & 461,120 & 28,570 & 32,668 \\ & Len-10 & 495,226 & 30,974 & 35,638 \\ & Len-15 & 489,812 & 30,815 & 35,385 \\ \bottomrule \end{tabular} \caption{Statistics of the two benchmarks evaluated in this paper.} \label{tab-data} \end{table} \begin{table*}[t \centering \setlength{\tabcolsep}{5.0pt} \begin{tabular}{l|c|c|c|c|c|c|c|c} \toprule & \multicolumn{2}{c|}{\citet{DBLP:conf/ijcai/HuCL0MY19}} & \multicolumn{6}{c}{\citet{DBLP:conf/emnlp/OuchiT16}} \\ \cline{2-9} & \multicolumn{2}{c|}{} & \multicolumn{2}{c|}{Len-5} & \multicolumn{2}{c|}{Len-10} & \multicolumn{2}{c}{Len-15} \\ \cline{2-9} & P@1 & Acc. & P@1 & Acc. & P@1 & Acc. & P@1 & Acc. \\ \hline Preceding \cite{DBLP:conf/emnlp/LeHSYBZY19} & - & - & 63.50 & 40.46 & 56.84 & 21.06 & 54.97 & 13.08 \\ Subsequent \cite{DBLP:conf/emnlp/LeHSYBZY19} & - & - & 61.03 & 40.25 & 54.57 & 20.26 & 53.07 & 12.79 \\ DRNN \cite{DBLP:conf/emnlp/OuchiT16} & - & - & 72.75 & 58.18 & 65.58 & 34.47 & 62.60 & 22.58 \\ SIRNN \cite{DBLP:conf/aaai/ZhangLPR18} & - & - & 75.98 & 62.06 & 70.88 & 40.66 & 68.13 & 28.05 \\ W2W \cite{DBLP:conf/emnlp/LeHSYBZY19} & - & - & 77.55 & 63.81 & 73.52 & 44.14 & 73.42 & 34.23 \\ \hline BERT \cite{DBLP:conf/naacl/DevlinCLT19} & 96.16 & 83.50 & 85.95 & 75.99 & 83.41 & 58.22 & 81.09 & 44.94 \\ SA-BERT \cite{DBLP:conf/cikm/GuLLLSWZ20} & 97.12 & 88.91 & 86.81 & 77.45 & 84.46 & 60.30 & 82.84 & 47.23 \\ MPC-BERT & \textbf{98.31} & \textbf{92.42} & \textbf{88.73} & \textbf{80.31} & \textbf{86.23} & \textbf{63.58} & \textbf{85.55} & \textbf{52.59} \\ \hline MPC-BERT w/o. RUR & 97.75 & 89.98 & 87.51 & 78.42 & 85.63 & 62.26 & 84.78 & 50.83 \\ MPC-BERT w/o. ISS & 98.20 & 91.96 & 88.67 & 80.25 & 86.14 & 63.40 & 85.02 & 51.12 \\ MPC-BERT w/o. PCD & 98.20 & 91.90 & 88.51 & 80.06 & 85.92 & 62.84 & 85.21 & 51.17 \\ MPC-BERT w/o. MSUR & 98.08 & 91.32 & 88.70 & 80.26 & 86.21 & 63.46 & 85.28 & 51.23 \\ MPC-BERT w/o. SND & 98.25 & 92.18 & 88.68 & 80.25 & 86.14 & 63.41 & 85.29 & 51.39 \\ \bottomrule \end{tabular} \caption{Evaluation results of addressee recognition on the test sets. Results except ours are cited from \citet{DBLP:conf/emnlp/LeHSYBZY19}. Numbers in bold denote that the improvement over the best performing baseline is statistically significant (t-test with \emph{p}-value $<$ 0.05).} \label{tab-ar} \end{table*} \begin{table*}[t \centering \begin{tabular}{l|c|c|c|c} \toprule & \multicolumn{1}{c|}{\citet{DBLP:conf/ijcai/HuCL0MY19}} & \multicolumn{3}{c}{\citet{DBLP:conf/emnlp/OuchiT16}} \\ \cline{2-5} & & Len-5 & Len-10 & Len-15 \\ \hline BERT \cite{DBLP:conf/naacl/DevlinCLT19} & 71.81 & 62.24 & 53.17 & 51.58 \\ SA-BERT \cite{DBLP:conf/cikm/GuLLLSWZ20} & 75.88 & 64.96 & 57.62 & 54.28 \\ MPC-BERT & \textbf{83.54} & \textbf{67.56} & \textbf{61.00} & \textbf{58.52} \\ \hline MPC-BERT w/o. RUR & 82.48 & 66.88 & 60.12 & 57.33 \\ MPC-BERT w/o. ISS & 77.95 & 66.77 & 60.03 & 56.73 \\ MPC-BERT w/o. PCD & 83.39 & 67.12 & 60.62 & 58.00 \\ MPC-BERT w/o. MSUR & 83.51 & 67.21 & 60.76 & 58.03 \\ MPC-BERT w/o. SND & 83.47 & 67.04 & 60.44 & 58.12 \\ \bottomrule \end{tabular} \caption{Evaluation results of speaker identification on the test sets in terms of P@1. Numbers in bold denote that the improvement over the best performing baseline is statistically significant (t-test with \emph{p}-value $<$ 0.05).} \label{tab-si} \end{table*} \begin{table*}[t \centering \setlength{\tabcolsep}{4.0pt} \begin{tabular}{l|c|c|c|c|c|c|c|c} \toprule & \multicolumn{2}{c|}{\citet{DBLP:conf/ijcai/HuCL0MY19}} & \multicolumn{6}{c}{\citet{DBLP:conf/emnlp/OuchiT16}} \\ \cline{2-9} & \multicolumn{2}{c|}{} & \multicolumn{2}{c|}{Len-5} & \multicolumn{2}{c|}{Len-10} & \multicolumn{2}{c}{Len-15} \\ \cline{2-9} & R$_2@1$ & R$_{10}@1$ & R$_2@1$ & R$_{10}@1$ & R$_2@1$ & R$_{10}@1$ & R$_2@1$ & R$_{10}@1$ \\ \hline DRNN \cite{DBLP:conf/emnlp/OuchiT16} & - & - & 76.07 & 33.62 & 78.16 & 36.14 & 78.64 & 36.93 \\ SIRNN \cite{DBLP:conf/aaai/ZhangLPR18} & - & - & 78.14 & 36.45 & 80.34 & 39.20 & 80.91 & 40.83 \\ \hline BERT \cite{DBLP:conf/naacl/DevlinCLT19} & 92.48 & 73.42 & 85.52 & 53.95 & 86.93 & 57.41 & 87.19 & 58.92 \\ SA-BERT \cite{DBLP:conf/cikm/GuLLLSWZ20} & 92.98 & 75.16 & 86.53 & 55.24 & 87.98 & 59.27 & 88.34 & 60.42 \\ MPC-BERT & \textbf{94.90} & \textbf{78.98} & \textbf{87.63} & \textbf{57.95} & \textbf{89.14} & \textbf{61.82} & \textbf{89.70} & \textbf{63.64} \\ \hline MPC-BERT w/o. RUR & 94.48 & 78.16 & 87.20 & 57.56 & 88.96 & 61.47 & 89.07 & 63.24 \\ MPC-BERT w/o. ISS & 94.58 & 78.82 & 87.54 & 57.77 & 88.98 & 61.76 & 89.58 & 63.51 \\ MPC-BERT w/o. PCD & 94.66 & 78.70 & 87.50 & 57.51 & 88.75 & 61.62 & 89.45 & 63.46 \\ MPC-BERT w/o. MSUR & 94.36 & 78.22 & 87.11 & 57.58 & 88.59 & 61.05 & 89.25 & 63.20 \\ MPC-BERT w/o. SND & 93.92 & 76.96 & 87.30 & 57.54 & 88.77 & 61.54 & 89.27 & 63.34 \\ \bottomrule \end{tabular} \caption{Evaluation results of response selection on the test sets. Results except ours are cited from \citet{DBLP:conf/emnlp/OuchiT16} and \citet{DBLP:conf/aaai/ZhangLPR18}. Numbers in bold denote that the improvement over the best performing baseline is statistically significant (t-test with \emph{p}-value $<$ 0.05).} \label{tab-rs} \end{table*} \subsection{Datasets} We evaluated our proposed methods on two Ubuntu IRC benchmarks. One was released by \citet{DBLP:conf/ijcai/HuCL0MY19}, in which both speaker and addressee labels was provided for each utterance. The other benchmark was released by \citet{DBLP:conf/emnlp/OuchiT16}. Here, we adopted the version shared in \citet{DBLP:conf/emnlp/LeHSYBZY19} for fair comparison. The conversation sessions were separated into three categories according to the session length (Len-5, Len-10 and Len-15) following the splitting strategy of previous studies \cite{DBLP:conf/emnlp/OuchiT16,DBLP:conf/aaai/ZhangLPR18,DBLP:conf/emnlp/LeHSYBZY19}. Table~\ref{tab-data} presents the statistics of the two benchmarks evaluated in our experiments. \subsection{Baseline Models} \paragraph{Non-pre-training-based models} \citet{DBLP:conf/emnlp/OuchiT16} proposed a dynamic model DRNN which updated speaker embeddings with the conversation flow. \citet{DBLP:conf/aaai/ZhangLPR18} improved DRNN to SI-RNN which updated speaker embeddings role-sensitively. \citet{DBLP:conf/emnlp/LeHSYBZY19} proposed W2W which jointly modeled interlocutors and utterances in a uniform framework, and predicted all addressees. \paragraph{Pre-training-based models} BERT \cite{DBLP:conf/naacl/DevlinCLT19} was pre-trained to learn general language representations with MLM and NSP tasks. SA-BERT \cite{DBLP:conf/cikm/GuLLLSWZ20} added speaker embeddings and further pre-trained BERT on a domain-specific corpus to incorporate domain knowledge. We re-implemented SA-BERT with the pre-training corpus used in this paper to ensure fair comparison. \begin{figure*}[t \centering \subfigure[Addressee recognition]{ \includegraphics[width=5cm]{figures/trend-addresse.pdf}} \subfigure[Speaker identification]{ \includegraphics[width=5cm]{figures/trend-speaker.pdf}} \subfigure[Response selection]{ \includegraphics[width=5cm]{figures/trend-response.pdf}} \caption{Performance of models under different session lengths on the test sets of \citet{DBLP:conf/emnlp/OuchiT16} on the tasks of (a) addressee recognition, (b) speaker identification and (c) response selection. } \label{fig-analysis} \end{figure*} \subsection{Implementation Details} \label{sec-details} The version of BERT-base-uncased was adopted for all our experiments. For pre-training, \texttt{GELU} \cite{DBLP:journals/corr/HendrycksG16} was employed as the activation for all non-linear transformations. The Adam method \cite{DBLP:journals/corr/KingmaB14} was employed for optimization. The learning rate was initialized as 0.00005 and the warmup proportion was set to 0.1. We pre-trained BERT for 10 epochs. The training set of the dateset used in \citet{DBLP:conf/ijcai/HuCL0MY19} was employed for pre-training. The maximum utterance number was set to 7. The maximum sequence length was set to 230. The maximum sampling numbers for each example were set to 4 for RUR, 2 for ISS and 2 for PCD. $\Delta$ in Eq.~(\ref{equ-pcd}) was set to 0.4, achieving the best performance out of \{0.2, 0.4, 0.6, 0.8\} on the validation set. The pre-training was performed using a GeForce RTX 2080 Ti GPU and the batch size was set to 4. For fine-tuning, some configurations were different according to the characteristics of these datasets. For \citet{DBLP:conf/ijcai/HuCL0MY19}, the maximum utterance number was set to 7 and the maximum sequence length was set to 230. For the three experimental settings in \citet{DBLP:conf/emnlp/OuchiT16}, the maximum utterance numbers were set to 5, 10 and 15, and the maximum sequence lengths were set to 120, 220 and 320. All parameters in PLMs were updated. The learning rate was initialized as 0.00002 and the warmup proportion was set to 0.1. For \citet{DBLP:conf/ijcai/HuCL0MY19}, the fine-tuning process was performed for 10 epochs for addressee recognition, 10 epochs for speaker identification, and 5 epochs for response selection. For \citet{DBLP:conf/emnlp/OuchiT16}, the fine-tuning epochs were set to 5, 5 and 3 respectively. The fine-tuning was also performed using a GeForce RTX 2080 Ti GPU. The batch sizes were set to 16 for \citet{DBLP:conf/ijcai/HuCL0MY19}, and 40, 20, and 12 for the three experimental settings in \citet{DBLP:conf/emnlp/OuchiT16} respectively. The validation set was used to select the best model for testing. All codes were implemented in the TensorFlow framework \cite{DBLP:conf/osdi/AbadiBCCDDDGIIK16} and are published to help replicate our results.~\footnote{https://github.com/JasonForJoy/MPC-BERT} \subsection{Metrics and Results} \paragraph{Addressee recognition} We followed the metrics of previous work \cite{DBLP:conf/emnlp/LeHSYBZY19} by employing precision@1 (P@1) to evaluate each utterance with ground truth. Also, a session is marked as positive if the addressees of all its utterances are correctly recognized, which is calculated as accuracy (Acc.). Table~\ref{tab-ar} presents the results of addressee recognition. It shows that MPC-BERT outperforms the best performing model, i.e., SA-BERT, by margins of 3.51\%, 2.86\%, 3.28\% and 5.36\% on these test sets respectively in terms of Acc., verifying the effectiveness of the proposed five self-supervised tasks as a whole. To further illustrate the effectiveness of each task, ablation tests were performed as shown in the last five rows of Table~\ref{tab-ar}. We can observe that all self-supervised tasks are useful as removing any of them causes performance drop. Among the five tasks, RUR plays the most important role, and the tasks focusing on modeling interlocutor structure contribute more than those for utterance semantics. \paragraph{Speaker identification} Similarly, P@1 was employed as the evaluation metric of speaker identification for the last utterance of a conversation and the results are shown in Table~\ref{tab-si}. It shows that MPC-BERT outperforms SA-BERT by margins of 7.66\%, 2.60\%, 3.38\% and 4.24\% respectively in terms of P@1. Besides, from the ablation results we find that all tasks are useful for improving the performance of speaker identification and ISS and RUR contribute the most. In particular, removing PCD, MSUR and SND only leads to slight performance drop. The reason might be that the information conveyed by these tasks is redundant. \paragraph{Response selection} The R$_n@k$ metrics adopted by previous studies \cite{DBLP:conf/emnlp/OuchiT16,DBLP:conf/aaai/ZhangLPR18} were used here. Each model was tasked with selecting $k$ best-matched responses from $n$ available candidates, and we calculated the recall as R$_n@k$. Two settings were followed in which \emph{k} was set to 1 and \emph{n} was set to 2 or 10. Table~\ref{tab-rs} presents the results of response selection. It shows that MPC-BERT outperforms SA-BERT by margins of 3.82\%, 2.71\%, 2.55\% and 3.22\% respectively in terms of R$_{10}@1$. Ablation tests show that SND is the most useful task for response selection and the two tasks focusing on the utterance semantics contribute more than those focusing on the interlocutor structures. \subsection{Discussions} Figure~\ref{fig-analysis} illustrates how the performance of BERT, SA-BERT and MPC-BERT changed with respect to different session lengths on the test sets of \citet{DBLP:conf/emnlp/OuchiT16}. It can be seen that the performance of addressee recognition and speaker identification dropped as the session length increased. The reason might be that longer sessions always contain more interlocutors which increase the difficulties of predicting interlocutors. Meanwhile, the performance of response selection was significantly improved as the session length increased. It can be attributed to that longer sessions enrich the representations of contexts with more details which benefit response selection. Furthermore, as the session length increased, the performance of MPC-BERT dropped more slightly than that of SA-BERT on addressee recognition and speaker identification, and the R$_{10}@1$ gap between MPC-BERT and SA-BERT on response selection enlarged from 2.71\% to 3.22\%. These results imply the superiority of MPC-BERT over SA-BERT on modeling long MPCs with complicated structures. \section{Conclusion} In this paper, we present MPC-BERT, a pre-trained language model with five self-supervised tasks for MPC understanding. These tasks jointly learn \emph{who} says \emph{what} to \emph{whom} in MPCs. Experimental results on three downstream tasks show that MPC-BERT outperforms previous methods by large margins and achieves new state-of-the-art performance on two benchmarks. \section*{Acknowledgments} We thank anonymous reviewers for their valuable comments. \bibliographystyle{acl_natbib}
{'timestamp': '2021-06-04T02:08:05', 'yymm': '2106', 'arxiv_id': '2106.01541', 'language': 'en', 'url': 'https://arxiv.org/abs/2106.01541'}
arxiv
\section{Introduction} \label{sec:Intro} Temporal Knowledge Graphs (Temporal KGs) are multi-relational graph where each edge is associated with a time duration. This is in contrast to a regular KG where no time annotation is present. For example, a regular KG may contain a fact such as (\textit{Barack Obama}, \textit{held position}, \textit{President of USA}), while a temporal KG would contain the start and end time as well --- (\textit{Barack Obama}, \textit{held position}, \textit{President of USA}, \textit{2008}, \textit{2016}). Edges may be associated with a set of non-contiguous time intervals as well. These temporal scopes on facts can be either automatically estimated \cite{talukdar2012coupled} or user contributed. Several such Temporal KGs have been proposed in the literature, where the focus is on KG completion (\citealt{dasgupta-etal-2018-hyte}; \citealt{garcia-duran-etal-2018-learning}; \citealt{leetaru2013gdelt}; \citealt{lacroix2020tntcomplex}; \citealt{jain-etal-2020-temporal}). The task of Knowledge Graph Question Answering (KGQA) is to answer natural language questions using a KG as the knowledge base. This is in contrast to reading comprehension-based question answering, where typically the question is accompanied by a context (e.g., text passage) and the answer is either one of multiple choices \citep{rajpurkar2016squad} or a piece of text from the context \citep{yang2018hotpotqa}. In KGQA, the answer is usually an entity (node) in the KG, and the reasoning required to answer questions is either single-fact based \citep{bordes2015large}, multi-hop (\citealt{yih-etal-2015-semantic}, \citealt{zhang2017variational}) or conjunction/comparison based reasoning \citep{talmor-berant-2018-web}. Temporal KGQA takes this a step further where: \begin{enumerate} \item The underlying KG is a Temporal KG. \item The answer is either an entity or time duration. \item Complex temporal reasoning might be needed. \end{enumerate} \vspace{1mm} KG Embeddings are low-dimensional dense vector representations of entities and relations in a KG. Several methods have been proposed in the literature to embed KGs (\citealt{bordes2013translating}, \citealt{trouillon2016complex}, \citealt{vashishth2020interacte}). These embeddings were originally proposed for the task of KG completion i.e., predicting missing edges in the KG, since most real world KGs are incomplete. Recently, however, they have also been applied to the task of KGQA where they have been shown to increase performance the settings of both of complete and incomplete KGs (\citealt{saxena-etal-2020-improving}; \citealt{sun2020faithful}). Temporal KG embeddings are another upcoming area where entities, relations and timestamps in a temporal KG are embedded in a low-dimensional vector space (\citealt{dasgupta-etal-2018-hyte}, \citealt{lacroix2020tntcomplex}, \citealt{jain-etal-2020-temporal}, \citealt{goel2019diachronic}). Here too, the main application so far has been temporal KG completion. In our work, we investigate whether temporal KG Embeddings can be applied to the task of Temporal KGQA, and how they fare compared to non-temporal embeddings or off-the-shelf methods without any KG Embeddings. In this paper we propose \textsc{CronQuestions}{}, a new dataset for Temporal KGQA. \textsc{CronQuestions}{} consists of both a temporal KG and accompanying natural language questions. There were three main guiding principles while creating this dataset: \begin{enumerate} \item The associated KG must provide temporal annotations. \item Questions must involve an element of temporal reasoning. \item The number of labeled instances must be large enough that it can be used for training models, rather than for evaluation alone. \end{enumerate} Guided by the above principles, we present a dataset consisting of a Temporal KG with 125k entities and 328k facts, along with a set of 410k natural language questions that require temporal reasoning. On this new dataset, we apply approaches based on deep language models (LM) alone, such as T5 \citep{raffel2020exploring}, BERT \citep{devlin2019bert}, and KnowBERT \citep{peters2019knowledge}, and also hybrid LM+KG embedding approaches, such as Entities-as-Experts \citep{fevry2020entexperts} and EmbedKGQA \citep{saxena-etal-2020-improving}. We find that these baselines are not suited to temporal reasoning. In response, we propose \textsc{CronKGQA}{}, an enhancement of EmbedKGQA, which outperforms baselines across all question types. \textsc{CronKGQA}{} achieves very high accuracy on simple temporal reasoning questions, but falls short when it comes to questions requiring more complex reasoning. Thus, although we get promising early results, \textsc{CronQuestions}{} leaves ample scope to improve complex Temporal KGQA. \ifaclfinal Our source code along with the \textsc{CronQuestions}{} dataset can be found at \url{https://github.com/apoorvumang/CronKGQA}. \else Our dataset \textsc{CronQuestions}{} along with source code to reproduce results is available in the supplementary material. \fi \input{example-question-table} \section{Related work} \subsection{Temporal QA data sets} \label{sec:temporal-qa-datasets} There have been several KGQA datasets proposed in the literature (Table~\ref{tab:tick-table}). In Simple\-Questions \citep{bordes2015large} one needs to extract just a single fact from the KG to answer a question. MetaQA \citep{zhang2017variational} and Web\-Questions\-SP \citep{yih-etal-2015-semantic} require multi-hop reasoning, where one must traverse over multiple edges in the KG to reach the answer. Complex\-Web\-Questions \citep{talmor-berant-2018-web} contains both multi-hop and conjunction/comparison type questions. However, none of these are aimed at temporal reasoning, and the KG they are based on is non-temporal. Temporal QA datasets have mostly been studied in the area of reading comprehension. One such dataset is TORQUE \citep{ning2020torque}, where the system is given a question along with some context (a text passage) and is asked to answer a multiple choice question with five choices. This is in contrast to KGQA, where there is no context, and the answer is one of potentially hundreds of thousands of entities. TempQuestions \citep{tempquestions2018} is a KGQA dataset specifically aimed at temporal QA. It consists of a subset of questions from Web\-Questions, Free917 \citep{cai-yates-2013-large} and Complex\-Questions \citep{bao-etal-2016-constraint} that are temporal in nature. They gave a definition for ``temporal question" and used certain trigger words (for example `before', `after') along with other constraints to filter out questions from these datasets that fell under this definition. However, this dataset contains only 1271 questions --- useful only for evaluation --- and the KG on which it is based (a subset of FreeBase \citep{freebase2008}) is not a temporal KG. Another drawback is that FreeBase has not been under active development since 2015, therefore some information stored in it is outdated and this is a potential source of inaccuracy. \subsection{Temporal QA algorithms} To the best of our knowledge, recent KGQA algorithms (\citealt{miller2016kvmnet}; \citealt{sun2019pullnet}; \citealt{cohen2020scalable}; \citealt{sun2020faithful}) work with \textit{non-temporal KGs}, i.e., KGs containing facts of the form (subject, relation, object). Extending these to \textit{temporal KGs} containing facts of the form (subject, relation, object, start time, end time) is a non-trivial task. TEQUILA \citep{Jia_2018} is one method aimed specifically at temporal KGQA. TEQUILA decomposes and rewrites the question into non-temporal sub-questions and temporal constraints. Answers to sub-questions are then retrieved using any KGQA engine. Finally, TEQUILA uses constraint reasoning on temporal intervals to compute final answers to the full question. A major drawback of this approach is the use of pre-specified templates for decomposition, as well as the assumption of having temporal constraints on entities. Also, since it is made for non-temporal KGs, there is no direct way of applying it to temporal KGs where facts are temporally scoped. \section{\textsc{CronQuestions}{}: The new Temporal KGQA dataset} \textsc{CronQuestions}{}, our Temporal KGQA dataset consists of two parts: a KG with temporal annotations, and a set of natural language questions requiring temporal reasoning. \subsection{Temporal KG} To prepare our temporal KG, we started by taking all facts with temporal annotations from the WikiData subset proposed by \citet{lacroix2020tntcomplex}. We removed some instances of the predicate ``\textit{member of sports team}'' in order to balance out the KG since this predicate constituted over 50 percent of the facts. Timestamps were discretized to years. This resulted in a KG with 323k facts, 125k entities and 203 relations. However, this filtering of facts misses out on important world events. For example, the KG subset created using the aforementioned technique contains the entity \textit{World War II} but no associated fact that tells us when \textit{World War II} started or ended. This knowledge is needed to answer questions such as ``\textit{Who was the President of the USA during World War II?}.'' To overcome this shortcoming, we first extracted entities from WikiData that have a ``start time'' and ``end time'' annotation. From this set, we then removed entities which were game shows, movies or television series (since these are not important world events, but do have a start and end time annotation), and then removed entities with less than 50 associated facts. This final set of entitities was then added as facts in the format (\textit{WWII, significant event, occurred, 1939, 1945)}. The final Temporal KG consisted of 328k facts out of which 5k are event-facts. \begin{table}[t!] \resizebox{\columnwidth}{!}{% \begin{tabular}{l|l} Template & \textit{When did \{head\} play in \{tail\}} \\ \hline Seed Qn & \textit{When did \textbf{Messi} play in \textbf{FC Barcelona}} \\ \hline \makecell{Human \\ Paraphrases} & \makecell[l]{ \textit{When was \textbf{Messi} playing in \textbf{FC Barcelona}} \\ \textit{Which years did \textbf{Messi} play in \textbf{FC Barcelona}} \\ \textit{When did \textbf{FC Barcelona} have \textbf{Messi} in their team} \\ \textit{What time did \textbf{Messi} play in \textbf{FC Barcelona}} \\ } \\ \hline \makecell{Machine \\ Paraphrases} & \makecell[l]{ \textit{When did \textbf{Messi} play for \textbf{FC Barcelona}} \\ \textit{When did \textbf{Messi} play at \textbf{FC Barcelona}} \\ \textit{When has \textbf{Messi} played at \textbf{FC Barcelona}} } \end{tabular} } \caption{Slot-filled paraphrases generated by humans and machine. Please refer to Section~\ref{sec:making-temporal-questions} for details.} \label{tab:pp} \end{table} \begin{table}[t!] \resizebox{\columnwidth}{!}{% \begin{tabular}{l|rrr} \hline & \multicolumn{1}{l}{\textbf{Train}} & \multicolumn{1}{l}{\textbf{Dev}} & \multicolumn{1}{l}{\textbf{Test}} \\ \hline Simple Entity & 90,651 & 7,745 & 7,812 \\ Simple Time & 61,471 & 5,197 & 5,046 \\ Before/After & 23,869 & 1,982 & 2,151 \\ First/Last & 118,556 & 11,198 & 11,159 \\ Time Join & 55,453 & 3,878 & 3,832 \\ \hline Entity Answer & 225,672 & 19,362 & 19,524 \\ Time Answer & 124,328 & 10,638 & 10,476 \\ \hline \textbf{Total} & \multicolumn{1}{l}{350,000} & \multicolumn{1}{l}{30,000} & \multicolumn{1}{l}{30,000} \\ \hline \end{tabular} } \caption{Number of questions in our dataset across different types of reasoning required and different answer types. Please refer to Section~\ref{sec:question-categorization} for details.} \label{tab:dataset-stats-questions} \end{table} \subsection{Temporal Questions} \label{sec:making-temporal-questions} To generate the QA dataset, we started with a set of templates for temporal reasoning. These were made using the five most frequent relations from our WikiData subset, namely \begin{itemize} \item \textit{member of sports team} \item \textit{position held} \item \textit{award received} \item \textit{spouse} \item \textit{employer} \end{itemize} This resulted in 30 unique seed templates over five relations and five different reasoning structures (please see Table~\ref{tab:template} for some examples). Each of these templates has a corresponding procedure that could be executed over the temporal KG to extract all possible answers for that template. However, similar to \citet{zhang2017variational}, we chose not to make this procedure a part of the dataset, to remove unwelcome dependence of QA systems on such formal candidate collection methods. This also allows easy augmentation of the dataset, since only question-answer pairs are needed. In the same spirit as ComplexWebQuestions, we then asked human annotators to paraphrase these templates in order to generate more linguistic diversity. Annotators were given slot-filled templates with dummy entities and times, and asked to rephrase the question such that the dummy entities/times were present in the paraphrase and the question meaning did not change. This resulted in 246 unique templates. We then used the monolingual paraphraser developed by \citet{N18-1007} to automatically generate paraphrases using these 246 templates. After verifying their correctness through annotators, we ended up with 654 templates. These templates were then filled using entity aliases from WikiData to generate 410k unique question-answer pairs. Finally, while splitting the data into train/test folds, we ensured that \begin{enumerate} \item Paraphrases of train questions are not present in test questions. \item There is no entity overlap between test questions and train questions. Event overlap is allowed. \end{enumerate} The second requirement implies that, if the question ``\textit{Who was president before Obama}'' is present in the train set, the test set cannot contain any question that mentions the entity `\textit{Obama}'. While this policy may appear like an overabundance of caution, it ensures that models are doing temporal reasoning rather than guessing from entities seen during training. \citet{lewis2020question} noticed an issue in WebQuestions where they found that almost 30\% of test questions overlapped with training questions. The issue has been seen in the MetaQA dataset as well, where there is significant overlap between test/train entities and test/train question paraphrases, leading to suspiciously high performance on baseline methods even with partial KG data \citep{saxena-etal-2020-improving}, which suggests that models that apparently perform well are not necessarily performing the desired reasoning over the KG. A drawback of our data creation protocol is that question/answer pairs are generated automatically. Therefore, the question distribution is artificial from a semantic perspective. (Complex\-Web\-Questions has a similar limitation.) However, since developing models that are capable of temporal reasoning is an important direction for natural language understanding, we feel that our dataset provides an opportunity to both train and evaluate KGQA models because of its large size, notwithstanding its lower-than-natural linguistic variety. In Section~\ref{sec:training-data-size-effect}, we show the effect that training data size has on model performance. Summarizing, each of our examples contains \begin{enumerate} \item A paraphrased natural language question. \item A set of entities/times in the question. \item A set of `gold' answers (entity or time). \end{enumerate} The entities are specified as WikiData IDs (e.g., \textit{Q219237}), and times are years (e.g., \textit{1991}). We include the set of entities/times in the test questions as well since similar to other KGQA datasets (MetaQA, WebQuestions, ComplexWebQuestions) and methods that use these datasets (PullNet, EmQL), entity linking is considered as a separate problem and complete entity linking is assumed. We also include the seed template and head/tail/time annotation in the train fold, but omit these from the test fold. \begin{figure*} \centering \includegraphics[width=\textwidth, trim={0.6cm 0 0.4cm 0},clip ]{cronkgqa_linear.pdf} \caption{The \textsc{CronKGQA}{} method. (i)~A temporal KG embedding model (Section \ref{sec:temporal-kg-embeddings}) is used to generate embeddings for each timestamp and entity in the temporal knowledge graph (ii)~BERT is used to get two question embeddings: $\bm{qe}_{ent}$ and $\bm{qe}_{time}$. (iii)~Embeddings of entity/time mentions in the question are combined with question embeddings using equations \ref{eqn:ent-score} and \ref{eqn:time-score} to get score vectors for entity and time prediction. (iv)~Score vectors are concatenated and softmax is used get answer probabilities. Please refer to Section \ref{sec:TembedKGQA} for details.} \label{fig:our-model} \end{figure*} \subsubsection{Question Categorization} \label{sec:question-categorization} In order to aid analysis, we categorize questions into ``simple reasoning'' and ``complex reasoning'' questions (please refer to Table~\ref{tab:dataset-stats-questions} for the distribution statistics). \begin{description} \item[Simple reasoning:] These questions require a single fact to answer, where the answer can be either an entity or a time instance. For example the question \textit{``Who was the President of the United States in 2008?"} requires a single fact to answer the question, namely (\textit{Barack Obama}, \textit{held position}, \textit{President of USA}, \textit{2008}, \textit{2016}) \item[Complex reasoning:] These questions require multiple facts to answer and can be more varied. For example \textit{``Who was the first President of the United States?"} This requires reasoning over multiple facts pertaining to the entity \textit{``President of the United States''}. In our dataset, all questions that are not ``simple reasoning'' questions are considered complex questions. These are further categorized into the types ``before/after`', ``first/last'' and ``time join'' --- please refer Table~\ref{tab:template} for examples of these questions. \end{description} \section{Temporal KG Embeddings} \label{sec:temporal-kg-embeddings} We investigate how we can use KG embeddings, both temporal and non-temporal, along with pre-trained language models to perform temporal KGQA. We will first briefly describe the specific KG embedding models we use, and then go on to show how we use them in our QA models. In all cases, the scores are turned into suitable losses with regard to positive and negative tuples in an incomplete KG, and these losses minimized to train the entity, time and relation representations. \subsection{ComplEx} \label{sec:complex} ComplEx \citep{trouillon2016complex} represents each entity $e$ as a complex vector $\bm{u}_e\in\mathbb{C}^D$. Each relation $r$ is represented as a complex vector $\bm{v}_r\in\mathbb{C}^D$ as well. The score $\phi$ of a claimed fact $(s,r,o)$ is \begin{align} \phi(s,r,o) &= \Re(\langle \bm{u}_s, \bm{v}_r, \bm{u}_o^\star \rangle) \notag \\ &= \Re\big(\textstyle\sum_{d=1}^D \bm{u}_s[d] \bm{v}_r[d] \bm{u}_o[d]^\star \big) \label{eqn:complex} \end{align} where $\Re(\cdot)$ denotes the real part and $c^\star$ is the complex conjugate. Despite further developments, ComplEx, along with refined training protocols \citep{lacroix2018canonical} remains among the strongest KB embedding approaches \citep{Ruffinelli2020You}. \subsection{TComplEx, TNTComplEx} \label{sec:tcomplex} \citet{lacroix2020tntcomplex} took an early step to extend ComplEx with time. Each timestamp $t$ is also represented as a complex vector $\bm{w}_t\in\mathbb{C}^D$. For a claimed fact $(s, r, o, t)$, their TComplEx scoring function is \begin{equation} \begin{aligned} \phi(s,r,o, t) &= \Re(\langle \bm{u}_s, \bm{v}_r, \bm{u}_o^\star, \bm{w}_t \rangle) \end{aligned} \label{eqn:tcomplex} \end{equation} Their TNTComplEx scoring function uses two representations of relations $r$: $\bm{v}^\text{T}_r$, which is sensitive to time, and $\bm{v}_r$, which is not. The scoring function is the sum of a time-sensitive and a time-insensitive part: $\Re(\langle \bm{u}_s, \bm{v}^\text{T}_r, \bm{u}_o^\star, \bm{w}_t \rangle + \langle \bm{u}_s, \bm{v}_r, \bm{u}_o^\star, \mathbf{1} \rangle)$. \subsection{TimePlex} TimePlex \citep{jain-etal-2020-temporal} augmented ComplEx with embeddings $\bm{u}_t \in \mathbb{C}^D$ for discretized time instants~$t$. To incorporate time, TimePlex uses three representations for each relation $r$, viz., $(\bm{v}^\text{SO}_r, \bm{v}^\text{ST}_r, \bm{v}^\text{OT}_r)$ and writes the base score of a tuple $(s, r, o, t)$ as \begin{multline} \phi(s, r, o, t) = \langle \bm{u}_s, \bm{v}_r^\text{SO}, \bm{u}_o^\star\rangle + \alpha\,\langle \bm{u}_s, \bm{v}_r^\text{ST}, \bm{u}_t^\star\rangle \\ + \beta\, \langle \bm{u}_o, \bm{v}_r^\text{OT}, \bm{u}_t^\star\rangle + \gamma\,\langle \bm{u}_s, \bm{u}_o, \bm{u}_t^\star\rangle, \label{eqn:timeplex} \end{multline} where $\alpha,\beta,\gamma$ are hyperparameters. \section{\textsc{CronKGQA}{}: Our proposed method} \label{sec:TembedKGQA} We start with a temporal KG, apply a time-agnostic or time-sensitive KG embedding algorithm (ComplEx, TComplEx, or TimePlex) to it, and obtain entity, relation, and timestamp embeddings for the temporal KG. We will use the following notation. \begin{itemize} \item $\mathcal{E}$ is the matrix of entity embeddings \item $\mathcal{T}$ is the matrix of timestamp embeddings \item $\mathcal{E.T}$ is the concatenation of $\mathcal{E}$ and $\mathcal{T}$ matrices. This is used for scoring answers, since the answer can be either an entity or timestamp. \end{itemize} In case entity/timestamp embeddings are complex valued vectors in $\mathbb{C}^D$, we expand them to real valued vectors of size $2D$, where the first half is the real part and the second half is the complex part of the original vector. We first apply EmbedKGQA \citep{saxena-etal-2020-improving} directly to the task of Temporal KGQA. In its original implementation, EmbedKGQA uses ComplEx (Section \ref{sec:complex}) embeddings and can only deal with non-temporal KGs and single entity questions. In order to apply it to \textsc{CronQuestions}{}, we set the first entity encountered in the question as the ``\textit{head entity}'' needed by EmbedKGQA. Along with this, we set the entity embedding matrix $\mathcal{E}$ to be the ComplEx embedding of our KG entities, and initialize $\mathcal{T}$ to a random learnable matrix. EmbedKGQA then performs prediction over $\mathcal{E.T}$. Next, we modify EmbedKGQA so that it can use temporal KG embeddings. We use TComplEx (Section \ref{sec:tcomplex}) for getting entity and timestamp embeddings. \textsc{CronKGQA}{} (Figure \ref{fig:our-model}) utilizes two scoring functions, one for predicting entity and one for predicting time. Using a pre-trained LM (BERT in our case) \textsc{CronKGQA}{} finds a question embedding $\bm{qe}$. This is then projected to get two embeddings, $\bm{qe}_{ent}$ and $\bm{qe}_{time}$, which are question embeddings for entity and time prediction respectively. \begin{description} \item[Entity scoring function:] We extract a subject entity $s$ and a timestamp $t$ from the question. If either is missing, we use a dummy entity/time. Then, using the scoring function $\phi(s, r, o, t)$ from equation~\ref{eqn:tcomplex}, we calculate a score for each entity $e \in \mathbf{E}$ as \begin{equation} \label{eqn:ent-score} \begin{aligned} \bm{\phi_{ent}}(e) = \Re(\langle \bm{u}_s, \bm{qe}_{ent}, \bm{u}_e^\star, \bm{w}_t \rangle) \end{aligned} \end{equation} where $\mathbf{E}$ is the set of entities in the KG. This gives us a score for each entity being an answer. \item[Time scoring function:] Similarly, we extract a subject entity $s$ and object entity $o$ from the question, using dummy entities if none are present. Then, using~\ref{eqn:tcomplex}, we calculate a score for each timestamp $t \in \mathbf{T}$ as \begin{equation} \label{eqn:time-score} \begin{aligned} \bm{\phi_{time}}(t) = \Re(\langle \bm{u}_s, \bm{qe}_{time}, \bm{u}_o^\star, \bm{w}_t \rangle) \end{aligned} \end{equation} \end{description} The scores for all entities and times are concatenated, and $\mathrm{softmax}$ is used to calculate answer probabilities over this combined score vector. The model is trained using cross entropy loss. \input{main-results} \section{Experiments and diagnostics} \label{sec:Expt} In this section, we aim to answer the following questions: \begin{enumerate} \item How do baselines and \textsc{CronKGQA}{} perform on the \textsc{CronQuestions}{} task? (Section~\ref{sec:main-results}.) \item Do some methods perform better than others on specific reasoning tasks? (Section~\ref{sec:perf_across_qn_type}.) \item How much does the training dataset size (number of questions) affect the performance of a model? (Section~\ref{sec:training-data-size-effect}.) \item Do temporal KG embeddings confer any advantage over non-temporal KG embeddings? (Section~\ref{sec:temp_vs_nontemp}.) \end{enumerate} \subsection{Other methods compared} It has been shown by \citet{petroni2019language} and \citet{raffel2020exploring} that large LMs, such as BERT and its variants, capture real world knowledge (collected from their massive, encyclopedic training corpus) and can directly be applied to tasks such as QA. In these baselines, we do not specifically feed our version of the temporal KG to the model --- we instead expect the model to have the real world knowledge to compute the answer. \begin{description} \item[BERT:] We experiment with BERT, RoBERTa \citep{liu2019roberta} and Know\-BERT \citep{peters2019knowledge} which is a variant of BERT where information from knowledge bases such as WikiData and WordNet has been injected into BERT. We add a prediction head on top of the [CLS] token of the final layer and do a $\mathrm{softmax}$ over it to predict the answer probabilities. \item[T5:] In order to apply T5 \citep{raffel2020exploring} to temporal QA, we transform each question in our dataset to the form `\textit{temporal question: }$\langle \mathrm{question} \rangle$\textit{?}'. For evaluation there are two cases: \begin{enumerate} \item Time answer: We do exact string matching between T5 output and correct answer. \item Entity answer: We compare the system output to the aliases of all entities in the KG. The entity having an alias with the smallest edit distance \citep{levenshtein1966binary} to the predicted text output is taken as the predicted entity. \end{enumerate} \item[Entities as experts:]\citet{fevry2020entexperts} proposed EaE, a model which aims to integrate entity knowledge into a transformer-based language model. For temporal KGQA on \textsc{CronQuestions}{}, we assume that all grounded entity and time mention spans are marked in the question\footnote{This assumption can be removed by using EaE's early transformer stages as NE spotters and disambiguators.}. We will refer to this model as \textbf{T-EaE-add}. We try another variant of EaE, \textbf{T-EaE-replace}, where instead of adding the entity/time and BERT token embeddings, we replace the BERT embeddings with the entity/time embeddings for entity/time mentions.\footnote{Appendix~\ref{sec:eae_appendix} gives details of our EaE implementation.} \end{description} \subsection{Main results} \label{sec:main-results} Table~\ref{tab:main-results} shows the results of various methods on our dataset. We see that methods based on large pre-trained LMs alone (BERT, RoBERTa, T5), as well as KnowBERT, perform significantly worse than methods that are augmented with KG embeddings (temporal or non-temporal). This is probably because having KG embeddings specific to our temporal KG helps the model to focus on those entities/timestamps. In our experiments, BERT performs slightly better than KnowBERT, even though KnowBERT has entity knowledge in its parameters. T5-3B performs the best among the LMs we tested, possibly because of the large number of parameters and pre-training. Even among methods that use KG embeddings, \textsc{CronKGQA}{} performs the best on all metrics, followed by T-EaE-replace. Since EmbedKGQA has non-temporal embeddings, its performance on questions where the answer is a time is very low --- comparable to BERT --- which is the LM used in our EmbedKGQA implementation. Another interesting thing to note is the performance on simple reasoning questions. \textsc{CronKGQA}{} far outperforms baselines for simple questions, achieving close to 0.99 hits@1, which is much lower for T-EaE (0.329). We believe there might be a few reasons that contribute to this: \begin{enumerate} \item There is the \textit{inductive bias} of combining embeddings using TComplEx scoring function in \textsc{CronKGQA}{}, which is the same one used in creating the entity and time embeddings, thus making the simple questions straightforward to answer. However, not relying on a scoring function means that T-EaE can be extended to any KG embedding, whereas \textsc{CronKGQA}{} cannot. \item Another contributing reason could be that there are fewer parameters to be trained in \textsc{CronKGQA}{} while a 6-layer Transformer encoder needs to be trained from scratch in T-EaE. Transformers typically require large amounts of varied data to train successfully. \end{enumerate} \begin{figure}[t!] \centering \input{dataset-graph} \caption{Model performance (hits@10) vs.\ training dataset size (percentage) for \textsc{CronKGQA}{} and T-EaE-add. Solid line is for simple reasoning and dashed line is for complex reasoning type questions. For each dataset size, models were trained until validation hits@10 did not increase for 10 epochs. Please refer to Section \ref{sec:training-data-size-effect} for details.} \label{fig:dataset-size} \end{figure} \subsection{Performance across question types} \label{sec:perf_across_qn_type} \input{reasoning-comparison} Table~\ref{tab:reasoning-comparison} shows the performance of KG embedding based models across different types of reasoning. As stated above in Section \ref{sec:main-results}, \textsc{CronKGQA}{} performs very well on simple reasoning questions (simple entity, simple time). Among complex question types, all models (except EmbedKGQA) perform the best on time join questions (e.g., `\textit{Who played with Roberto Dinamite on the Brazil national football team}'). This is because such questions typically have multiple answers (such as all the players when \textit{Roberto Dinamite} was playing for Brazil), which makes it easier for the model to make a correct prediction. In the other two question types, the answer is always a single entity/time. Before/after questions seem most challenging for all methods, with the best method achieving only 0.288 hits@1. \subsection{Effect of training dataset size} \label{sec:training-data-size-effect} Figure~\ref{fig:dataset-size} shows the effect of training dataset size on model performance. As we can see, for T-EaE-add, increasing the training dataset size from 10\% to 100\% steadily increases its performance for both simple and complex reasoning type questions. This effect is somewhat present in \textsc{CronKGQA}{} for complex reasoning, but not so for simple reasoning type questions. We hypothesize that this is because T-EaE has more trainable parameters --- it has a 6-layer transformer that needs to be trained from scratch --- in contrast to \textsc{CronKGQA}{} that needs to merely fine tune BERT and train some shallow projection layers. These results affirm our hypothesis that having a large, even if synthetic, dataset is useful for training temporal reasoning models. \subsection{Temporal vs.\ non-temporal KG embeddings} \label{sec:temp_vs_nontemp} We conducted further experiments to study the effect of temporal vs.\ non-temporal KG embeddings. We replaced the temporal entity embeddings in T-EaE-replace with ComplEx embeddings, and treated timestamps as regular tokens (not associated with any entity/time mentions). \textsc{CronKGQA}{}-CX is the same as EmbedKGQA. The results can be seen in Table \ref{tab:complex-vs-tcomplex}. As we can see, for both \textsc{CronKGQA}{} and T-EaE-replace, using temporal KGE (TComplex) gives a significant boost in performance compared to non-temporal KGE (ComplEx). \textsc{CronKGQA}{} receives a much larger boost in performance compared to T-EaE-replace, probably because the scoring function has been modeled after TComplEx and not ComplEx, while there is no such embedding-specific engineering in T-EaE-replace. Another observation is that questions having temporal answers achieve very low accuracy (0.057 and 0.062 respectively) in both \textsc{CronKGQA}{}-CX and T-EaE-replace-CX, which is much lower than what these models achieve with TComplEx. This shows that having temporal KG embeddings is essential for achieving good performance for KG embedding-based methods. \input{temporal_vs_nontemporal} \section{Conclusion} In this paper we introduce \textsc{CronQuestions}{}, a new dataset for Temporal Knowledge Graph Question Answering. While there exist some Temporal KGQA datasets, they are all based on non-temporal KGs (e.g., Freebase) and have relatively few questions. Our dataset consists of both a temporal KG as well as a large set of temporal questions requiring various structures of reasoning. In order to develop such a large dataset, we used a synthetic generation procedure, leading to a question distribution that is artificial from a semantic perspective. However, having a large dataset provides an opportunity to train models, rather than just evaluate them. We experimentally show that increasing the training dataset size steadily improves the performance of certain methods on the TKGQA task. We first apply large pre-trained LM based QA methods on our new dataset. Then we inject KG embeddings, both temporal and non-temporal, into these LMs and observe significant improvement in performance. We also propose a new method, \textsc{CronKGQA}{}, that is able to leverage Temporal KG Embeddings to perform TKGQA. In our experiments, \textsc{CronKGQA}{} outperforms all baselines. These results suggest that KG embeddings can be effectively used to perform temporal KGQA, although there remains significant scope for improvement when it comes to complex reasoning questions. \section*{Acknowledgements} We would like to thank the anonymous reviewers for their constructive feedback, and Pat Verga and William Cohen from Google Research for their insightful comments. We would also like to thank Chitrank Gupta (IIT Bombay) for his help in debugging the source code and dataset. This work is supported in part by a gift from Google Research, India and a Jagadish Bose Fellowship. \bibliographystyle{acl_natbib}
{'timestamp': '2021-06-04T02:07:25', 'yymm': '2106', 'arxiv_id': '2106.01515', 'language': 'en', 'url': 'https://arxiv.org/abs/2106.01515'}
arxiv
\section{Introduction}\label{sec:1} Multiple imputation (MI), first introduced by \citet{rubin1978multiple}, has received increasing recognition in dealing with missing data as it can reduce bias and represent the uncertainty of missing values. For an incomplete dataset, each missing value is replaced by a set of $M>1$ plausible values instead of a single value. Analysis can then be performed separately on $M$ complete imputed datasets, and results can be combined to yield valid inference. \cite{rubin:1987} argued that the pooled estimates and variance would be statistically valid under proper imputation conditions. A number of frameworks have been developed to implement multiple imputation (MI). However, few automated procedures have been devised for large-scale imputation. One main flaw of traditional MI implementations is that they fail to capture complex relations among variables automatically. If such relations exist, popular software packages such as \texttt{mi} \citep{su2011mi} and \texttt{mice} with default settings \citep{buuren2011mice} would produce unsatisfactory results unless users manually specify any potential non-linear or interaction effects in the imputation model for each incomplete variables. Indeed, \cite{buuren2011mice} indicate that using default \texttt{mice} generally would not be optimal and including the interaction of interest in the imputation model is crucial. However, it appears that researchers would often use \texttt{mice} in an automated way \citep[e.g.,][]{micedefault1,micedefault2,micedefault3}. On the other hand, tree-based algorithms provide a possible way to overcome this shortcoming. \cite{stekhoven2012missforest} proposed a non-parametric method for missing value imputation based on random forests \citep{breiman2001random} and implemented it in an \texttt{R} package called \texttt{missForest}. \cite{doove2014recursive} implemented classification and regression tree (CART) and random forests within the \texttt{mice} framework (\texttt{mice-cart} and \texttt{mice-rf}) and showed that their performances on preserving the non-linear effects are better than standard \texttt{mice} implementations. Another disadvantage of existing MI frameworks is the excessive computation time for large datasets. Recent advances in technology have rendered the collection and analysis of large datasets feasible. However, current MI methods, including those with abilities to capture complex data structures like \texttt{mice-cart} and \texttt{mice-rf}, are more suitable for small datasets and often struggle with medium datasets. When there are reasonably large amounts of missing values present across many variables, this problem can become unmanageable. Applying machine learning (ML) techniques to multiple imputation can help to tackle the computational bottleneck, but the validity of imputed values obtained by current ML-based implementations is questionable. One disadvantage is that some software can only perform single imputation and ignores the uncertainty about missing values, thus leading to invalid inference. \cite{zhang2019XGBoost} proposed to use an XGBoost-based model to impute time series data. To our knowledge, this is a single imputation approach. An \texttt{R} package \texttt{missRanger} \citep{mayer2019ranger} was developed using \texttt{ranger} \citep{wright2015ranger}, which is a faster implementation of random forests. It is mainly designed for single imputation even though \cite{wright2015ranger} claimed that multiple imputation with \texttt{missRanger} could be achieved by running the imputation model $M$ times. However, its performance has not been investigated. Another concern is that most ML-based implementations have validated their imputation performances by point prediction accuracy. \cite{rubin1996multiple} explained that imputation methods which aim to generate the most accurate imputed value based on the best point prediction would neglect the intrinsic uncertainty of the missing data. These methods are prone to underestimate variance, thus leading to invalid statistical inference. \cite{lall2020applying} implemented multiple imputation with denoising autoencoders in a \texttt{Python} library \texttt{midas}, which offers an efficient solution for large-sized incomplete data. The main goal of \texttt{midas} is to generate the most accurate imputed values relative to true values, and it appears to overlook whether imputed values reflect adequate variability. Similarly, \cite{YinglingJason2019MIoM} used metrics such as Root Mean Square Error (RMSE) and Mean Absolute Error (MAE) to validate XGBoost-based imputation models, which also aims to recreate the true data rather than represent the uncertainty of missing values. The purpose of this paper is to present a fast and automated multiple imputation procedure \texttt{mixgb}, which is based on XGBoost \citep{chen2016xgboost}, bootstrapping \citep{Efron1979} and predictive mean matching \citep{little1988missing}, with a focus on yielding statistically valid results. XGBoost, a fast tree boosting algorithm, has been a frequent winner in Kaggle data competitions \citep{chen2016xgboost} and has gained immense popularity because of its speed and accuracy. XGBoost's ability to efficiently capture complex structures of large datasets means it has great potential for automated multiple imputation. With bootstrapping and predictive mean matching, our proposed method can better incorporate the variability of missing data and enhance the imputation quality. This paper is structured as follows. Section \ref{sec:2} describes the proposed multiple imputation through XGBoost framework (\texttt{mixgb}) in detail. An overview of simulation studies on imputation performance is given in Section \ref{sec:3.1}. The evaluation criteria for multiple imputation implementations are presented in Section \ref{sec:3.2}. Simulation results are given in Section \ref{sec:3.3}, demonstrating the imputation quality of \texttt{mixgb}. Section \ref{sec:4} demonstrates the advantage of \texttt{mixgb} over other implementations in terms of computational efficiency, and an example using a real dataset is illustrated in Section \ref{sec:5}. Finally, discussions based on empirical results are presented in Section \ref{sec:6}. We implement the proposed method in our \texttt{R} package \texttt{misle} (multiple imputation through statistical learning), which is available at \url{https://github.com/agnesdeng/misle}. \section{Framework}\label{sec:2} Using XGBoost to impute missing data has attracted growing interest in recent years. However, previous work has focused on the prediction accuracy of missing values without sufficient consideration for uncertainty of missing data, which leads to underestimating the variability of imputation. To address this problem, we propose using XGBoost with bootstrapping and predictive mean matching (PMM) for multiple imputation. Our framework \texttt{mixgb} works as follows: Given an incomplete $n\times p$ dataset $X$, we first sort our variables by the number of missing values. We then conduct an initial imputation for missing values to obtain a complete sorted dataset $Y$. We choose to initially impute missing data by randomly drawing from the observed data. We let $Y_i^{\text{obs}}$ and $Y_i^{\text{mis}}$ be the observed values and imputed (originally missing) values for the variable $Y_i$. We also let $Y_{-i}^{\text{obs}}$ denote the corresponding data in all variables other than $Y_i$ for entries where $Y_i$ was observed and $Y_{-i}^{\text{mis}}$ denote the data for variables other than $Y_i$ for entries where $Y_i$ was originally missing before initial imputation. We use XGBoost models with bootstrapping to better account for uncertainty of missing values. For each of the $M$ imputations, we generate a bootstrapped sample $Y^*$ from $Y$. For each variable we fit an XGBoost model $f^*:Y_i^{*\text{obs}}\sim Y_{-i}^{*\text{obs}}$, where $Y_i^{*\text{obs}}$ were the originally observed values in $Y_i^*$ and $Y_{-i}^{*\text{obs}}$ were the corresponding data in all other variables except $Y_{i}^*$. After fitting the model $f^*$ using the bootstrapped data, we use this model and $Y_{-i}^{\text{mis}}$ to obtain predictions for $Y_i^{\text{mis}}$, which we call $\widetilde{Y_i^{\text{mis}}}$. However, simply imputing missing values with $\widetilde{Y_i^{\text{mis}}}$ is susceptible to underestimation of imputation variability for continuous data. This problem can be alleviated by predictive mean matching (PMM), which was first proposed by \cite{rubin1986statistical} and extended to multiple imputation by \cite{little1988missing}. The idea of PMM is to match the predicted values of the missing entries to a set of $K$ donors that have the closest predicted mean values from other observed entries. A donor is then randomly selected and its observed value is used to impute the missing value. \Citet{van2018flexible} summarises four types of predictive mean matching. We only implement type 1 and type 2 matching in our framework as type 0 is improper and type 3 is not applicable to our method. The detailed algorithm for \texttt{mixgb} is described in Algorithm \ref{algo:mixgb} and is implemented in our \texttt{R} package \texttt{misle}. Figure \ref{fig:pmm} illustrates the need for predictive mean matching for continuous data in multiple imputation through XGBoost. We create a dataset with 1000 observations using $y_i=5x_i+\epsilon_i$, where $\epsilon\sim N(0,1)$. We then generate 50\% missing data in x under the MCAR mechanism. As shown in Figure \ref{fig:pmm}, the variability within an imputed dataset using \texttt{mixgb} without the aid of PMM is considerably smaller than both the variance of the observed data and the true variance of masked data. By contrast, both type 1 and type 2 PMM obtain similar within-variance as the masked true variance. \begin{figure}[H] \centering \includegraphics[width=0.8\columnwidth]{pmm} \caption{The need for PMM when imputing continuous missing data in \texttt{mixgb}.} \label{fig:pmm} \end{figure} \begin{center} \begin{algorithm}[H] \scriptsize \SetArgSty{textnormal} \KwIn{ $n\times p$ incomplete dataset $X$\; the number of imputations $M$\; type of predictive mean matching (auto,1,2, or NULL) }% {\bf Initialization:} sort variables by the number of missing values in ascending order\; make an initial guess for missing data and obtain a complete sorted dataset $Y$\; If pmm.type=auto, then set pmm.type=2 for numeric variables and set pmm.type=NULL for categorical variables. \For{$m=1$ \KwTo $M$} { $Y\leftarrow$ use the last imputed data set \; generate a bootstrap sample $Y^*$ from the dataset $Y$\; \For{$i=1$ \KwTo $p$}{ fit a XGBoost model $f^*$ using $Y_i^{*\text{obs}} \sim Y_{-i}^{*\text{obs}}$\; $\widetilde{Y_i^{\text{mis}}}\leftarrow$ predict $Y_i^{\text{mis}}$ with model $f^*$ and $ Y_{-i}^{\text{mis}}$\; \uIf{pmm.type=1}{fit a XGBoost model $f$ using $Y_i^{\text{obs}} \sim Y_{-i}^{\text{obs}}$\; $\widehat{Y_i^{\text{obs}}}\leftarrow$ predict $Y_i^{\text{obs}}$ with model $f$ and $ Y_{-i}^{\text{obs}}$\; $\overline{Y_i^{\text{mis}}} \leftarrow$match $\widetilde{Y_i^{\text{mis}}}$ to $\widehat{Y_i^{\text{obs}}}$\; update $Y$ with $\overline{Y_i^{\text{mis}}}$ } \uElseIf{pmm.type=2}{$\widetilde{Y_i^{\text{obs}}}\leftarrow$ predict $Y_i^{\text{obs}}$ with model $f^*$ and $ Y_{-i}^{\text{obs}}$\; $\overline{Y_i^{\text{mis}}} \leftarrow$match $\widetilde{Y_i^{\text{mis}}}$ to $\widetilde{Y_i^{\text{obs}}}$\; update $Y$ with $\overline{Y_i^{\text{mis}}}$} \uElse{update $Y$ with $\widetilde{Y_i^{\text{mis}}}$} } convert $Y^{(m)}$ to $Y_{\text{imp}}^{(m)}$ by reverting the variable ordering\; \KwRet{$Y_{\text{imp}}^{(m)}$} } \KwOut{% $M$ imputed datasets $Y_{\text{imp}}=(Y_{\text{imp}}^{(1)},Y_{\text{imp}}^{(2)},...,Y_{\text{imp}}^{(M)})$ }% \caption{Multiple imputation of missing data through XGBoost \label{algo:mixgb}% \end{algorithm} \end{center} \newpage \section{Simulation studies}\label{sec:3} \subsection{Overview}\label{sec:3.1} We conducted simulation studies based on \cite{doove2014recursive}, who evaluated the performance of multiple imputation using recursive partitioning techniques (CART, Forest-boot and Forest-RI) within the mice framework. \textbf{Data generation models:} We generated simulated continuous datasets using three different data generation models (\ref{eqn:model1}-\ref{eqn:model3}): \begin{align} y_{1,i} &=\beta_0+\beta_1 x_{1,i}+\beta_2 x_{2,i}+\beta_3 x_{3,i}+\beta_4 x_{8,i}+\beta_5 x_{9,i}+\beta_6 x_{3,i}^2+\epsilon_i;\label{eqn:model1}\\ y_{2,i}&=\beta_0+\beta_7 x_{1,i}+\beta_8 x_{2,i}+\beta_9 x_{3,i}+\beta_{10} x_{8,i}+\beta_{11} x_{9,i}+\beta_{12} x_{1,i} x_{2,i}+\epsilon_i; \label{eqn:model2}\\ y_{3,i}&=\beta_0+\beta_{13} x_{1,i}+\beta_{14}x_{2,i}+\beta_{15} x_{3,i}+\beta_{16} x_{8,i}+\beta_{17} x_{9,i}+\beta_{18} x_{8,i} x_{9,i}+\epsilon_i,\label{eqn:model3} \end{align} where $\epsilon_i\sim N(0,1)$. Simulated categorical datasets were generated by three different logistic regression models (\ref{eqn:model4}-\ref{eqn:model6}): \begin{align} \text{logit}[P(Y_1=1)]&=\alpha_0+\alpha_1 d_1+\alpha_2 d_2+\alpha_3 d_3+\alpha_4 d_4+\alpha_5 d_8+\alpha_6 d_9 +\alpha_7 d_1 d_2; \label{eqn:model4}\\ \text{logit}[P(Y_2=1)]&=\alpha_0+\alpha_8 d_1+\alpha_9 d_2+\alpha_{10} d_3+\alpha_{11} d_4+\alpha_{12} d_8+\alpha_{13} d_9 +\alpha_{14} d_3 d_4; \label{eqn:model5}\\ \text{logit}[P(Y_3=1)]&=\alpha_0+\alpha_{15} d_1+\alpha_{16} d_2+\alpha_{17} d_3+\alpha_{18} d_4+\alpha_{19} d_8+\alpha_{20} d_9 +\alpha_{21} d_8 d_9.\label{eqn:model6} \end{align} In order to make a direct comparision with other tree-based implementations, we used the same values of $\beta_i$ and $\alpha_i$ as \cite{doove2014recursive}, which are shown in Table \ref{tab:param}. They correspond to interactions with a medium effect size for continuous data generation models and a large effect size for categorical models. For continuous data models, ten variables $x_1$ to $x_{10}$ were drawn from a multivariate normal distribution with means equal to zero and pairwise correlations between the first four variables $x_1$ to $x_4$ equal to 0.5 and pairwise correlations between the last six variables $x_5$ to $x_{10}$ equal to 0.3. All other pairwise correlations are 0. For categorical data models, binary variables $d_1$, $d_2$, $d_3$, $d_4$, $d_8$ and $d_9$ were randomly assigned 0 or 1 with equal probability, while categorical variables with three categories, $d_5$, $d_6$, $d_7$ and $d_{10}$ were drawn from a binomial distribution with parameters $n=2$ and $p=0.5$. \begin{table}[H] \centering \resizebox{0.5\textheight}{!}{% \begin{tabular}{lrlrlrcclrlrlr} \toprule \multicolumn{6}{c}{Continuous data} & & & \multicolumn{6}{c}{Categorical data} \\ \cmidrule{1-6} \cmidrule{9-14} \multicolumn{2}{l}{model \ref{eqn:model1}} & \multicolumn{2}{l}{model \ref{eqn:model2}} & \multicolumn{2}{l}{model \ref{eqn:model3}} & & & \multicolumn{2}{l}{model \ref{eqn:model4}} & \multicolumn{2}{l}{model \ref{eqn:model5}} & \multicolumn{2}{l}{model \ref{eqn:model6}} \\ \midrule $\beta_0$&0&$\beta_0$ &0 &$\beta_0$&0 &&& $\alpha_0$ &0 & $\alpha_0$ & 0 & $\alpha_0$ &0 \\ $\beta_1$&0.31&$\beta_7$ &0.31 &$\beta_{13}$&0.31 &&& $\alpha_1$ &0.5 & $\alpha_8$ & 0.7 & $\alpha_{15}$ &0.4 \\ $\beta_2$&0.31&$\beta_8$ &0.31 &$\beta_{14}$&0.31 &&& $\alpha_2$ &1 & $\alpha_9$ & 0.5 & $\alpha_{16}$ &0.4 \\ $\beta_3$&0.31&$\beta_9$ &0.31 &$\beta_{15}$&0.31 &&& $\alpha_3$ &0.5 & $\alpha_{10}$ & 0.7 & $\alpha_{17}$ &0.4 \\ $\beta_4$&0.31&$\beta_{10}$ &0.31 &$\beta_{16}$&0.31 &&& $\alpha_4$ &$-1$ & $\alpha_{11}$ & $ -0.2$ & $\alpha_{18}$ &$-1.3$ \\ $\beta_5$&0.31&$\beta_{11}$ &0.31 &$\beta_{17}$&0.31 &&& $\alpha_5$ &$-1$& $\alpha_{12}$ & $-1.1$ & $\alpha_{19}$ &$-0.2$ \\ $\beta_6$&0.28&$\beta_{12}$ &0.35 &$\beta_{18}$&0.37 &&& $\alpha_6$ &$-0.5$ & $\alpha_{13}$ & $ -1.1$ & $\alpha_{20}$ &$-0.2$ \\ & & & & & &&& $\alpha_7$ & 1.1 & $\alpha_{14}$ & 1.1 & $\alpha_{21}$ &1.1 \\ \bottomrule \end{tabular}% } \caption{Parameter values for data generation models \ref{eqn:model1}-\ref{eqn:model6}.}\label{tab:param} \end{table} \textbf{Missing data mechanisms:} For each continuous data generation model, we created a dataset with 1000 observations and missing data were generated according to the following mechanism: 20\% MCAR in $x_1$ and $x_2$ and 20\% MAR in y for model \ref{eqn:model1}; 20\% MCAR in $x_3$ and $x_8$ and 20\% MAR in y for model \ref{eqn:model2}; 20\% MCAR in $x_2$ and $x_3$ and 20\% MAR in y for model \ref{eqn:model3}. Let $\pi$ be the probability that $y$ is missing. Variable $y$ was made MAR by $\text{logit} (\pi)=\gamma+x_9+x_{10}$, where $\gamma$ was found such that the expected value of $\pi$ is 0.2. For each categorical data generation model, we created a dataset with 1000 observations and missing data were generated according to the following mechanism: 20\% MCAR in $d_3$ and $d_4$ and 20\% MAR in y for model \ref{eqn:model4}; 20\% MCAR in $d_1$ and $d_2$ and 20\% MAR in y for model \ref{eqn:model5} and \ref{eqn:model6}. Missing values in $y$ were created by $\text{logit} (\pi)=\gamma+d_9+d_{10}$ such that $\mathbb{E}(\pi) = 0.2$. \textbf{Methods:} We assess the imputation quality of the following implementations: (a) predictive mean matching within MICE (\texttt{mice.pmm}) for continuous data; logistic regression within MICE (\texttt{mice.logreg}) for categorical data; (b) weighted predictive mean matching within MICE (\texttt{mice.midastouch}) for continuous data and bootstrapping logistic regression within MICE (\texttt{mice.logregboot}) for categorical data; (c) classification and regression trees within MICE (\texttt{mice.cart}); (d) random forests within MICE (\texttt{mice.rf}); (e) fast implementation of random forests (\texttt{missRanger}); (f) XGBoost without predictive mean matching (\texttt{mixgb.null}); (g) XGBoost with type 1 predictive mean matching (\texttt{mixgb.pmm1}); (h) XGBoost with type 2 predictive mean matching (\texttt{mixgb.pmm2}). All methods except \texttt{missRanger} used default settings and the number of multiple imputations was set to 20. We set the number of trees to 100 in \texttt{missRanger} as we considered the default number 500 too large for this problem. In addition, the author of \texttt{mice} set the default number of trees in \texttt{mice.rf} to 10 based on simulation studies by \cite{shah2014comparison}. To make a fair comparision between these two random forests-based imputation methods, it would be reasonable to set the number of trees in \texttt{missRanger} to 10. However, we found that the performance was far worse than that of \texttt{mice.rf} under the same number of trees. Therefore, we decided to use 100 trees in \texttt{missRanger} instead. The performance of these methods was then evaluated over 1000 simulations based on biases, total-imputation variability, between-imputation variability, within-imputation variability, coverage, the width of confidence interval and the fraction of missing information. \subsection{Evaluation criteria}\label{sec:3.2} To investigate the validity of multiple imputation methods, we use the following criteria: \paragraph{Bias.} Suppose that $\beta$ is the true value of an estimand, such as one of the $\beta_i$ that we use to generate a simulated dataset and $\hat{\beta}$ is the estimate of $\beta$ for a given complete simulated dataset. We generate missing data under a specified missing data mechanism and impute the incomplete dataset $M=20$ times. For each imputed dataset, we obtain an estimate $\beta^*$ so the combined estimate would be \begin{align} \overline{\beta}_M=\frac{1}{M} \sum_{m=1}^M \beta_m^*. \end{align} Note that the bias of $\overline{\beta}_M$ consists of two components: \begin{align} E[\overline{\beta}_M]-\beta= (E[\overline{\beta}_M]-E[\hat{\beta}])+(E[\hat{\beta}]-\beta). \end{align} We are only interested in the phase two bias $E[\overline{\beta}_M]- E[\hat{\beta}]$, as the phase one bias $E[\hat{\beta}]-\beta$ is subject to random noise, such as the error term $\epsilon_i$ that we use to generate simulated data. Therefore, we report the average phase two bias over $R=1000$ simulations for each of the coefficients. \begin{align} \text{Bias}=E[\overline{\beta}_M]- E[\hat{\beta}],\quad \text{where} \quad E[\overline{\beta}_M]=\frac{1}{R} \sum_{r=1}^R \overline{\beta}_M^{(r)} \quad \text{and} \quad E[\hat{\beta}]=\frac{1}{R} \sum_{r=1}^R \hat{\beta}^{(r)}. \end{align} \paragraph{Total variance.} If an imputation method is proper, we would expect the average total variance of the MI combined estimate over $R=1000$ replications to be approximately equal to the observed variance between all $\overline{\beta}_M^{(r)}$, for $r=1,2,...,R$. That is, $\text{Var}_{\text{total}}\doteq\text{Var}_{\text{total}} \text{(true)} $, where \begin{align} \text{Var}_{\text{total}}= E[T_m]=\frac{1}{R} \sum_{r=1}^R \left[\overline{U}_M^{(r)}+\left(1+\frac{1}{M}\right) B_M^{(r)}\right], \end{align} \begin{align} \text{Var}_{\text{total}} \text{(true)} =\text{Var}[\overline{\beta}_M]&=\frac{1}{R-1} \sum_{r=1}^R \left(\overline{\beta}_M^{(r)}-\mu \right)^2, \quad\text{and} \quad \mu =\frac{1}{R}\sum_{r=1}^R \overline{\beta}_M^{(r)}. \end{align} \paragraph{Within-imputation variance.} The expectation of the within-variance component of the combined MI estimate over $R=1000$ simulations, should be similar to the expectation of complete data variances. That is, $\text{Var}_{\text{within}}\doteq\text{Var}_{\text{within}} \text{(true)}$ , where \begin{align} \text{Var}_{\text{within}}= E[\overline{U}_M]=\frac{1}{R} \sum_{r=1}^R \overline{U}_M^{(r)}, \end{align} \begin{align} \text{Var}_{\text{within}} \text{(true)}=E[U]=\frac{1}{R} \sum_{r=1}^R U_r. \end{align} \paragraph{Between-imputation variance.} The expected value of the variance between $M$ estimates obtained from imputed datasets should be close to the true value of the between variance component: $\text{Var}_{\text{between}}\doteq\text{Var}_{\text{between}}\text{(true)}$, where \begin{align} \text{Var}_{\text{between}} =(1+\frac{1}{M})E[B_M],\quad\text{and} \notag\\ E[B_M]=\frac{1}{R} \sum_{r=1}^R B_M^{(r)}=\frac{1}{R} \frac{1}{M-1}\sum_{r=1}^R \sum_{m=1}^M( \beta_m^{*(r)}-\overline{\beta}_M^{(r)})^2, \end{align} \begin{align} \text{Var}_{\text{between}}\text{(true)}=\text{Var}_{\text{total}}\text{(true)}-\text{Var}_{\text{within}}\text{(true)} \end{align} \paragraph{Coverage.} The proportion of replications where the 95\% confidence interval around the combined MI estimate $\overline{\beta}_M$ contains the complete data estimate $\hat{\beta}$. \paragraph{Width of the 95\% confidence interval.} \paragraph{The fraction of missing information $\gamma$.} This is defined as the ratio of missing information to the complete-data information. This parameter indicates the impact of missing data. Higher value implies a more severe missing data problem. \subsection{Results}\label{sec:3.3} In this study, we aim to investigate the performance of \texttt{mixgb} against other multiple imputation frameworks, such as those evaluated in \cite{doove2014recursive}. In their studies, CART (mice.cart) was suggested to be the best at preserving interaction and nonlinear effects. In this section, we present results for continuous data generation model \ref{eqn:model2} and categorical data generation model \ref{eqn:model6}. We observe fairly similar patterns for the other four data generation models. Their simulation results are omitted here but can be found in the supplementary materials. Table \ref{tab:model2} shows the simulation results for continuous data generation model \ref{eqn:model2}. Visualizations of performances on bias and imputation variance are summarized in Figure \ref{fig:bias2} and Figure \ref{fig:var2}, respectively. As expected, using \texttt{mice.pmm} or \texttt{mice.midastouch} incurs a considerably large bias for the estimate of the interaction term $\beta_{12}$ (see Figure \ref{fig:bias2} ) since they do not automatically capture interaction relations between variables. However, standard \texttt{mice} implementations appear to generate less biased estimates for linear main effects. On the other hand, the bias of $\beta_{12}$ is significantly smaller when \texttt{mice.cart} or \texttt{mice.rf} is used. These findings are consistent with results obtained in \cite{doove2014recursive}. In addition, we found that even though the two random forests-based implementations \texttt{mice.rf} and \texttt{missRanger} can reduce the bias of $\beta_{12}$ , they tend to have evidently larger biases in estimates for other linear terms. It should be noted that the results for \texttt{mice.rf} and \texttt{missRanger} are somewhat different. This may be due to different default settings for hyperparameters in these two packages. When \texttt{missRanger}, \texttt{mixgb.null}, \texttt{mice.pmm} and \texttt{mice.midastouch} are used, we observe relatively larger biases in $\beta_7$ and $\beta_8$, which are the parameters associated with the interaction term $\beta_{12}$. Overall, both \texttt{mixgb.pmm1} and \texttt{mixgb.pmm2} obtain results as good as that of \texttt{mice.cart}, with \texttt{mixgb.pmm1} performing slightly better than \texttt{mixgb.pmm2}. To evaluate the performance on imputation variance, we display the difference between the measured and the true variance in Figure \ref{fig:var2}. Smaller difference indicates a better variance estimate. In terms of capturing proper within-imputation and between-imputation variances for estimates in model \ref{eqn:model2}, we can see that \texttt{mixgb.pmm2} is the best among all methods, followed by \texttt{mice.pmm}, \texttt{mice.midastouch} and \texttt{mice.cart}. When predictive mean matching is not applied, \texttt{mixgb} is prone to underestimate both the within-imputation and between-imputation variances for most estimates. Even though \texttt{mixgb.pmm1} alleviates this problem to some extent, it is notably inferior to \texttt{mixgb.pmm2}. On the contrary, random forests-based implementations such as \texttt{mice.rf} and \texttt{missRanger}, tend to overestimate the imputation variability for most estimates. With regard to the coverage rate for interaction term $\beta_{12}$, \texttt{mice.pmm} and \texttt{mice.midastouch} obtain substantially lower coverages compared to other imputation models (see Table \ref{tab:model2}). Most implementation can achieve at least 95\% coverage for other estimates except for $\beta_{10} $, where \texttt{mice.rf} and \texttt{missRanger} have a lower coverage rate at around 90\%. Compared to \texttt{mice.pmm} and \texttt{mice.midastouch}, tree-based imputation models tend to be more efficient as their confidence intervals are generally narrower while the coverage rate is not less than 95\%. The estimated fraction of missing information due to nonresponse is generally higher when we use \texttt{mice.pmm} and \texttt{mice.midastouch} for imputation, which indicates a more complicated missing data problem according to \cite{li1991large}. \begin{table}[H] \centering \resizebox{\textwidth}{!}{% \begin{tabular}{rlcccccccccc} \hline & Method & \begin{tabular}[c]{@{}c@{}}Bias\\ $\times 100$\end{tabular} & \begin{tabular}[c]{@{}c@{}} $\text{Var}_{\text{total}}$ \\ $\times 10000$\end{tabular} & \begin{tabular}[c]{@{}c@{}}$\text{Var}_{\text{total}}$(true) \\ $\times 10000$\end{tabular}& \begin{tabular}[c]{@{}c@{}}$\text{Var}_{\text{within}}$\\ $\times 10000$\end{tabular}& \begin{tabular}[c]{@{}c@{}}$\text{Var}_{\text{within}}$(true) \\ $\times 10000$\end{tabular}& \begin{tabular}[c]{@{}c@{}}$\text{Var}_{\text{between}}$\\ $\times 10000$\end{tabular}& \begin{tabular}[c]{@{}c@{}}$\text{Var}_{\text{between}}$(true) \\ $\times 10000$\end{tabular}&CI coverage \% & CI width & missinfo \% \\ \hline $\beta_0$& mice.pmm & 3.41 & 18.55 & 17.49 & 12.67 & 12.08 & 5.88 & 5.41 & 98 & 0.17 & 32 \\ & mice.midastouch & 3.12 & 18.32 & 17.32 & 12.84 & 12.08 & 5.48 & 5.23 & 99 & 0.17 & 30 \\ & mice.cart & -0.54 & 16.59 & 17.65 & 12.77 & 12.08 & 3.83 & 5.57 & 100 & 0.16 & 23 \\ & mice.rf & -1.14 & 17.40 & 16.74 & 13.43 & 12.08 & 3.96 & 4.66 & 100 & 0.16 & 23 \\ & missRanger & 0.13 & 15.56 & 17.70 & 12.44 & 12.08 & 3.11 & 5.62 & 100 & 0.15 & 20 \\ & mixgb.null & -0.22 & 13.03 & 17.27 & 10.54 & 12.08 & 2.50 & 5.19 & 100 & 0.14 & 19 \\ & mixgb.pmm1 & 0.31 & 13.69 & 17.57 & 10.82 & 12.08 & 2.87 & 5.49 & 100 & 0.15 & 21 \\ & mixgb.pmm2 & -0.67 & 15.57 & 17.14 & 12.10 & 12.08 & 3.47 & 5.06 & 100 & 0.15 & 22 \\ \hline $\beta_7$& mice.pmm & 1.04 & 21.80 & 23.51 & 15.88 & 15.15 & 5.92 & 8.36 & 100 & 0.18 & 27 \\ & mice.midastouch & 1.00 & 22.36 & 23.18 & 16.06 & 15.15 & 6.30 & 8.04 & 100 & 0.19 & 28 \\ & mice.cart & -0.03 & 20.75 & 21.37 & 15.96 & 15.15 & 4.79 & 6.22 & 100 & 0.18 & 23 \\ & mice.rf & -0.17 & 22.29 & 18.44 & 16.70 & 15.15 & 5.59 & 3.29 & 100 & 0.19 & 25 \\ & missRanger & 1.54 & 19.38 & 19.92 & 15.68 & 15.15 & 3.70 & 4.77 & 100 & 0.17 & 19 \\ & mixgb.null & -1.14 & 15.85 & 21.00 & 13.40 & 15.15 & 2.46 & 5.85 & 100 & 0.16 & 15 \\ & mixgb.pmm1 & -0.18 & 16.58 & 21.27 & 13.79 & 15.15 & 2.80 & 6.12 & 100 & 0.16 & 17 \\ & mixgb.pmm2 & -0.12 & 19.69 & 20.50 & 15.18 & 15.15 & 4.51 & 5.35 & 100 & 0.17 & 23 \\ \hline $\beta_8$& mice.pmm & 0.96 & 21.77 & 22.87 & 15.87 & 15.14 & 5.90 & 7.72 & 100 & 0.18 & 27 \\ & mice.midastouch & 0.94 & 22.28 & 22.11 & 16.05 & 15.14 & 6.23 & 6.96 & 100 & 0.19 & 28 \\ & mice.cart & -0.03 & 20.75 & 20.99 & 15.95 & 15.14 & 4.81 & 5.85 & 100 & 0.18 & 23 \\ & mice.rf & -0.15 & 22.23 & 17.82 & 16.69 & 15.14 & 5.54 & 2.67 & 100 & 0.19 & 25 \\ & missRanger & 1.52 & 19.34 & 18.80 & 15.68 & 15.14 & 3.66 & 3.65 & 100 & 0.17 & 19 \\ & mixgb.null & -1.13 & 15.90 & 20.21 & 13.39 & 15.14 & 2.51 & 5.06 & 99 & 0.16 & 16 \\ & mixgb.pmm1 & -0.18 & 16.54 & 20.36 & 13.78 & 15.14 & 2.76 & 5.21 & 100 & 0.16 & 17 \\ & mixgb.pmm2 & -0.15 & 19.77 & 19.51 & 15.17 & 15.14 & 4.60 & 4.37 & 100 & 0.17 & 23 \\ \hline $\beta_9$ & mice.pmm & 0.44 & 25.51 & 26.00 & 15.86 & 15.11 & 9.65 & 10.89 & 99 & 0.20 & 38 \\ & mice.midastouch & -0.16 & 26.04 & 25.20 & 16.00 & 15.11 & 10.04 & 10.09 & 100 & 0.20 & 38 \\ & mice.cart & -2.37 & 23.85 & 26.43 & 15.84 & 15.11 & 8.01 & 11.32 & 98 & 0.19 & 33 \\ & mice.rf & -4.03 & 25.24 & 18.35 & 16.49 & 15.11 & 8.76 & 3.24 & 98 & 0.20 & 35 \\ & missRanger & -3.34 & 24.33 & 18.77 & 15.86 & 15.11 & 8.47 & 3.66 & 99 & 0.19 & 35 \\ & mixgb.null & 0.94 & 19.84 & 27.19 & 15.23 & 15.11 & 4.61 & 12.08 & 98 & 0.17 & 23 \\ & mixgb.pmm1 & -1.17 & 19.11 & 23.36 & 15.36 & 15.11 & 3.75 & 8.25 & 99 & 0.17 & 20 \\ & mixgb.pmm2 & -2.41 & 23.59 & 21.87 & 15.82 & 15.11 & 7.77 & 6.76 & 99 & 0.19 & 33 \\ \hline $\beta_{10}$ & mice.pmm & 0.49 & 18.62 & 18.01 & 11.64 & 11.09 & 6.97 & 6.92 & 100 & 0.17 & 37 \\ & mice.midastouch & -0.21 & 18.89 & 17.66 & 11.78 & 11.09 & 7.10 & 6.57 & 100 & 0.17 & 37 \\ & mice.cart & -3.05 & 17.55 & 18.88 & 11.70 & 11.09 & 5.85 & 7.79 & 96 & 0.17 & 33 \\ & mice.rf & -5.40 & 18.64 & 13.90 & 12.33 & 11.09 & 6.31 & 2.81 & 89 & 0.17 & 34 \\ & missRanger & -4.94 & 17.52 & 13.47 & 11.51 & 11.09 & 6.01 & 2.38 & 91 & 0.16 & 34 \\ & mixgb.null & 0.17 & 14.40 & 19.42 & 11.12 & 11.09 & 3.28 & 8.33 & 99 & 0.15 & 23 \\ & mixgb.pmm1 & -1.32 & 14.06 & 17.40 & 11.17 & 11.09 & 2.88 & 6.31 & 98 & 0.15 & 20 \\ & mixgb.pmm2 & -2.96 & 17.33 & 16.03 & 11.69 & 11.09 & 5.64 & 4.94 & 98 & 0.16 & 32 \\ \hline $\beta_{11}$ & mice.pmm & 1.28 & 19.12 & 18.79 & 11.62 & 11.08 & 7.49 & 7.71 & 100 & 0.17 & 39 \\ & mice.midastouch & 1.13 & 18.97 & 18.41 & 11.75 & 11.08 & 7.23 & 7.33 & 100 & 0.17 & 38 \\ & mice.cart & -2.34 & 16.97 & 18.82 & 11.69 & 11.08 & 5.29 & 7.74 & 98 & 0.16 & 31 \\ & mice.rf & -3.24 & 17.21 & 14.46 & 12.25 & 11.08 & 4.96 & 3.38 & 98 & 0.16 & 29 \\ & missRanger & -0.70 & 15.01 & 16.99 & 11.45 & 11.08 & 3.56 & 5.90 & 100 & 0.15 & 24 \\ & mixgb.null & -2.76 & 13.40 & 17.05 & 9.77 & 11.08 & 3.63 & 5.97 & 95 & 0.14 & 27 \\ & mixgb.pmm1 & -1.66 & 14.15 & 17.64 & 10.06 & 11.08 & 4.10 & 6.55 & 99 & 0.15 & 29 \\ & mixgb.pmm2 & -2.22 & 16.38 & 16.58 & 11.10 & 11.08 & 5.28 & 5.50 & 98 & 0.16 & 32 \\ \hline $\beta_{12}$& mice.pmm & -5.63 & 10.94 & 9.68 & 8.56 & 8.17 & 2.38 & 1.51 & 68 & 0.13 & 22 \\ & mice.midastouch & -5.69 & 11.67 & 9.77 & 8.68 & 8.17 & 2.99 & 1.60 & 71 & 0.13 & 25 \\ & mice.cart & -2.27 & 10.94 & 10.69 & 8.63 & 8.17 & 2.30 & 2.52 & 98 & 0.13 & 21 \\ & mice.rf & -3.51 & 11.99 & 9.96 & 9.08 & 8.17 & 2.91 & 1.79 & 94 & 0.14 & 24 \\ & missRanger & -1.84 & 10.34 & 10.07 & 8.41 & 8.17 & 1.93 & 1.90 & 99 & 0.13 & 18 \\ & mixgb.null & -2.51 & 8.30 & 10.37 & 7.13 & 8.17 & 1.18 & 2.20 & 95 & 0.11 & 14 \\ & mixgb.pmm1 & -2.32 & 8.59 & 10.44 & 7.32 & 8.17 & 1.28 & 2.27 & 96 & 0.11 & 15 \\ & mixgb.pmm2 & -2.46 & 10.28 & 10.34 & 8.18 & 8.17 & 2.10 & 2.17 & 97 & 0.13 & 20 \\ \hline &Maximum Monte Carlo SE &0.11 & --- &--- &--- &---&--- &--- &1 &0.0005 &0.3 \\ &Maximum Bootstrap SE (100 samples) &--- &0.01 &0.1 &0.004 &0.003 & 0.01 &0.1 &--- &--- &--- \\ \hline \end{tabular}% } \caption{Simulation results for continuous data generation model \ref{eqn:model2}.} \label{tab:model2} \end{table} \begin{figure}[H] \centering \includegraphics[width=\textwidth]{bias2} \caption{Average bias ($\times 100$) with Monte Carlo 95\% confidence interval over 1000 simulations for continuous data generation model \ref{eqn:model2}.}\label{fig:bias2} \end{figure} \begin{figure}[H] \centering \includegraphics[width=\textwidth]{var2} \caption{Difference between measured and true variances with 95\% bootstrap confidence interval (100 samples) over 1000 simulations for continuous data generation model \ref{eqn:model2}. \\Upper panel -- Within-imputation variance; Lower panel -- Between-imputation variance.}\label{fig:var2} \end{figure} Imputation performance on biases for categorical data generation model \ref{eqn:model6} are illustrated in Figure \ref{fig:biasb3}. Interaction term $\alpha_{21}$ and its related parameters $\alpha_{19}$ and $\alpha_{20}$ are least biased when \texttt{mixgb.null} or \texttt{mixgb.pmm1} is used. As anticipated, \texttt{mice.logreg} and \texttt{mice.logregboot} show unsatisfactory results for the interaction parameter. Surprisingly, random forests-based methods do not appear to reduce the bias for the interaction term $\alpha_{21}$. Also, they have considerably larger biases for main effects compared with other implementations. Imputation with \texttt{mixgb.pmm2} performs slightly better than \texttt{mice.cart} on biases for parameters associated with the interaction, but exhibits moderate biases for main effects. The differences in the measured and true within-imputation variance are fairly small for all methods, with \texttt{mice.rf} and \texttt{missRanger} having larger differences. With regard to the performance on between-imputation variance, \texttt{mice.pmm} and \texttt{mice.midastouch} perform the worst for the interaction term while \texttt{mice.rf} and \texttt{missRanger} show undesirable results for most estimates. Performance by \texttt{mice.cart} or \texttt{mixgb.pmm2} seems to be satisfactory but \texttt{mixgb.null} and \texttt{mixgb.pmm1} yield optimal results on imputation variability. Overall, it appears that \texttt{mixgb.null} and \texttt{mixgb.pmm1} are superior to other implementations for categorical data. However, their performances are indistinguishable, suggesting that predictive mean matching may not be needed for categorical data. \begin{figure}[H] \centering \includegraphics[width=\textwidth]{biascat3} \caption{Average bias ($\times 100$) with Monte Carlo 95\% confidence interval over 1000 simulations for categorical data generation model \ref{eqn:model6}. }\label{fig:biasb3} \end{figure} \begin{figure}[H] \centering \includegraphics[width=\textwidth]{varcat3} \caption{Difference between measured and true variances with 95\% bootstrap confidence interval (100 samples) over 1000 simulations for categorical data generation model \ref{eqn:model6}. \\Upper panel-- Within-imputation variance; Lower panel -- Between-imputation variance. }\label{fig:varb3} \end{figure} \section{Computational time}\label{sec:4} In this section, we compare the computation time for different multiple imputation software using real and simulated datasets. All code and details for datasets used in this section are available in the supplementary materials. Table \ref{tab:time} shows the average computational time needed to obtain 5 imputed datasets for different imputation implementations using open datasets with various sizes. For each dataset, 30\% missing data were created under the MCAR mechanism and performances on wall clock time (elapsed) were averaged over 10 replications. The experiment was run on a Ubuntu 18.04 server with a 64-core processor and 187GB of RAM. Based on the simulation results in Section \ref{sec:3.3}, we apply \texttt{mixgb.pmm2} for continuous variables and \texttt{mixgb.null} for categorical variables as our default settings, which we call \texttt{mixgb.auto}. As both \texttt{XGBoost} and \texttt{Ranger} provide multithread parallel computing, we set the number of threads as 4 in \texttt{mixgb.auto} and \texttt{missRanger}. \begin{table}[H] \resizebox{\columnwidth}{!}{% \begin{tabular}{llllllllllll} \toprule \multirow{2}{*}{\textbf{Method}} & \textbf{Dataset} & & soybean & & ntws & & nhanes & & credit & & adult \\ \cline{2-12} & \textbf{Size$^a$} & & $683\times 36 \;(118)$ & & $3915\times 12 \;(20) $ & & $9575\times 15\; (21)$ & & $30000\times 24\; (35) $ & & $48842\times 15\; (107) $ \\ \midrule mice.default & & & 212 & & 11 & & 24 & & 522 & & N/A \\ mice.cart & & & 58 & & 34 & & 141 & & 1684 & & 5260 \\ mice.rf & & & 264 & & 399 & & 1377 & &16978 & & N/A \\ missRanger & & & 12 & & 17 & & 77 & & 793 & & 350 \\ mixgb.auto $^b$ & & & 46 & & 11 & & 22 & & 203 & & 238 \\ \midrule \textbf{maximum S.E} & & & 1 & & 1 & & 8 & & 28 & & 27 \\ \bottomrule \end{tabular}% } \footnotesize{ $^a$ Number in parentheses is the number of columns after one-hot encoding.}\\ \footnotesize{$^b$ Use \texttt{mixgb.pmm2} for continuous variables and \texttt{mixgb.null} for categorical variables.} \caption{Comparisons of average computation time (in seconds).} \label{tab:time} \end{table} Even though \texttt{mice.default} ran reasonably fast for small datasets, it was unable to handle medium or large datasets, especially those with more categorical variables. Random forests within the \texttt{MICE} framework was the slowest among all methods and it failed to impute the \texttt{ADULT} dataset. Using decision tree within the \texttt{MICE} framework could manage all five datasets, but it was considerably slower than \texttt{missRanger} or \texttt{mixgb.auto} and it scaled badly for large datasets. Overall, \texttt{mixgb.auto} and \texttt{missRanger} were the fastest. However, \texttt{missRanger} seemed to outperform \texttt{mixgb.auto} in datasets with fewer observations and more categorical variables. To assess the performance of these two methods in different scenarios, we compared the computation time using simulated data. Figure \ref{fig:timepfm} shows the log time to obtain five imputations on 36 combinations of datasets, with the number of features between 11 and 31, the number of observations ranging from $10^2$ to $10^5$ and the types of features all being continuous, all binary or a mixture of binary and 3-class variables. When the number of observations was $10^2$ , \texttt{missRanger} was faster than \texttt{mixgb.auto} for all types of variables and numbers of features. However, its advantage vanished with larger sample size. For continuous data, \texttt{mixgb.auto} was much faster than \texttt{missRanger} when the number of observations was greater than $10^2$. For binary data, \texttt{mixgb.auto} outperformed \texttt{missRanger} once the number of observations was over $10^4$ for all numbers of features. For data with a mix of binary and 3-class features, \texttt{mixgb.auto} outperformed \texttt{missRanger} when the number of observations was $10^5$. \newpage \begin{figure}[H] \centering \includegraphics[width=0.6\textwidth]{timepfm} \caption{Time performance comparison between missRanger and mixgb.auto.}\label{fig:timepfm} \end{figure} \section{Data Examples}\label{sec:5} We illustrate our proposed multiple imputation method \texttt{mixgb.auto} using the NWTS (US National Wilms' Tumor Study) dataset \citep{d1989treatment}. This dataset contains outcome variables (e.g. \texttt{relaps} and \texttt{dead}) as well as histology results for 3915 patients. Since it provides both the central lab histology (\texttt{histol}) and local institution histology (\texttt{instit}) results, it is extensively used as an example to illustrate two-phase sampling designs \citep[e.g.,][]{Breslow1999NWTS,Breslow2009NWTS,Tong2020NWTS}. Other variables include \texttt{study} (3 or 4), \texttt{stage} (1-4), the \texttt{age} and \texttt{year} at diagnosis, the weight of tumor (\texttt{specwgt}), the diameter of tumor (\texttt{tumdiam}), time to relapse (\texttt{trel}) and time to death (\texttt{tsur}). There are no missing values in the original dataset. We created 20\% missing data in \texttt{histol} and \texttt{tumdiam} by an MAR mechanism that depends on \texttt{trel}. Five imputed datasets were then generated using \texttt{mixgb.auto}. Comparisons of some marginal and conditional distributions of various continuous and categorical variables are shown in Figure \ref{fig:data1} and Figure \ref{fig:data2}. \begin{figure}[H] \centering \includegraphics[width=0.85\textwidth]{NWTS1} \caption{Marginal distribution of imputed missing values.}\label{fig:data1} \end{figure} \begin{figure}[H] \centering \includegraphics[width=0.85\textwidth]{NWTS2} \caption{Conditional distribution of imputed missing values.}\label{fig:data2} \end{figure} For some variables, such as \texttt{histol}, marginal distributions of imputed values are close to the distribution of masked true values. However, for some other variables such as \texttt{tumdiam}, some imputed values can still be distributed quite differently from their masked true values or the observed values. This phenomenon is not uncommon in an automated imputation procedure where expert knowledge about the data is not included in the imputation model. \section{Discussion}\label{sec:6} Commonly used multiple imputation implementations, such as the standard MICE algorithm, cannot automatically preserve complex data structure. To achieve satisfactory performance, they often rely on users to carefully select predictor variables and specify potential nonlinear or interaction effects in the imputation model for each incomplete variable. Ideally, identifying all inherent relations would guarantee a more desirable imputation quality, but it imposes higher requirements on expert knowledge. If the number of variables is large, this task may not be readily feasible and quite often gets omitted. Although using CART and random forests within the MICE framework can incorporate complex relations among data automatically, applying them for large-scale imputations can be challenging as imputation processes are often time-consuming or even abort with error messages. To address these issues, we propose a scalable MI approach based on XGBoost, a fast implementation of a gradient boosting algorithm. We found that multiple imputation through XGBoost (\texttt{mixgb}) has the advantage of capturing nonlinear relations among variables automatically. To assess the performance of \texttt{mixgb} against other state-of-the-art approaches, we extend the simulation studies by \cite{doove2014recursive}. We measured not only the biases but also the imputation variability of estimates. We found that the standard application of MICE was more capable of modeling main effects but can lead to severely biased interaction estimates. In addition, apparent inconsistencies between the total variance and the true total variance arose, resulting in undesirable performance on between-variance. These results were as expected, since MICE does not automatically incorporate nonlinear relationships between variables without imputers specifying any possible complex structures in the data. On the other hand, \texttt{mice.cart} and \texttt{mixgb}, were the best at reserving quadratic or interaction effects. Meanwhile, they also performed well on imputation variance. Imputation with random forests within the MICE framework (\texttt{mice-rf}) or \texttt{missRanger} slightly reduced biases for interaction terms, but its ability to accommodate non-linearity was inferior to that of \texttt{mixgb} or \texttt{mice.cart}. Furthermore, \texttt{mice-rf} and \texttt{missRanger} underperformed on reflecting appropriate imputation variabilities. As a result, they can sometimes lead to inaccurate estimates of the coverage rate and width of the confidence interval. The performance of random forests-based implementations was not as good as expected. This may be due to the fact that the number of features in our simulated datasets are quite small ($p=10$), and the default number of features selected at each node for splitting in random forests is $\sqrt{p}$, which could highly affect the performance of random forests in relatively low dimensional data. With regard to computational efficiency, \texttt{mixgb} shows superior performance across datasets with different sizes. The only competitor is \texttt{missRanger}, which tends to outperform \texttt{mixgb} for datasets with fewer observations and a larger number of categorical features. Using random forests within the MICE framework is the slowest among all methods, even with its default setting \texttt{num.trees=10}. Imputation with \texttt{missRanger} is substantially faster than \texttt{mice.rf} when the same number of trees is used. Even though \texttt{mice.cart} achieved satisfactory results on imputation performance, it is evidently slower than \texttt{missRanger} or \texttt{mixgb}. Applying machine learning algorithms to multiple imputation has attracted growing interest. However, some implementations can only undertake single imputation tasks, while others focus on accurately recovering the true data as a prediction task instead of reflecting suitable variability of missing data for more reliable statistical inferences. To the best of our knowledge, this is the first attempt to implement and evaluate multiple imputation through XGBoost with bootstrapping and predictive mean matching. We show that by using bootstrapping, and with the aid of predictive mean matching for continuous variables, \texttt{mixgb} can achieve imputation performances as good as that of \texttt{mice.cart}, which was previously considered to be the best at capturing complex data structure \citep{doove2014recursive}. In addition, we found that \texttt{mixgb} is exceptionally faster than MICE-based methods including \texttt{mice.cart}. Even though \texttt{missRanger} can rival \texttt{mixgb} on some occasions in terms of computational efficiency, its imputation quality based on the bias and variance criteria was inferior to \texttt{mixgb}. Our findings suggest that \texttt{mixgb} would be a promising automated MI approach for large and complex datasets. However, our findings may be limited to scenarios similar to simulation studies in this paper and may not generalize well to all scenarios. Although our simulation studies covered both continuous and categorical data, we have not investigated the imputation performance on data that includes categorical features with more than three levels. Additionally, it is worth noting that the speed and quality of imputation generally depend on hyperparameter settings of different methods, such as the number of trees in \texttt{mice.cart} and \texttt{missRanger}, the number of rounds in \texttt{XGBoost} and the number of threads when a multicore processor is available. Future work should therefore evaluate imputation performance with other data settings and a wider range of hyperparameter configurations. \bigskip \begin{center} {\large\bf Supplementary Materials} \end{center} All supplementary materials except the R package \texttt{misle} are available at \url{https://github.com/agnesdeng/mixgb}. \begin{description} \item[Additional tables and figures: ] The document \texttt{supplement.pdf} contains all simulation results for data generation models \ref{eqn:model1}-\ref{eqn:model6}. \item[R-package: ] R-package \texttt{misle} includes the implementation of \texttt{mixgb}. It is available at \url{https://github.com/agnesdeng/misle}. \item[Simulation R code: ] Code for simulation studies in Section \ref{sec:3} can be found in the folder \texttt{simulation}. \item[Datasets and R code for computational time: ] Details for datasets and code used in Section \ref{sec:4} can be found in the folder \texttt{time}. \item[R code for data example: ] R code for generating figures shown in Section \ref{sec:5} can be found in the folder \texttt{example}. \end{description} \bibliographystyle{JASA.bst}
{'timestamp': '2021-06-04T02:09:59', 'yymm': '2106', 'arxiv_id': '2106.01574', 'language': 'en', 'url': 'https://arxiv.org/abs/2106.01574'}
arxiv
\section{Introduction} The question of \emph{versatility} versus \emph{specialization} is often raised in the design of any multilingual translation system: is it possible to have a single model that can translate from any source language to any target one, or does it have to be multiple models each of which is in charge of one language pair? The former is referred to as a \emph{multilingual} model, while the latter are \emph{bilingual} ones. These two paradigms have their own strengths and limitations. From a practical point of view, a multilingual model seems to be highly desirable due to its simplicity in \emph{training} and \emph{deployment}, in terms of both time and space complexities. However, in terms of \emph{accuracy}, a multilingual model could be outperformed by its bilingual counterparts, especially on high-resource language pairs. \begin{figure}[!htb] \centering \begin{subfigure}[b]{0.6\linewidth} \centering \includegraphics[width=\linewidth]{transformer_simple_with_adapters.pdf} \caption{\label{fig:transformer}Transformer with adapters.} \end{subfigure} \begin{subfigure}[b]{0.38\linewidth} \centering \includegraphics[width=0.7\linewidth]{adapter_cell.pdf} \caption{\label{fig:adapter_cell} An adapter cell.} \end{subfigure}% \caption{\label{fig:adapters} (a) Transformer with adapters at its FFN sub-layers. For simplicity, layer normalization \cite{ba2016layer} is omitted. During fine-tuning, only the adapters are trained. (b) A typical adapter architecture.} \vspace{-6mm} \end{figure} In practice, a certain trade-off between the aforementioned factors (and thus more generally between versatility and specialization) has often to be made, and depending on the application, one can be favored more than the other. One way to move along the spectrum between multilingual and bilingual models is to use adapter tuning which consists in freezing pre-trained parameters of a multilingual model and injecting lightweight modules between layers resulting in the addition of a small number of language-specific trainable parameters. While adapter tuning was investigated for multilingual neural machine translation (NMT)~\cite{bapna2019simple}, to our knowledge, this paper proposes the first comprehensive analysis of adapters for multilingual speech translation. Our contributions are the following: (1) we show that both versatility and specialization can be achieved by tuning language-specific adapter modules on top of a multilingual system. Bilingual models with higher accuracy than the original multilingual model are obtained, yet keeping a low maintenance complexity; (2) starting from a different initialization point, we show that adapters can also be used as a glue to connect off-the-shelf systems (an automatic speech recognition (ASR) model and a multilingual denoising auto-encoder mBART~\cite{liu2020multilingual,tang2020multilingual}) to perform the multilingual ST task. Extensive experiments on the MuST-C dataset~\cite{di2019must} show that adapter-based fine-tuning can achieve very competitive results to full fine-tuning---while being much more parameter-efficient---in both standard and low-resource settings. Our code based on \textsc{fairseq S2T}~\cite{wang2020fairseq} is publicly available.\footnote{\url{https://github.com/formiel/fairseq/tree/master/examples/speech_to_text/docs/adapters.md}} % \section{Related Work} Adapter layers (or \textit {adapters} for short) were first proposed in computer vision~\cite{rebuffi2017learning}, then explored for text classification tasks in NLP~\cite{houlsby2019parameter}. Adapters are generally inserted % between the layers of a pre-trained network and finetuned on the adaptation corpus. \newcite{bapna2019simple} studied adapters in the context of NMT and evaluated them on two tasks: domain adaptation and massively multilingual NMT. \newcite{philip2020language} later introduced monolingual adapters for zero-shot NMT. Other research groups made contributions on the use of adapters in NLP~\cite{pfeiffer2020mad,pfeiffer2020adapterfusion} and a framework built on top of HuggingFace Transformers library~\cite{wolf2019transformers} was also released to facilitate the downloading, sharing, and adapting state-of-the-art pre-trained models with adapter modules \cite{pfeiffer2020adapterhub}. Also very relevant to our paper is the work of~\newcite{stickland2020recipes} where adapters are used to adapt pre-trained BART~\cite{lewis2020bart} and mBART25 (multilingual BART pre-trained on 25 languages)~\cite{liu2020multilingual} to machine translation. % As far as speech processing is concerned, adapters were mostly used in ASR \cite{kannan2019large,lee2020adaptable,winata2020adapt,zhu2020multilingual}. Recently, they have also been explored for ST as well but in a limited scope. \newcite{escolano2020enabling} addressed a very specific setting (zero-shot ST), while \newcite{li2020multilingual} and \newcite{gallego2021upc} used only one or two adapters right after a Transformer encoder.% \section{Adapters for Speech Translation} In this section, we describe the integration of adapters into a given backbone model for speech translation. As the Transformer~\cite{vaswani2017attention} has become common in speech processing,\footnote{For speech applications~\cite{inaguma2020espnet,wang2020fairseq}, the embedding layer of the encoder is often a small convolutional neural network \cite{fukushima1982neocognitron,lecun1989backpropagation}.} it will be used as our backbone. % Our method, however, can be applied to any other architectures, e.g\onedot} \def\Eg{E.g\onedot, dual-decoder Transformer~\cite{le2020dualdecoder}. % Adapter modules can be introduced into a Transformer in a \emph{serial} or \emph{parallel} fashion. Consider a layer represented by a function $f$ that produces an output ${\mathbf{y}}$ from an input $\mathbf{x}$, i.e\onedot} \def\Ie{I.e\onedot, ${\mathbf{y}} = f(\mathbf{x})$. This can be an entire encoder or decoder layer, or just one of their sub-layers (e.g\onedot} \def\Eg{E.g\onedot, the self-attention or the final feed-forward network (FFN) component). Suppose that our adapter layer is represented by a function $g$. The new ``adapted'' output is then given by: \begin{equation*} {\mathbf{y}}_{\mathrm{serial}} = g(f(\mathbf{x})),\quad {\mathbf{y}}_{\mathrm{parallel}} = f(\mathbf{x}) + g(\mathbf{x}). \end{equation*} Intuitively, a serial adapter modifies the output directly, while a parallel one performs the operations in parallel before merging its output to the layer. In Figure~\ref{fig:transformer}, we show an example of serial adapters being integrated to the Transformer, or more precisely to its FFN sub-layers. A common adapter module \cite{bapna2019simple} is presented in Figure~\ref{fig:adapter_cell}. Here $g$ is a small FFN with a residual connection. The first linear layer is typically a down projection to a bottleneck dimension, and the second one projects the output back to the initial dimension. Bottleneck allows us to limit the number of parameters. Other adapter architectures also exist, e.g\onedot} \def\Eg{E.g\onedot, \newcite{stickland2019bert} explored parallel adapters consisting of a multi-head attention (MHA) layer in a multi-task setup. For multilingual ST, we adopt the following general recipe for adapter-based fine-tuning. Starting from a pre-trained backbone, an adapter is added for each language pair and then finetuned on the corresponding bilingual data (while the rest of the backbone is frozen). The pre-trained backbone plays a crucial role in this recipe. We explore two common scenarios to obtain this pre-trained model, namely \emph{refinement} and \emph{transfer learning}. We present them in details, together with extensive experimental results, in Section \ref{sec:adapting_finetuning} and \ref{sec:transfer}. In the next section, we present our experimental setup. \section{Experimental Setup} \begin{table*}[htb!] \centering \resizebox{\linewidth}{!}{ \begin{tabular}{c|c| c | ccc | cc | l | llll llll | c } \toprule & & & \multicolumn{3}{c|}{\textbf{Adapter}} & \multicolumn{2}{c|}{\textbf{Finetune}} & {\textbf{\# params (M)}} & & & & & & & & & \\ & \textbf{Dict} & $D$ &$d$ & \textbf{ENC} & \textbf{DEC}& \textbf{ENC}& \textbf{DEC} & \textbf{trainable/total} & \textbf{de} & \textbf{es} & \textbf{fr} & \textbf{it} & \textbf{nl} & \textbf{pt} & \textbf{ro} & \textbf{ru} & \textbf{avg} \\ \midrule \multicolumn{9}{r|}{Training data (hours)}& 408 & 504 & 492 & 465 & 442 & 385 & 432 & 489 & \\ \midrule 1 & {mono} & {\multirow{8}{*}{\rotatebox[origin=c]{90}{256}}} & - & - & - & - & - & 8$\times$31.1/8$\times$31.1& 22.16 & 30.42& 27.92& 22.92& 24.10& 27.19 & 21.51& 14.36 & 23.82\\ 2 & {multi} & & - &- & - & - & - & 32.1/32.1 & 22.37 & 30.40 & 27.49 & 22.79 & 24.42 & 27.32 & 20.78 & 14.54 & 23.76\\ \cmidrule{4-18} 3 & {multi} & & 64 &- & \checkmark & - & - & 8$\times$0.2/33.7& 22.32 & 30.50 & 27.55 & 22.91 & 24.51 & 27.36 & 21.09 & 14.74 & 23.87\\ 4 & {multi} & & 64 & \checkmark & \checkmark & - & - & 8$\times$0.6/36.9 & 22.75 & 31.07 & 28.03 & 23.04 & 24.75 & 28.06 & 21.20 & 14.75 & 24.21\\ \cmidrule{4-18} 5 & {multi} & & 128 &- & \checkmark & - & - & 8$\times$0.4/35.3& 22.45 & 30.85 & 27.71 & 23.06 & 24.57 & 27.52 & 20.93 & 14.57 & 23.96\\ 6 & {multi} & & 128 & \checkmark & \checkmark & - & - & 8$\times$1.2/41.7 & 22.84$^{*}$ & 31.25$^{*}$ & 28.29$^{*}$ & 23.27$^{*}$ & 24.98$^{*}$ & 28.16$^{*}$ & 21.36$^{*}$ & 14.71 & 24.36\\ \cmidrule{4-18} 7 & {multi} & & - &- & - & - & \checkmark & 8$\times$14.6/8$\times$32.1& \underline{23.49} & 31.29 & {28.40} & 23.63 & 25.51 & 28.71 & 21.73 & 15.22 & 24.75\\ 8 & {multi} & & - &- & - & \checkmark & \checkmark & 8$\times$32.1/8$\times$32.1& 23.13$^{*}$ & \underline{31.39}$^{*}$ & \underline{28.67}$^{*}$ & \underline{23.80}$^{*}$ & \underline{25.52}$^{*}$ & \underline{29.03}$^{*}$ & \underline{22.25}$^{*}$ & \underline{15.44}$^{*}$ & \underline{24.90}\\ \midrule 9 & {mono} & {\multirow{10}{*}{\rotatebox[origin=c]{90}{512}}} & - & - & - & - & - & 8$\times$74.3/8$\times$74.3& 21.93 & 30.46 & 27.90 & 22.64 & 23.98 & 25.98 & 20.50 & 14.01 & 23.42 \\ 10 & {multi} & & - &- & - & - & - & 76.3/76.3 & 23.98 & 32.47 & 29.24 & 24.97 & 26.20 & 29.81 & 22.74 & 15.30 & 25.59 \\ \cmidrule{4-18} 11 & {multi} & & 64 &- & \checkmark & - & - & 8$\times$0.4/79.5& 24.24 & 32.52 & 29.47 & \color{HighlightColor}24.74 & \color{HighlightColor}26.13 & \color{HighlightColor}29.72 & \color{HighlightColor}22.53 & \color{HighlightColor}15.25 & \color{HighlightColor}25.57 \\ 12 & {multi} & & 64 & \checkmark & \checkmark & - & - & 8$\times$1.2/85.9 & 24.13 & 32.80 & 29.55 & \color{HighlightColor}24.90 & \color{HighlightColor}26.04 & 30.25 & \color{HighlightColor}22.73 & 15.31 & 25.72 \\ \cmidrule{4-18} 13 & {multi} & & 128 &- & \checkmark & - & - & 8$\times$0.8/82.7& 24.34 & 32.86 & 29.51 & \color{HighlightColor}24.73 & \color{HighlightColor}26.15 & 30.01 & \color{HighlightColor}22.58 & \color{HighlightColor}15.07 & 25.66\\ 14 & {multi} & & 128 &\checkmark & \checkmark & - & - & 8$\times$2.4/95.5& 24.30 & 32.61 & 29.72$^{*}$ & 25.07 & 26.29 & 30.46$^{*}$ & 22.99 & 15.47 & 25.86\\ \cmidrule{4-18} 15 & {multi} & & 256 &- & \checkmark & - & - & 8$\times$1.6/89.1& 24.38 & 32.78 & 29.69 & \color{HighlightColor}24.72 & 26.25 & 29.93 & \color{HighlightColor}22.63 & 15.40 & 25.72\\ 16 &{multi} & & 256 &\checkmark & \checkmark & - & - & 8$\times$4.8/114.7 & 24.61 & 32.94 & 29.67 & \highlight{25.12} & \color{HighlightColor}26.16 & \highlight{30.53} & \color{HighlightColor}22.66 & 15.31 & 25.88\\ \cmidrule{4-18} 17 & {multi} & & - & - &-& - & \checkmark & 8$\times$35.5/8$\times$36.3& \highlight{24.67} & \highlight{33.12} & \highlight{30.11} & {25.05} & \highlight{26.33} & 29.85 & \highlight{23.04} & \highlight{15.61} & \highlight{25.97}\\ 18 & {multi} & & - & - & - & \checkmark & \checkmark & 8$\times$76.3/8$\times$76.3& 24.54$^{*}$ & 32.95$^{*}$ & 29.96$^{*}$ & 25.01 & 26.31 & {30.04} & \color{HighlightColor}22.66 & 15.54$^{*}$ & 25.88\\ \bottomrule \end{tabular} } \caption{\label{tab:adating_finetuning_ablation}BLEU on MuST-C dev set for \textbf{refinement}. In the \textbf{Dict} column, \var{mono} and \var{multi} mean, respectively, monolingual and multilingual dictionary. $D$ is the Transformer hidden dimension. In the \textbf{Adapter} group, $d$ is the adapter bottleneck dimension, \var{ENC} and \var{DEC} mean adding adapters to encoder and decoder, respectively; and idem for the \textbf{Finetune} group. Rows 1--2 and rows 9--10 represent our bilingual and multilingual baselines for each $D$. Values lower than the multilingual baselines are colored in {\color{HighlightColor}blue}. The highest values in each group of $D$ are \underline{underlined}, while the highest values of each column are in \textbf{bold} face. {Furthermore, we select the top configurations (6, 8, 14, 18) and perform statistical significance test using bootstrap re-sampling~\cite{koehn2004statistical}. Results passing the test (compared to the corresponding multilingual baselines, with $p$-value $< 0.05$) are marked with a star.}} \vspace{-3mm} \end{table*} \subsection{Dataset} \paragraph{MuST-C} We evaluate our recipes on MuST-C~\cite{di2019must}, a large-scale one-to-many ST dataset from English to eight target languages including Dutch (\texttt{nl}), French (\texttt{fr}), German (\texttt{de}), Italian (\texttt{it}), Portuguese (\texttt{pt}), Romanian (\texttt{ro}), Russian (\texttt{ru}), and Spanish (\texttt{es}). Each direction includes a triplet of speech, transcription, and translation. Sizes range from 385 hours (\texttt{pt}) to 504 hours (\texttt{es}). % \paragraph{MuST-C-Imbalanced} {We built a low-resource version of MuST-C, called MuST-C-Imbalanced, in which we randomly keep only $X$\% of the original training data, where $X = 100$ for \texttt{es}, \texttt{fr}; $X = 50$ for \texttt{ru}, \texttt{it}; $X = 20$ for \texttt{nl}, \texttt{ro}; and $X = 10$ for \texttt{de}, \texttt{pt} (same order of the languages in the original MuST-C if we sort them in decreasing amount of data). The amount of speech data ranges from 41 hours (\texttt{de}) to 504 hours (\texttt{es}) in this version, better reflecting real-world data imbalance scenarios.} \subsection{Implementation details} Our implementation is based on the \textsc{fairseq S2T} toolkit~\cite{wang2020fairseq}. We experiment with two architectures: a small Transformer model with dimension $D=256$ and a medium one where $D=512$. All experiments use the same encoder with 12 layers. The decoder has 6 layers, except for the transfer learning scenario where we used the mBART decoder for initialization. We used 8k and 10k unigram vocabulary~\cite{kudo2018sentencepiece} for bilingual and multilingual models, respectively. The speech features are 80-dimensional log mel filter-bank. Utterances having more than 3000 frames are removed for GPU efficiency. We used SpecAugment~\cite{park2019specaugment} with LibriSpeech basic (LB) policy for data augmentation. We used the Adam optimizer~\cite{kingma2015adam} with learning rate linearly increased for the first 10K steps to a value $\eta_{\max}$, then decreased proportionally to the inverse square root of the step counter. For all adapter experiments, $\eta_{\max}$ is set to \num{2e-3}. For the others, however, we perform a grid search over three values $\{\num{2e-3}, \num{2e-4}, \num{2e-5}\}$ and select the best one on the dev set, as they are more sensitive to the learning rate.% \section{Refinement} \label{sec:adapting_finetuning} \begin{table*}[htb!] \centering \resizebox{\linewidth}{!}{ \begin{tabular}{c| c | ccc | cc | l | cccc cccc | c } \toprule & & \multicolumn{3}{c|}{\textbf{Adapter}} & \multicolumn{2}{c|}{\textbf{Finetune}} & {\textbf{\# params (M)}} & & & & & & & & & \\ & $D$ &$d$ & \textbf{ENC} & \textbf{DEC}& \textbf{ENC}& \textbf{DEC} & \textbf{trainable/total} & \textbf{de} & \textbf{es} & \textbf{fr} & \textbf{it} & \textbf{nl} & \textbf{pt} & \textbf{ro} & \textbf{ru} & \textbf{avg} \\ \midrule \multicolumn{8}{r|}{Training data (hours)}& 41 & 504 & 492 & 232 & 89 & 38 & 86 & 245 & \\ \midrule 1 & {\multirow{3}{*}{\rotatebox[origin=c]{90}{256}}} & - &- & - & - & - & 32.1/32.1 & 15.99 & 30.51 & 28.17 & 21.80 & 20.27 & 22.47 & 17.38 & 13.18 & 21.22\\ 2 & & 128 & \checkmark & \checkmark & - & - & 8$\times$1.2/41.7 & \underline{17.02} & 30.71 & \underline{28.42} & 22.37 & \underline{21.01} & \underline{23.74} & \underline{18.55} & 13.52 & \underline{21.92}\\ 3 & & - &- & - & \checkmark & \checkmark & 8$\times$32.1/8$\times$32.1& 16.93 & \underline{30.86} & 28.34 & \underline{22.42} & 20.86 & 23.44 & 18.49 & \underline{13.63} & 21.87 \\ \midrule 4 & {\multirow{3}{*}{\rotatebox[origin=c]{90}{512}}} & - &- & - & - & - & 76.3/76.3 & 17.05 & 31.92 & 29.06 & 22.91 & 21.64 & 24.15 & 19.18 & 14.09 & 22.50 \\ 5 & & 256 &\checkmark & \checkmark & - & - & 8$\times$4.8/114.7 & 17.46 & \textbf{31.94} & 29.09 & \textbf{23.11} & 21.76 & \textbf{24.96} & \textbf{19.50} & 14.10& \textbf{22.74}\\ 6 & & - & - & - & \checkmark & \checkmark & 8$\times$76.3/8$\times$76.3& \textbf{17.49} & 31.67 & \textbf{29.27} & 22.97 & \textbf{21.80} & 24.80 & 19.43 & \textbf{14.17} & 22.70\\ \bottomrule \end{tabular} } \caption{\label{tab:mustc_imbalanced}{BLEU on MuST-C dev set for \textbf{refinement} in the low-resource scenario where the models were trained on MuST-C-Imbalanced dataset. We refer to Table~\ref{tab:adating_finetuning_ablation} for other notation.}} \vspace{-3mm} \end{table*} \begin{table*}[!htb] \centering \resizebox{0.9\linewidth}{!}{ \begin{tabular}{l | l | l | cccc cccc | c} \toprule & {\textbf{Method}} & \begin{tabular}{@{}c@{}} \textbf{\# params (M)} \\ \textbf{trainable/total} \end{tabular} & {\textbf{de}} & {\textbf{es}} & {\textbf{fr}} & {\textbf{it}} & {\textbf{nl}} & {\textbf{pt}} & {\textbf{ro}} & {\textbf{ru}} & {\textbf{avg}} \\ \midrule \multirow{3}{*}{\rotatebox[origin=c]{90}{Ours}} & Baseline & 76.3/76.3 & 24.18 & 28.28 & \textbf{34.98} & 24.62 & \textbf{28.80} & \textbf{31.13} & 23.22 & 15.88 & 26.39 \\ & Best adapting & 8 $\times$ 4.8/76.3 & \textbf{24.63} & \textbf{28.73} & 34.75 & \textbf{24.96} & \textbf{28.80} & 30.96 & 23.70 & \textbf{16.36} & \textbf{26.61} \\ & Best fine-tuning & 8 $\times$35.5/8 $\times$ 76.3 & 24.50 & 28.67 & 34.89 & 24.82 & 28.38 & 30.73 & \textbf{23.78} & 16.23 & 26.50 \\ \midrule \multirow{3}{*}{\rotatebox[origin=c]{90}{\citeauthor{li2020multilingual}}} & \texttt{LNA-D} & 53.5/76.3 & 24.16 & 28.30 & 34.52 & 24.46 & 28.35 & 30.51 & 23.29 & 15.84 & 26.18 \\ & \texttt{LNA-E} & 48.1/76.3 & 24.34 & 28.25 & 34.42 & 24.24 & 28.46 & 30.53 & 23.32 & 15.89 & 26.18 \\ & \texttt{LNA-E,D} & 25.3/76.3 & 24.27 & 28.40 & 34.61 & 24.44 & 28.25 & 30.53 & 23.27 & 15.92 & 26.21 \\ \bottomrule \end{tabular} } \caption{\label{tab:comparison_to_li_et_al}BLEU on MuST-C test set. Our method compares favorably with \cite{li2020multilingual}.} \vspace{-3mm} \end{table*} In this section, a fully trained multilingual ST backbone is further refined on each language pair to boost the performance and close potential gaps with bilingual models. We compare adapter tuning with other fine-tuning approaches as well as the bilingual and multilingual baselines (the latter being the starting point for all fine-tuning approaches)~\cite{bapna2019simple}. % Starting from these backbones, we either add language-specific adapters and train them only, or we finetune the backbone on each language pair, either fully or partially. All these trainings are performed on MuST-C. The results are shown in Table~\ref{tab:adating_finetuning_ablation}. There are two main blocks corresponding to two architectures: $D=256$ (small) and $D=512$ (medium). Rows 1 and 9 provide the bilingual baselines, while rows 2 and 10 serve as the multilingual baselines for each block. % {In addition, we compare adapter-tuning with full fine-tuning and multilingual-training (baseline) on MuST-C-Imbalanced. Table~\ref{tab:mustc_imbalanced} displays the results for this set of experiments.} \paragraph{Bilingual \vs Multilingual} For the small architecture ($D=256$), the bilingual models slightly outperform their multilingual counterpart (rows 1, 2). Looking further into the performance of each language pair, the multilingual model is able to improve the results for 4 out of 8 pairs (\texttt{de}, \texttt{nl}, \texttt{pt}, \texttt{ru}), mainly those in the lower-resource direction, but the joint multilingual training slightly hurts the performance of higher-resource pairs such as \texttt{es}, \texttt{fr}, \texttt{it}, and \texttt{ro}. Finally, we observe that the medium model ($D=512$) performs better in the multilingual setting than the bilingual one (rows 9, 10). % \paragraph{Adapter tuning \vs Fine-tuning} Both recipes yield improvements over the multilingual baseline and recover the lost performance of higher-resource directions compared to the bilingual baseline for the small model ($D=256$). For the medium one ($D=512$), one adapter tuning (row 14) can slightly improve the scores in all directions and even approach the results of the best fine-tuning experiment (row 17) while maintaining much lower model sizes (95.5M \vs 8$\times$ 36.3M parameters). \paragraph{Low-resource scenario} The obtained results on small models show that adapter-tuning achieved the best performance, producing clear improvements over the baseline, especially for the low-resource languages: $+1.1$ BLEU on average on \texttt{nl}, \texttt{ro}, \texttt{de}, \texttt{pt}; $+0.3$ BLEU on average on \texttt{es}, \texttt{fr}, \texttt{ru}, \texttt{it}; which is competitive to full fine-tuning ($+0.9$ and $+0.4$ BLEU, respectively) while being more parameter-efficient as well as simpler for training and deployment (one model with adapters versus eight separate models). For larger models, however, the improvement is smaller: $+0.4$ BLEU on average on the lower-resource pairs and $+0.1$ on the higher-resource ones; while those of full fine-tuning are $+0.4$ and roughly no improvement, respectively. \begin{table*}[htb!] \centering \resizebox{\linewidth}{!}{ \begin{tabular}{c| ccc| c | l| cccc cccc | c} \toprule & \multicolumn{3}{c|}{\textbf{Adapter}} & \textbf{Finetune}& {\textbf{\# params (M)}}& & & & & & & & &\\ &$d$ & \textbf{ENC} & \textbf{DEC}& \textbf{xattn}& \textbf{trainable/total} & \textbf{de} & \textbf{es} & \textbf{fr} & \textbf{it} & \textbf{nl} & \textbf{pt} & \textbf{ro} & \textbf{ru} & \textbf{avg} \\ \midrule 1 & - & -& -& -& 8$\times$31.1/8$\times$31.1& 22.16 & 30.42& 27.92& 22.92& 24.10& 27.19 & 21.51& 14.36 & 23.82\\ \midrule 2 & - & - &- & \checkmark& 38 / 486 & 18.41 & 25.42 & 23.46 & 18.44 & 20.87 & 20.55 & 17.19 & 11.79 & 19.52\\ 3 & 512 & - & \checkmark &- & 101 / 587 & 0.94 & 0.65 & 0.93 & 0.76 & 0.95 & 0.89 & 0.52 & 0.93 & 0.82\\ 4 & 512 & - & \checkmark &\checkmark & 139 / 587 & 21.98 & 29.47 & 27.05 & 22.89 & 24.06 & 26.34 & 21.0 & 14.35 & 23.39 \\ 5 & 512 & \checkmark & \checkmark& -& 152 / 638 & 11.04 & 18.62 & 16.10 & 12.37 & 13.18 & 14.29 & 10.62 & 6.95 & 12.90\\ 6 & 512 & \checkmark & \checkmark &\checkmark& 190 / 638 & 22.62 & 30.85 & 28.23 & 23.09 & 24.43 & 26.56 & 22.13 & 14.92 & 24.10 \\ \bottomrule \end{tabular} } \caption{\label{tab:transfer_learning_all}BLEU on MuST-C dev set for \textbf{transfer learning} from pre-trained ASR and mBART models. We compare the results with the bilingual baselines (trained from scratch), shown in row 1 (which is identical to row 1 in Table~\ref{tab:adating_finetuning_ablation}). The column ``Finetune xattn'' means updating the cross-attention parameters. We refer to Table~\ref{tab:adating_finetuning_ablation} for other notation.} \vspace{-3mm} \end{table*} \paragraph{Results on test set} We select the best-performing fine-tuning recipes on the dev set (rows 16 and 17 in Table~\ref{tab:adating_finetuning_ablation}) for evaluation on the test set. For reference, we also include the multilingual baseline (row 10). Moreover, to go beyond conventional fine-tuning approaches, we also compare our recipes with a contemporary work in which only several components of the network are finetuned~\cite{li2020multilingual}. For a fair comparison, we did not use large pre-trained components such as wav2vec~\cite{baevski20wav2vec} or mBART~\cite{tang2020multilingual} but instead considered the same pre-trained components used in our previous experiments. Following~\cite{li2020multilingual}, we considered six variants: fine-tuning LayerNorm + Attention in the encoder (\texttt{LNA-E}), or the decoder (\texttt{LNA-D}), or both (\texttt{LNA-E,D}); each with or without the length adapter. % We found that adding the length adapter did not help in our experiments. % Table~\ref{tab:comparison_to_li_et_al} shows that our approach compares favorably with \cite{li2020multilingual} in terms of both performance and parameter-efficiency.% \paragraph{Other comments} For small models, the encoder adapters boost the performance ($0.3$--$0.4$ BLEU on average) in all directions (rows 3 and 4, 5 and 6, Table \ref{tab:adating_finetuning_ablation}), indicating that language-specific adapters can tweak the encoder representations to make them better suited for the decoder. In larger models, however, the impact of the encoder adapters is varied depending on languages and bottleneck dimensions. We also notice that increasing the bottleneck dimension slightly improves performance while remaining parameter-efficient. % Fine-tuning remains the best option to optimize the models in most cases but leads to much larger model sizes. {The adapter-tuning approach is competitive to fine-tuning while being much more parameter-efficient. % } \section{Transfer Learning} \label{sec:transfer} In this section, we show that adapters can be used to combine available pre-trained models to perform a multilingual ST task. In particular, we initialize the encoder using a pre-trained ASR encoder (on MuST-C)\footnote{{Pre-training on ASR data and then transferring to ST is not new but rather standard. See, e.g\onedot} \def\Eg{E.g\onedot, \citet{bansal2019pretraining}}.} provided by~\newcite{wang2020fairseq} and the decoder using mBART50, a multilingual denoising auto-encoder pre-trained on 50 languages~\cite{tang2020multilingual}. We tune language independent cross-attention and language-specific adapters on top of these backbone models (using MuST-C as well). The results presented in \autoref{tab:transfer_learning_all} highlight that fine-tuning cross-attention is crucial to transfer to multilingual ST (rows 3 and 5 show poor results without doing so). Adding adapters to the backbone decoder (row 4) or to both encoder and decoder (row 6) further boosts performance, demonstrating the ability of adapters to connect off-the-shelf models in a modular fashion. The best-performing model in this recipe (row 6) also outperforms bilingual systems (row 1) despite having fewer trainable parameters (190M \vs 248M). It is also important to mention that while we experiment on 8 target languages of MuST-C corpus, the multilingual ST model of row 2 should be practically able to decode into 50 different target languages. Investigating such a zero-shot ST scenario is left for future work. \section{Conclusion} We have presented a study of adapters for multilingual ST and shown that language-specific adapters can enable a fully trained multilingual ST model to be further specialized in each language pair. With these adapter modules, one can efficiently obtain a single multilingual ST system that outperforms the original multilingual model as well as multiple bilingual systems while maintaining a low storage cost and simplicity in deployment. In addition, adapter modules can also be used to connect available pre-trained models such as an ASR model and a multilingual denoising auto-encoder to perform the multilingual speech-to-text translation task. \section*{Acknowledgments} This work was supported by a Facebook AI SRA grant, and was granted access to the HPC resources of IDRIS under the allocation 2020-AD011011695 made by GENCI. It was also done as part of the Multidisciplinary Institute in Artificial Intelligence MIAI@Grenoble-Alpes (ANR-19-P3IA-0003). We thank the anonymous reviewers for their insightful questions and feedback. \bibliographystyle{acl_natbib}
{'timestamp': '2021-07-14T02:01:40', 'yymm': '2106', 'arxiv_id': '2106.01463', 'language': 'en', 'url': 'https://arxiv.org/abs/2106.01463'}
arxiv
\section{Analysis} \begin{table} \small \centering \begin{tabular}{lc|c} \toprule &{In Domain} & {Out of Domain}\\ \hline & {SQuAD1.1 + Hotpot QA}& {Other MRQA datasets}\\ \midrule CLS & 63.5$\pm$0.4 & 62.3$\pm$0.5 \\ Ours & 65.8$\pm$0.3 & 63.7$\pm$0.3 \\%& 66.8$\pm$0.4 & 43.1\% & 64.1$\pm$0.3 & 41.6\% Diff. & 2.3\% &1.4\%\\ \bottomrule \end{tabular} \caption{CLS token ablation results, all numbers refer to calibration accuracy. Using CLS token as a feature shows a strong calibration performance, lagging behind question context encoding from the RC model only by a few points. The gap is even smaller in out of domain setting. } \label{tab:cls_token_ablation} \end{table} \subsection{Task-Agnostic Representation vs. Representation from QA Model}\label{subsec:task-agnostic} Our study has shown that input example embedding is very useful, adding complementary power to model confidence features. Based on this result, we further ask the question, is it possible to build a calibrator without accessing the model parameters, but only a small amount of calibration training data (which consists of questions, context, and whether the model's prediction is correct or incorrect)? We train a calibrator that does not have any access to the QA model parameters and only takes the model's predictions on a small set of training data (a couple thousand of QA examples). This calibrator uses a standard pretrained language model (BERT) to encode [CLS$; (q_i, c_i)$] and takes the final layer hidden representation of the [CLS] token as a feature. Table~\ref{tab:cls_token_ablation} shows the performance of the [CLS] token classifier. Surprisingly, this calibrator outperforms the MaxProb baseline (in Table~\ref{tab:out_of_domain}) in all settings and outperforms ~\citet{kamath2020selective} (in Table~\ref{tab:out_of_domain}) in most settings, indicating information about the question and context might be more useful than the QA model's confidence. Using the input example embedding from the QA model shows only 1-3 point gains than using the CLS token embedding. This trend holds for across various settings (more results in Table~\ref{tab:cls_token_ablation_full} in Appendix). \subsection{Quality of Back Translation}\label{subsec:qual_backtranslation} Question paraphrasing~\cite{dong-etal-2017-learning} can improve performances of QA models. Similarly, both question and context paraphrasing improves calibration performance. In this section, we investigate the quality of backtranslation used in our study. We manually inspect 100 question paraphrasing from SQuAD 2.0 dataset. 71 examples maintain the original meaning, 12 examples change its meanings, and 17 examples are hard to distinguish. One common pattern for meaning change is when proper nouns in the original sentences are missing and incorrectly translated (e.g. John Calvin $\rightarrow$ Jean Calvin). \begin{table} \centering \footnotesize \begin{tabular}{c|p{21em}} \hline $q$ & In what country is Normandy located? \\ $q'$ & What country is Normandy in? \\ \hline $q$ & When did Edward return? \\ $q'$ &When did Edward come back? \\ \hline $q$ & How would one write T(n) = 7n2 + 15n + 40 in big O notation?\\ $q'$ &How do you write T(n) = 7n2 + 15n + 40? \\ \hline $q$ & What kind of arches does Norman architecture have? \\ $q'$ & What kind of arches does Norman's building have? \\ \hline \end{tabular} \caption{Question back translation samples from SQuAD 2.0 dataset. The first row (q) refers to the original question, and the second row ($q'$) refers to backtranslated question. In the third example, back translation introduces an error. } \label{tab:my_label} \end{table} We study how much variability is introduced during paraphrasing by studying divergence between the original sentence and the paraphrased sentence. We calculate the sentence BLEU score with \emph{NLTK} \cite{bird2009nltk}, using the original text as source and the back-translated text as target for both question paraphrasing and context paraphrasing. The average sentence BLEU score is larger than 0.55 for all datasets, indicating back-translation introduces relatively minor changes in phrasing. \paragraph{Visualization} Figure~\ref{fig:hidden_represetation} shows a visualization of the question context embeddings from HotpotQA and SQuAD. We use linear discriminant analysis~\citep{pedregosa2011scikit} to plot input example embeddings and observe that embeddings from the same dataset are closer to each other. It demonstrates that embeddings are almost linearly separable between domains, but it is much harder to distinguish correct answers from incorrect ones. \begin{figure} \centering \footnotesize \vspace{-1em} \includegraphics[width=0.45\textwidth]{figure/figure_hidden.pdf} \vspace{-1.3em} \caption{A visualization for the input example embedding from HotPotQA and SQuAD datasets. We denote the data domain by markers with different shapes and denote the correctness with different colors. The X-axis and Y-axis denote the first and second dimensions extracted by linear discriminant analysis, respectively.}\vspace{-0.4em} \label{fig:hidden_represetation} \end{figure} \begin{table} \footnotesize \centering \begin{tabular}{lc|c} \toprule & {In Domain} & {Out of Domain}\\ & {SQuAD1.1 + NQ}& { Other MRQA datasts}\\ \hline Xgboost & 67.4$\pm$0.5 & 65.4$\pm$0.3 \\ LR & 66.6$\pm$0.3 & 64.7$\pm$0.3 \\ KNN & 66.3$\pm$0.2 & 64.6$\pm$0.3 \\ \bottomrule \end{tabular} \caption{Ablation study on different classifiers with features (Ours + features). All numbers refer to calibration accuracy.} \label{tab:ablation_classifier} \end{table} \paragraph{Choice of Calibrator Architecture} We test if our results are sensitive to the choice of classifiers: XGBoost, logistic regression (LR), and k-nearest neighbors (KNN). Table~\ref{tab:ablation_classifier} indicates our gains hold across different classifiers. Full experimental results can be found in Appendix. \paragraph{Choice of Pivot Language} We test whether the choice of pivot language in backtranslation impacts performances. We find little difference between pivoting through German or French (See Table~\ref{tab:backtrans_ablation}). \begin{table}[t] \small \centering \resizebox{1.0\columnwidth}{!}{ \begin{tabular}{lc|c|c} \toprule &Lang-& \multicolumn{1}{c|}{In Domain} & \multicolumn{1}{c}{Out of Domain}\\ & uage &\multicolumn{1}{c|}{{SQuAD1.1 + NQ}}& \multicolumn{1}{c}{{Other MRQA datasets }}\\ \hline $ \phi(q_i,c'_i)$ &FR & 73.2$\pm$0.4 & 66.7$\pm$0.5\\% & 72.1$\pm$0.5 \\ $ \phi(q_i,c'_i)$ &DE & 73.0$\pm$0.4 & 66.5$\pm$0.5 \\%& 71.9$\pm$0.6 \\ \hline $ \phi(q'_i,c_i)$ &FR& 72.5$\pm$0.4 & 65.8$\pm$0.5 \\%& 71.4$\pm$0.5 \\ $ \phi(q'_i,c_i)$ &DE & 72.8$\pm$0.3 & 66.1$\pm$0.4 \\%& 71.7$\pm$0.5 \\ \bottomrule \end{tabular}} \caption{Calibration accuracy for different pivot languages: French vs. German, using calibrator with features (Ours + features). } \label{tab:backtrans_ablation} \end{table} \section*{Appendix} \section{Conclusion} We introduce a richer feature space for question answering calibrators with question and context embeddings and paraphrase-augmented inputs. Our work suggests deciding the correctness of a QA system depends on both the semantics of the question-context and the confidence of the model. We thoroughly test our calibrator in domain shift, adversarial, and open domain QA settings. The experiments show noticeable gains in performance across all settings. We further demonstrate our calibrator's general applicability by using it as a reranker in extractive open domain QA. To summarize, our calibrator is simple, effective and general, with potential to be incorporated into existing models or extended for other NLP tasks. \section{Experimental Settings} In this section, we describe the experimental setting, dataset setups and baseline systems. Table~\ref{tab:experiement_setting} summarizes the evaluation scheme. A separate calibrator is trained for each calibrator train data configuration. \subsection{Data} For all in-domain reading comprehension experiments, we randomly split the data into training, development, and test (40\%,10\%,50\%), following regression and classification benchmarks ~\cite{asuncion2007uci}. Further, we assume only limited supervised data is available for calibrators, simulating a set up where we have a general QA model and small number of annotated data reserved for calibration. \paragraph{Standard RC } We test two in domain settings and two out of domain settings. We randomly sample 4K examples from each of the datasets included in the training portion of the MRQA shared task~\cite{fisch2019mrqa} (SQuAD~\cite{rajpurkar2016squad}, NewsQA~\cite{trischler2017newsqa}, TriviaQA~\cite{joshi2017triviaqa}, SearchQA~\cite{dunn2017searchqa}, HotpotQA~\cite{yang2018hotpotqa}, Natural Questions~\cite{kwiatkowski2019natural}). We train two calibrators, one with the SQuAD1.1 + HotpotQA datasets and another with the SQuAD1.1 + NQ datasets. For out of domain evaluation, we use four remaining datasets from MRQA shared task training set. \paragraph{Adversarial RC (SQuAD 1.1 Adversarial)} The adversarial examples manipulate the evidence paragraph to change the model prediction but not the gold answer. We sample 2K examples from the development portion of the SQuAD 1.1 ~\cite{jia2017adversarial} AddSent dataset, which appends an additional sentence that looks similar to the question at the end of the paragraph. For the out-of-domain case, we train the calibrator on 6K examples (1K each sampled from MRQA datasets) and test on adversarial examples. \paragraph{Unanswerable RC (SQuAD 2.0)} We sampled 2K examples from the development portion of the SQuAD 2.0 dataset~\cite{rajpurkar2018know}, which contains examples where the answer to the question cannot be derived from the provided context. Crowdworkers posed questions that were impossible to answer based on the paragraph alone while referencing entities in the paragraph and ensuring that a plausible answer is present. For out of domain setting, we train the calibrator on 6K examples (1K each sampled from MRQA datasets) and test on SQuAD 2.0 dataset (same as adversarial RC setting). \paragraph{Open Retrieval QA} We use the open retrieval version of the NQ ~\cite{Lee2019LatentRF}. We split its training data 60\% and 40\% for calibrator training and validation and use the NQ test set for testing. \subsection{Comparison Systems} We summarize the calibrators used in our study in Table~\ref{tab:mode_detail}. All calibrators are trained with the same gradient boosting library XGBoost~\cite{chen2016xgboost}, and they only differ in the feature sets. These calibrators are efficient, trained within a few minutes even with our new feature space. \begin{table} \centering \footnotesize \small \begin{tabular}{l|l|l} \toprule \bf{QA model} & \bf{Calibrator Feature Set} & \bf{\# Features} \\ \midrule \multirow{6}{*}{RC} &MaxProb & 1 \\ & features: \citet{kamath2020selective} &17 \\ & Ours & $m$ \\ & + features& 17 + $m$ \\ & + features + $ \phi(q_i,c'_i)$ &17 + 2$m$\\ & + features + $ \phi(q'_i,c_i)$ &17 + 2$m$ \\%& N\\ \midrule \multirow{2}{*}{Extractive} & Unnormalized Scores & 2 \\ & Normalized Scores & 2 \\ (DPR) & Ours + Normalized Score & 2 + 2$m$ \\ \midrule Generation& Likelihood & 1\\ (T5)& Ours + Likelihood & 1 + $m$ \\ \bottomrule \end{tabular} \caption{Comparison Systems: different calibrators explored for three base QA models. The last two QA models are for open retrieval QA task. The dimension of question context embedding is $m$ defined in Eqn \eqref{eq:feature} (eg. $m$ is 768 for reading comprehension). } \label{tab:mode_detail} \end{table} \subsubsection{Reading Comprehension} \label{subsec:rc} \paragraph{MaxProb} is the simplest baseline that relies on the model's confidence score. The model score is the sum of the logit scores of the start and end of the answer span for reading comprehension. For open retrieval question answering, the model first determines the passage with the highest passage-match score and then extracts the answer span from this passage. Formally, given the set of answer spans $Y$, MaxProb with model $M_\theta$ estimates confidence on input $x_i$ as: $$ \textit {MaxProb } =\max_{y \in Y} M_\theta \left(y \mid x_i \right), $$ where $M_\theta (y \mid x_i )$ refers to the model score for candidate answer $y$. \paragraph{\citet{kamath2020selective}} uses a calibrator based on the following general features: passage length, the predicted answer length, and the top-5 largest softmax probabilities generated by the model. They also use test time dropout~\cite{gal2016dropout}: given an input $x_i$ and model $M_\theta$, compute $M_\theta(x_i)$ with $K$ different dropout masks, obtaining prediction distributions $\hat p_1, ..., \hat p_k$, where each $\hat p_i$ is a probability distribution over $Y$. Two options are used as confidence estimates. First, taking the mean of $\hat p_i$ \citep{lakshminarayanan2017simple} $$ \textit {Dropout Mean }=\frac{1}{K} \sum_{i=1}^{K} \hat {p_i}. $$ Second, taking the variance of the $\hat p_i$ \cite{feinman2017detecting, smith2018understanding} $$ \textit{Dropout Variance} = \operatorname{Var}\left[\hat{p}_{1}, \ldots, \hat{p}_{K}\right]. $$ \noindent The dimension of $\textit{MaxProb}$, 2th-5th probability, $\textit{Dropout Mean}$, $\textit{Dropout Variance}$, context length and prediction length are 1, 4, 5, 5, 1, 1, respectively. In total, this feature set contains 17 features. \begin{table*} \footnotesize \centering \begin{tabular}{lccc|ccc} \toprule & \multicolumn{3}{c|}{In Domain} & \multicolumn{3}{c}{Out of Domain}\\ & Calib. Accu & AUROC & Cov@Acc=80\% & Calib. Accu & AUROC & Cov@Acc=80\%\\ \hline & \multicolumn{3}{c|}{SQuAD1.1 + HotpotQA}& \multicolumn{3}{c}{SQuAD1.1 + HotpotQA / Other MRQA datasets}\\ \hline MaxProb & 58.2$\pm$0.2 & 58.0$\pm$0.3 & 38.4\% & 56.8$\pm$0.2 & 56.5$\pm$0.2 & 38.3\%\\ \citet{kamath2020selective} & 62.6$\pm$0.5 & 62.3$\pm$0.7 & 40.9\% &61.2$\pm$0.4 & 60.7$\pm$0.5 & 39.7\%\\ Ours & 65.8$\pm$0.3 & 66.8$\pm$0.4 & 43.1\% & 63.7$\pm$0.3 & 64.1$\pm$0.3 & 41.6\% \\ + features & 67.4$\pm$0.5 & 68.5$\pm$0.4 & 43.3\% & 65.4$\pm$0.3 & 66.9$\pm$0.3 & 42.7\%\\ + features + $ \phi(q_i,c'_i)$ & \bf{69.2$\pm$0.4} & \bf{70.3$\pm$0.4}& \bf{44.3\%} & \bf{67.6$\pm$0.4} & \bf{68.8$\pm$0.5}& \bf{43.9\%} \\ + features + $ \phi(q'_i,c_i)$ & 66.8$\pm$0.3 & 67.9$\pm$0.3 & 42.4\% & 64.7$\pm$0.4 & 66.2$\pm$0.3 & 42.5\%\\ \hline & \multicolumn{3}{c|}{SQuAD1.1 + NQ}& \multicolumn{3}{c}{SQuAD1.1 + NQ / Other MRQA datasets}\\ \hline MaxProb & 64.8$\pm$0.3 & 71.5$\pm$0.3 & 49.2\% & 61.4$\pm$0.2 & 66.7$\pm$0.3 & 45.9\% \\ \citet{kamath2020selective} & 68.5$\pm$0.4 & 75.5$\pm$0.6 & 53.4\% & 64.1$\pm$0.6 & 69.2$\pm$0.5 & 51.5\% \\ Ours & 69.5$\pm$0.3 & 76.3$\pm$0.5 & 57.8\% & 64.3$\pm$0.4 & 69.4$\pm$0.4 & 54.3\% \\ + features & 70.3$\pm$0.4 & 77.0$\pm$0.3 & 59.1\% & 64.9$\pm$0.5 & 70.4$\pm$0.5 & 56.5\%\\ + features + $ \phi(q_i,c'_i)$ & \bf{73.2$\pm$0.4} & \bf{79.4$\pm$0.3} & \bf{60.7\%} & \bf{66.7$\pm$0.5} & \bf{72.1$\pm$0.5} & \bf{57.6\% }\\ + features + $ \phi(q'_i,c_i)$ & 72.5$\pm$0.4 & 78.7$\pm$0.3 & 59.3\% & 65.8$\pm$0.5 & 71.4$\pm$0.5& 55.9\% \\ \bottomrule \end{tabular} \caption{Calibration results on standard reading comprehension datasets. In the out of domain setting, we first list the training dataset of calibrator, then the test dataset. } \label{tab:out_of_domain} \end{table*} \paragraph{Ours} represents a calibrator that is trained with the question context embedding, $\phi(q_i, c_i)$ in Eqn \eqref{eq:feature}. `+ features' refers to augmenting features from \citep{kamath2020selective}, described above. Augmenting the feature sets with question context embeddings from backtranslated questions is denoted as `+$ \phi(q'_i,c_i)$', and augmenting the feature sets with question context embeddings from backtranslated contexts is denoted as `+$ \phi(q_i,c'_i)$' from Eqn. \eqref{eq:bt}. \subsubsection{Open Retrieval QA} We consider separate calibrators for two different approaches~\cite{karpukhin2020dense,Raffel2020ExploringTL}. \paragraph{Extractive (Retrieve-And-Predict)} We consider two baseline calibrators: one takes the product of normalized passage score (normalized across all passage candidates) and answer score (normalized across the top 10 answer spans for each passage), and another takes the product of unnormalized passage and answer scores. Then, we introduce calibrator augmented with our input example embedding. We include two example embeddings as features: one is the question context embedding as used in the reading comprehension setting (from Eqn~\ref{eq:feature}), and another is the average of the answer span start token representation and the answer span end token representation. \paragraph{Generation based (Seq2Seq)} For seq2seq models~\cite{Raffel2020ExploringTL}, the output answer space includes all sentences that can be generated with conditional language model. Thus, instead of MaxProb, we use the likelihood of the generated answer (i.e., the product of the conditional probabilities for each token in the generated answer) as a baseline. Then, we introduce calibrator with our input example embedding (from Eqn~\ref{eq:feature}). \section{Introduction} Despite rapid progress in AI models, building a question answering (QA) system that can always correctly answer any given query is beyond our reach. Thus, questioners have to {interpret} the model prediction, deciding whether to trust it. We study providing an accurate estimate of the correctness of model prediction for each example at test time. As making incorrect predictions can be much more costly than making no prediction (e.g., missing diagnosis is much more costly than querying human experts), calibrators can bring practical benefits~\cite{kamath2020selective}. Existing work on calibration focuses on mdoel confidence, such as the max probability of the predicted class~\cite{guo2017calibration,Desai2020CalibrationOP}. Unlike classification tasks, question answering explores large output space, either through answer generation~\cite{Raffel2020ExploringTL,Lewis2020RetrievalAugmentedGF} or selecting a span from provided documents~\cite{rajpurkar2016squad}. In both settings, optimal decoding is often prohibitively expensive, and heuristic decoding is a standard practice~\cite{Seo2017BidirectionalAF}. Thus, relying on the model's confidence score alone is not sufficient for calibration~\cite{Kumar2019CalibrationOE}. Nonetheless, prior work~\cite{kamath2020selective,Jagannatha2020CalibratingSO} relied heavily on model confidence, such as the max probability of the predicted answer, together with a handful of manually crafted features containing little information about the input, such as the length of the question. We empower the calibrator by introducing an input example embedding from a pre-trained language model~\cite{alberti2019bert,liu2019roberta} finetuned on QA supervision data as additional features. With this simple and general feature, calibrator can identify questions regarding rare entities or examples with little lexical overlap between the question and the context. We bring further gains by paraphrasing questions or contexts respectively through back translation~\cite{Sennrich2016ImprovingNM}, providing lexical variations of the question and the context and enriching the feature space We evaluate our calibrator with internal metrics (i.e., calibration accuracy) and external metrics (i.e., impact on QA performance). We first evaluate calibrators in reading comprehension settings introduced in~\citet{kamath2020selective} -- in-domain~\cite{rajpurkar2016squad,kwiatkowski2019natural}, out of domain~\cite{fisch2019mrqa}, and adversarial~\cite{jia2017adversarial}. Then, we expand calibration study to more challenging open retrieval QA setting~\cite{trec, chen2017}, where a system is not provided with an evidence document. We adapt our calibrator for state-of-the-art generation based~\cite{Raffel2020ExploringTL} and extractive (retrieve-and-predict) QA models~\cite{karpukhin2020dense}, showing gains in both models. While calibration accuracy is higher in the generation based model, the extractive method provides better answer coverage above fixed accuracy. Lastly, we use calibrator as a reranker for the answer span candidates in an extractive open retrieval QA model~\cite{karpukhin2020dense}, showing modest gains. We provide rich ablation studies on design choices for our calibrator, such as the choice of base model to derive input example encoding. Our simple input example embedding from pretrained language models shows consistent gains in all settings and datasets. Without any manual engineering specific to the question answering task, our calibrator could be easily adapted to other tasks with rich output space. \section{Methods} We propose two general approaches to improve binary calibrator: new feature vector, a dense representation of the input example (Section~\ref{subsec:feature}) and data augmentation with backtranslation which further improves the new feature vector (Section~\ref{subsec:paraphrase}). While both are simple, well-established formula for improving end tasks in NLP, neither has been explored in the context of calibration, as prior work assumed model confidence score is the most prominent signal. We follow prior work~\cite{kamath2020selective} for calibrator architecture and focus on improving its feature space. \subsection{Calibrator Architecture} A binary classifier is trained using the gradient boosting library XGBoost~\cite{chen2016xgboost}, which classifies each test example as correctly answered by the base QA model or not. This calibrator does not share its weights with the base QA models. We finetune the following hyper-parameters on the development set: colsample by level, colsample by node, colsample by tree, learning rate, and the number of estimators. All calibrators are trained five times, each with different data partitions and random seeds. We report the variances in the results. \subsection{Input Example Embedding Feature From Base QA Model}~\label{subsec:feature} Prior work uses manually designed features based on the scores to the predicted answer (details in Section~\ref{subsec:rc}). Such features retain little information about input example -- e.g, question and the evidence context. Inspired by the recent works in machine learning \citep[e.g.][]{song2019unsupervised, hendrycks2019using}, which use hidden vectors to classify in-domain and out-of-domain data, we introduce an input example embedding, a new feature vector that represent question and (optionally) evidence context to a calibrator. Our input example embedding is a fixed dimensional vector representing an input example, similar to sentence embeddings~\cite{Conneau2017SupervisedLO}. It differs in that the representation is taken from the final layer of base QA model, which is trained with supervision from question answering data and it encodes question and (optional) evidence context simultaneously. In Section~\ref{subsec:task-agnostic}, we report minor performance degradation from using embeddings from generic pretrained language model instead. Each base model processes input example, either query $q_i$ or query, context pair $(q_i, c_i)$ to generate a sequence of hidden vectors, which will be compressed into a fixed dimensional vector to be used as calibrator feature.\footnote{For simplicity, we write equations with $(q_i, c_i)$ pair as an input, when only query is provided (e.g., generation based open retrieval QA method) $c_i$ is empty.} We denote the input example as a sequence of tokens $\mathbf{t} = (t_0, t_1, \cdots, t_n)$ where $n$ is the length of the input. We pass the sequence $\mathbf{t}$ through base QA model and get $(\mathbf{h}_0, \mathbf{h}_1, \cdots, \mathbf{h}_n)$ where $\mathbf{h}_i$ is the corresponding final-layer hidden state of $t_i$, and $\mathbf{h}_i = (\mathbf{h}_{i, 0}, \cdots, \mathbf{h}_{i, m})$ where $m$ is the number of hidden dimensions. Then, we get the $m$-dimensional feature vector \begin{equation} \label{eq:feature} \phi(q_i,c_i) = [\frac{1}{n}\sum_{i=1}^{n} \mathbf{h}_{i, 0}; \cdots; \frac{1}{n}\sum_{i=1}^{n} \mathbf{h}_{i, m})], \end{equation} where each dimension is an average across the length $n$. We then train a binary classifier using these features as a calibrator. We now describe our base QA models to get this hidden representations. \subsubsection{Base QA Model} We use standard span prediction architecture for RC, and a generation based model and an extractive model for open retrieval QA. For RC and extractive open retrieval QA model, we use a standard span prediction architecture based on a pretrained language model~\cite{Devlin2018BERTPO}, which predicts start and end index of the answer span separately with softmax layer. The output hidden vector sequence will equal the sum of the length of question and the length of evidence context. For the open retrieval QA setting, the extractive model first retrieves a passage from the corpus and predicts an answer span from it. We use the best model from dense passage retrieval (DPR)\citep{karpukhin2020dense}.\footnote{\url{https://github.com/facebookresearch/DPR}} Specifically, this model retrieves the top $100$ retrieved passages as input and trains a span prediction model, which optimizes a softmax cross-entropy loss to select the correct passage among the candidates, and the answer span prediction loss. The model then selects the answer span with the highest answer span score (sum of the start and end logit score) from the passage with the highest passage score. In this setting, $\mathbf{t}$ is a concatenation of question $q_i$ and the context $c_i$. For generation based model, we use a sequence-to-sequence (seq2seq) model, specifically T5-small~\citep{Raffel2020ExploringTL}, which takes the question as an input and generates answer tokens. For this base QA model, $\mathbf{t}$ only consists of the query since the context is not provided. \noindent \textbf{Data} For all experiments in RC, we train the model on the SQuAD 1.1 dataset. For open retrieval QA, models are trained on the Natural Questions (NQ) dataset ~\citep{kwiatkowski2019natural} following the data split from ~\citet{Lee2019LatentRF}. \begin{table*} \centering \footnotesize \begin{tabular}{l|l|c|c|c} \toprule \bf{Task} & \bf{Setup}& \bf{Base QA model (train)} & \bf{Calibrator (train \& dev)} & \bf{Calibrator (test)} \\ \midrule & In domain& & SQuAD 1.1 + HotpotQA & SQuAD 1.1 + HotpotQA \\ \multirow{2}{*}{Standard RC} & Out of domain & & SQuAD 1.1 + HotpotQA & Other MRQA \\ & In domain& & SQuAD 1.1 + NQ & SQuAD 1.1 + NQ \\ & Out of domain & SQuAD 1.1 & SQuAD 1.1 + NQ & Other MRQA \\ \multirow{2}{*}{Adversarial RC}& In domain & & SQuAD 1.1 Adversarial & SQuAD1.1 Adversarial \\ & Out of domain & & MRQA & SQuAD1.1 Adversarial \\ \multirow{2}{*}{Unanswerable RC}& In domain & & SQuAD 2.0 & SQuAD 2.0 \\ & Out of domain & &MRQA & SQuAD 2.0 \\ \hline \hline \\ [-2.0ex] Open Retrieval QA &In domain & \multicolumn{2}{c|}{NQ Training Set} & NQ Test Set \\ \bottomrule \end{tabular} \caption{Experiment Configuration. In domain / Out of domain distinguishes whether the training data for calibrator is different from the test data. } \label{tab:experiement_setting} \end{table*} \subsection{Data Augmentation Via Paraphrasing}~\label{subsec:paraphrase} Paraphrase generation can improve QA models~\cite{Yu2018QANetCL} by handling language variation. Compared to sentence retrieval \cite{du2020self} and language model based example generation \cite{anaby2020not}, backtranslation can capture the ambiguity of questions and answer\cite{singh2019xlda}. Given a $(q_i, c_i)$ pair, we use back translation~\cite{Sennrich2016ImprovingNM} to generate paraphrases of the question $q'_i$ from $q_i$ and the evidence context $c'_i$ from $c_i$. We use standard transformer-based neural machine translation models~\cite{mariannmt} trained on WMT dataset.\footnote{\url{https://huggingface.co/transformers/model_doc/marian.html}} We first translate the original sentences to a pivot language and then translate them back to the source language. To guarantee translation quality, French and German are used as the pivot languages. We use beam search decoding with beam size as 4 and truncate the context length to 512, as the reading comprehension model truncates the context anyway. We analyze the quality of backtranslation in Section~\ref{subsec:qual_backtranslation}. We denote $(q'_i, c_i)$ as $\mathbf{t}^q = (t^q_0, \cdots, t^q_{n_q})$ and $(q_i, c'_i)$ as $\mathbf{t}^c = (t^c_0, \cdots, t^c_{n_c})$. Here, $n_q$ and $n_c$ denote the length after backtranslating the question and context, respectively. For $\mathbf{t}^q$ and $\mathbf{t}^c$, we pass them through the base QA model, get $\mathbf{h}^q$ and $\mathbf{h}^c$, and extract the $m$-dimensional feature vector as in Eqn \eqref{eq:feature}, \begin{align} \begin{split} \label{eq:bt} \phi(q'_i,c_i) & = [\frac{1}{n_q}\sum_{i=1}^{n_q} \mathbf{h}^q_{i, 0}, \cdots, \frac{1}{n_q}\sum_{i=1}^{n_q} \mathbf{h}^q_{i, m}], \\ \phi(q_i,c'_i)& = [\frac{1}{n_c}\sum_{i=1}^{n_c} \mathbf{h}^c_{i, 0}, \cdots, \frac{1}{n_c}\sum_{i=1}^{n_c} \mathbf{h}^c_{i, m})]. \end{split} \end{align} We use the concatenation of the original input example embedding and backtranslated one, $[\phi(q_i,c_i);\phi(q'_i,c_i)]$ and $[\phi(q_i,c_i);\phi(q_i,c'_i)]$ as features. Backtranslating both context and question did not bring further gains, thus the results from such a feature set are not presented. {We hypothesize that backtranslating context and question together might introduce too severe noise.} We do not use data augmentation for open retrieval QA experiments. \section*{Acknowledgments} We would like to thank UT Austin NLP group, especially Kaj Bostrom and Greg Durrett for feedback and suggestions. \section{Related Work} \paragraph{Calibration in NLP} Calibration has become an important topic in NLP as well as general machine learning~\cite{Guo2017OnCO, pleiss2017fairness, fan2021contextual} as confidence scores from calibrators can be useful for the error correction process~\cite{feng2004using}. Calibration has been studied in natural language inference, commonsense reasoning~\cite{Desai2020CalibrationOP,Varshney2020ItsBT}, dialogue systems ~\citep{Mielke2020LinguisticCT}, semantic parsing~\cite{Dong2018ConfidenceMF}, coreference resolution~\cite{Nguyen2015PosteriorCA} and sequence labeling~\citep{Jagannatha2020CalibratingSO}. In question answering, ~\citet{kamath2020selective}'s study on selective question answering inspired our work. We measure the calibration performance with calibrator accuracy, AUROC, and coverage at accuracy. Expected Calibration Error (ECE) \cite{guo2017calibration} is another commonly used metric for calibration performance, but we consider calibrator as a binary classifier at here. ~\citet{Jagannatha2020CalibratingSO} also studies calibration in reading comprehension, using language model perplexity and model's confidence as features. Language model perplexity coarsely and indirectly captures information about the question and context. We propose an improved feature space and thoroughly test it in challenging settings, e.g., adversarial RC, unanswerable RC, and open retrieval QA. \paragraph{Calibration During Training} Recent work in QA introduces an answer verification step \citep{tan2018know, hu2019read+, wang2020no} at the end of the pipeline. During the training, this verifier module takes the questions, answers, or MRC model's state as inputs and determines the answers' validity. Then, the validity score is used to update the model parameters during training. Thus, the validator is jointly trained with the MRC model. While this is conceptually similar to our set up, instead of tying the calibrator into the model, we design a universal post-hoc calibrator that can be easily applied to any model architecture. \paragraph{Calibration with Ensembles} Ensemble diversity has been used to improve uncertainty estimation and calibration \citep[e.g.][]{Raftery2005UsingBM, Stickland2020DiverseEI}. While it is effective, calibration with model ensembling is usually expensive and time consuming~\cite{Zhou2002EnsemblingNN,Zhou2018DiverseEE}. Our calibrator is an offline postprocessing step that does not require further training of the original model. \section{Results} \begin{table*}\vspace{-5pt} \footnotesize \centering \begin{tabular}{lccc|ccc} \toprule & \multicolumn{3}{c|}{In Domain} & \multicolumn{3}{c}{Out of Domain}\\ & Calib. Accu & AUROC & Cov@Acc=80\% & Calib. Accu & AUROC & Cov@Acc=80\%\\ \hline & \multicolumn{3}{c|}{SQuAD1.1 Adversarial} &\multicolumn{3}{c}{MRQA / SQuAD1.1 Adversarial} \\ \hline \citet{kamath2020selective}& 52.4$\pm$0.2 & 53.7$\pm$0.4 & 25.4\% & 52.4$\pm$0.2 & 52.2$\pm$0.4 & 24.7\%\\ Ours & 61.1$\pm$0.4 & 63.2$\pm$0.3 & 35.6\% & 53.2$\pm$0.4 & 53.6$\pm$0.3 & 25.3\%\\ + features & 61.4$\pm$0.6 & 63.5$\pm$0.3 & 35.8\% & 53.8$\pm$0.4 & 54.3$\pm$0.4 & 26.8\%\\ + features + $ \phi(q_i,c'_i)$ & \bf{62.8$\pm$0.3} & \bf{65.2$\pm$0.2}& \bf{37.3\%} & \bf{54.9$\pm$0.5} & \bf{55.1$\pm$0.3}& \bf{27.5\%}\\ + features + $ \phi(q'_i,c_i)$ & 61.6$\pm$0.3 & 63.7$\pm$0.4 & 35.5\% & 53.6$\pm$0.5 & 53.9$\pm$0.5 & 26.6\% \\ \midrule & \multicolumn{3}{c|}{SQuAD2.0 } & \multicolumn{3}{c}{MRQA / SQuAD2.0 }\\ \hline \citet{kamath2020selective} & 57.6$\pm$0.3 & 59.2$\pm$0.4 & 31.7\% & 54.8$\pm$0.4 & 56.5$\pm$0.5 & 29.6\%\\ Ours & 58.9$\pm$0.2 & 61.1$\pm$0.2 & 33.8\% & 55.7$\pm$0.3 & 57.4$\pm$0.4 & 30.7\% \\ + features & 60.1$\pm$0.2 & 61.9$\pm$0.3 & 34.2\% & 56.6$\pm$0.4 & 58.3$\pm$0.5 & 31.6\%\\ + features + $ \phi(q_i,c'_i)$ & 60.2$\pm$0.3 & 61.8$\pm$0.3 & 34.1\% & 56.4$\pm$0.5 & 57.9$\pm$0.4 & 31.2\%\\ + features + $ \phi(q'_i,c_i)$ & \bf{62.6$\pm$0.4} & \bf{64.3$\pm$0.3} & \bf{35.9\%} & \bf{58.1$\pm$0.4} & \bf{60.4$\pm$0.4} & \bf{32.9\%} \\ \bottomrule \end{tabular} \caption{Calibration results on adversarial and unanswerable SQuAD datasets. In the out of domain setting, we first list the training dataset of calibrator, then the test dataset. } \label{tab:harder_mc} \end{table*} \begin{table*}[h] \footnotesize \centering \begin{tabular}{lclccc} \toprule Model & Answer Acc &Calibrator & Calib. Accu & Calib. AUROC & Cov@Acc=80\%\\ \midrule Extractive (DPR) & 41.0 & Unnormalized scores & 65.9$\pm$0.2 & 65.2$\pm$0.2 & 10.4\%\\%10.3$\pm$0.2 & 23.1$\pm$0.3 \\ \tiny{\citep{karpukhin2020dense}}& & Normalized scores & 72.2$\pm$0.4 & 74.5$\pm$0.3 & 28.9\%\\%41.2$\pm$0.1 & 58.6$\pm$0.1\\ & & Ours (+ Normalized Scores)& \bf{77.3$\pm$0.3} & \bf{78.7$\pm$0.2} & \bf{30.5\%} \\\midrule Generation (T5)& 25.5 &Likelihood & 89.3$\pm$0.1 & 86.6$\pm$0.1 & 10.4\%\\ \tiny{\citep{Raffel2020ExploringTL}}& & Ours (+ Likelihood) & \bf{91.6$\pm$0.3} & \bf{92.9$\pm$0.1}& \bf{ 11.3\%}\\ \bottomrule \end{tabular} \caption{Calibration results on NQ open retrieval test set for different base QA models and calibration features.} \label{tab:opendomain_qa} \end{table*} \paragraph{Calibration} Table~\ref{tab:out_of_domain} reports calibration results on standard reading comprehension datasets. The top block displays the performance of calibrators trained on the SQuAD and HotpotQA datasets, and the bottom block shows the results of calibrators trained on the SQuAD and NQ datasets. In both settings, the our input example embedding works better than the manual feature set. However, two approaches are complementary in all settings. Interestingly, paraphrasing questions shows gains in Natural Questions but not in other datasets. We hypothesize that organically collected search queries contain more ambiguous and ill-defined queries than crowdsourced questions where questions were based directly on the context. Adding paraphrased context embeddings, on the other hand, shows a modest gain across all settings. Unlike QA models have access to millions of parameters, calibrators, even with our feature set, are provided with very limited information. We hypothesize that augmenting the feature set with paraphrased context enabled the calibrator to gain more information about the example, facilitating higher performance. Table~\ref{tab:harder_mc} shows the results in more challenging settings: one with adversarial attacks and another containing unanswerable questions. In both settings, we observe sizable gains (5-10\% increase in calibration accuracy) for the in domain setting, but the gains are smaller in out of domain settings. Similar to the Natural Questions dataset, in SQuAD 2.0, which includes adversarially designed questions without an answer, paraphrasing the question is more helpful than paraphrasing the context. On the other hand, in the adversarial setting where contexts are manipulated, paraphrasing contexts is more effective. Overall, our new feature vector shows consistent gain across all datasets and settings. We present the calibration in open retrieval QA in Table~\ref{tab:opendomain_qa}. Overall, calibrator accuracy is higher compared to RC, partially because the answer accuracy is substantially lower. For example, with generation based model (T5)'s answer accuracy of 25.5, simply predicting incorrectly for every example will give 74.5 calibration accuracy. In both models, internal confidence scores (Likelihood and Normalized scores) provide reasonable calibrator performance, yet adding our feature set improves the performance. In particular, our calibrator shows a larger gain in the DPR setting. Encouraged by this result, we test our calibrator as an answer candidate reranker for top answer candidates from DPR. Despite high calibration accuracy of generation based approach, selective QA performance (Cov@Acc=80\%) is higher with the extractive approach, suggesting comparing calibration performance across models of different accuracy is challenging. \paragraph{Answer Reranking} Table~\ref{tab:reranker} shows the results of our calibrator as an answer candidate reranker. The calibrator considers the top 1,000 answer candidates (100 retrieved passages, each with top 10 answer spans) and outputs top candidates based on the calibrator score instead of the model score. We show negligible gains in top 1 accuracy but bigger gains in top 5 accuracy. These small but noticeable gains show potential for using calibrators to improve open retrieval QA performances, where multiple answer candidates are considered. \begin{table} \centering \resizebox{0.95\columnwidth}{!}{ \begin{tabular}{lcc} \toprule & Top 1 EM & Top 5 EM \\ \hline DPR & 41.0 &57.8 \\ Unnormalized scores & 10.3$\pm$0.2 & 23.1$\pm$0.3 \\ Normalized scores & 41.2$\pm$0.1 & 58.6$\pm$0.1\\ Ours (+ Normalized scores) & \bf{41.4$\pm$0.1} & \bf{59.0$\pm$0.1} \\ \bottomrule \end{tabular}} \caption{Results on open domain question answering in NQ. The calibrator is used as a reranker for selecting the top answer span out of 1,000 answer spans (10 answer spans per each of 100 retrieved passages). } \label{tab:reranker} \end{table} \section{Problem Definition}\label{sec:task} We estimate how the models' prediction confidence aligns with the empirical likelihood of correctness~\cite{Brier1950VERIFICATIONOF}. Formally, a calibrator $f$ takes the input example $x_i$ and the trained model $M_\theta$ and identifies whether the model's prediction is correct or not. We treat the correctness as binary (i.e., answer string exact match) for simplicity, instead of partial credit (e.g., token level F1 score). We study two settings: reading comprehension (RC) and open retrieval QA. In RC, an input example $x_i$ will be a context $c_i$ and the question $q_i$, and in open domain QA, an input example will be a corpus $C$ and the question $q_i$. We use the same metrics to evaluate the performance of the calibrator $f$ in the two settings. \subsection{Metric: Calibrator performance} \paragraph{Accuracy:} Given evaluation data $D_{\text{eval}}=\{(x_1,y_1),(x_2,y_2)\ldots(x_N,y_N)\}$ and a learned model $M_{\theta}$, we define the accuracy of the calibrator $f$ as: $$ \text{acc}(f)=\sum_{i=1}^{N}\mathbbm{I}\bigg\{f(x_i, M_\theta)=\mathbbm{I} [M_\theta(x_i)=y_i]\bigg\}. $$ \paragraph{AUROC: } Based on the above definition of the accuracy of the calibrator $f$, we computes the coverage -- fraction of evaluation data $D_{eval}$ that model makes prediction on -- and risk, the error at that coverage. We plot risk versus coverage graph, and measure the area under the curve, i.e., AUROC (Area Under the Receiver Operating Characteristic Curve)~\cite{hanley1982auroc}. \subsection{Metric: End task performance} We measure how the calibrator performance impacts QA performances. First, we study selective QA setting -- where we use calibrator score to decide which examples from $D_{eval}$ to make predictions. For the extractive model for open retrieval QA~\cite{karpukhin2020dense}, where multiple answer candidates are given, we further evaluate the performance of calibrator as a reranker and measure the answer span exact match (EM) score. \paragraph{Selective QA (coverage at fixed accuracy): } We use the calibrator score to rank the \textit{examples} in the evaluation data. Specifically, we use the calibrator's confidence for the top answer candidate instead of model score to decide which examples in $D_{eval}$ the model answers most confidently. Then, we report the percentage of evaluation data that can be predicted while maintaining threshold accuracy (80\%), following prior work~\cite{kamath2020selective}. \paragraph{Open Retrieval QA (top-N accuracy):} We use the calibrator score to rank the \textit{answer candidates} for each evaluation example, similar to how candidate translations are reranked in machine translation~\cite{Shen2004DiscriminativeRF}. We first retrieve answer candidates from multiple paragraphs and utilize the calibrator to override the model's prediction. The calibrator scores the top N answer candidates and outputs the answer with the highest confidence score instead of the answer with the highest model score. Our calibrator can be added as last step for any open retrieval QA systems which generates multiple answer candidates without retraining the model. We evaluate the top 1 exact match accuracy and the top 5 exact match accuracy after re ranking with our calibrator score.
{'timestamp': '2021-06-04T02:06:15', 'yymm': '2106', 'arxiv_id': '2106.01494', 'language': 'en', 'url': 'https://arxiv.org/abs/2106.01494'}
arxiv
\section{Introduction} \label{sec1} Document-level relation extraction (DocRE) aims to extract relations among entities within a document which requires multiple reasoning skills (i.e., pattern recognition, logical reasoning, coreference reasoning, and common-sense reasoning)~\cite{yao-etal-2019-docred}. Generally, the input document is constructed as a structural graph-based on syntactic trees, coreference or heuristics to represent relation information between all entity pairs~\cite{Nan2020ReasoningWL,zeng-etal-2020-double,docred-rec}. Thus, graph neural networks are applied to the constructed structural graph to model these reasoning skills. After performing multi-hop graph convolution, the feature representations of two entities are concatenated to recognize their relation by the classifier, achieving state-of-the-art performance in the DocRE task~\cite{zeng-etal-2020-double,docred-rec}. \begin{figure}[t] \centering \includegraphics[scale=0.98]{example.pdf} \caption{An example of different reasoning types. Different reasoning types have different reasoning processing.} \label{fig1:example} \end{figure} However, it is yet to be seen whether modeling these reasoning skills implicitly is competitive with the intuitive reasoning skills between one entity pair in this document. Figure~\ref{fig1:example} shows four kinds of reasoning skills for entity pairs in the DocRE dataset \cite{yao-etal-2019-docred}. First, take two entity pairs \{``\textit{Me Musical Nephews}", ``\textit{1942}"\} and \{``\textit{William}", ``\textit{Adelaide}"\} as examples, the intra-sentence reasoning concerns about the mentions inside the sentence, for example, ``\textit{Me Musical Nephews}" and ``\textit{1942}" for pattern recognition, and ``\textit{William}" and ``\textit{Adelaide}" for the common-sense reasoning. Also, the logical reasoning for entity pair \{``\textit{U.S.}", ``\textit{Baltimore}"\} requires the reason path from ``\textit{U.S.}"$\to$``Maryland" (bridge entity)$\to$``\textit{Baltimore}" while the coreference reasoning for entity pair \{``\textit{Dwight Tillery}", ``\textit{University of Michigan Law School}"\} pays attention to the reason path from ``\textit{Dwight Tillery}"$\to$``\textit{He}" (reference word)$\to$``\textit{University of Michigan Law School}". However, the advanced DocRE models generally use the universal multi-hop convolution networks to model these reasoning skills implicitly and do not consider the above intuitive reasoning skills explicitly, which may hinder the further improvement of DocRE. To this end, we propose a novel discriminative reasoning framework to explicitly model the reasoning processing of these reasoning skills, such as intra-sentence reasoning (including pattern recognition and common-sense reasoning), logical reasoning, and coreference reasoning. Specifically, inspired by \citeauthor{docred-rec}'s meta-path strategy, we extract the reasoning paths of the three reasoning skills discriminatively from the input document. Thus, a discriminative reasoning network is designed to estimate the relation probability distribution of different reasoning paths based on the constructed graph and vectorized document contexts for each entity pair, thereby recognizing their relation. In particular, there are the probabilities of multiple reasoning skills for each candidate relation between one entity pair, to ensure that all potential reasoning skills can be considered in the inference. In summary, our main contributions are as follows: \begin{enumerate} \item[$\bullet$] We propose a discriminative reasoning framework to model the reasoning skills between two entities in a document. To the best of our knowledge, this is the first work to model different reasoning skills explicitly for enhancing the DocRE. \item[$\bullet$] Also, we introduce a discriminative reasoning network to encode the reasoning paths based on the constructed heterogeneous graph and the vectorized original document, thereby recognizing the relation between two entities by the classifier. \item[$\bullet$] Experimental results on the large-scale DocRE dataset show the effectiveness of the proposed method, especially outperform the recent state-of-the-art DocRE model. \end{enumerate} \section{Discriminative Reasoning Framework} \label{sec2} In this section, we propose a novel discriminative reasoning framework to model different reasoning skills explicitly to recognize the relation between each entity pair in the input document. The discriminative reasoning framework contains three parts: definition of reasoning paths, modeling reasoning discriminatively, and multi-reasoning based relation classification. \subsection{Definition of Reasoning Path} \label{sec2-1} Formally, given one unstructured document comprised of $N$ sentences $D$=$\{s_1, s_2, \cdots, s_N\}$, each sentence is a sequence of words $s_n = \{s_{n}^{1}, s_{n}^{2}, \cdots, s_{n}^{J}\}$ with the length $J_n$=$|s_n|$. The annotations include concept-level entities~$\varepsilon=\{e_i\}_{i=1}^P$ as well as multiple occurrences of each entity under the same phrase of alias $e_i=\{m_i^{s_k}\}_{k=1}^Q$ ($m_i^{s_k}$ denotes the mention of $e_i$ which occur in the sentence $s_k$) and their entity type~(i.e. locations, organizations, and persons). The DocRE aims to extract the relation between two entities in $\varepsilon$, namely $P(r|e_i,e_j,D)$. For the simplification of reason skills, we first combine both pattern recognition and commonsense reasoning as the intra-sentence reasoning because they generally perform reasoning inside the sentence. Consequently, the original four kinds of the reasoning skills~\cite{yao-etal-2019-docred} are further refined as three reasoning skills: intra-sentence reasoning, logical reasoning, and coreference reasoning. Inspired by \citeauthor{docred-rec}'s work, we also use the meta-path strategy to extract reasoning path for each reason skill, thereby representing the above three reasoning skills explicitly. Specifically, meta-paths for different reasoning skills are defined as follows: \begin{enumerate} \item[1)] \textbf{Intra-sentence reasoning path}: It is formally denoted as $PI_{ij}$=$m_i^{s_1} \circ s_1 \circ m_j^{s_1}$ for one entity pair \{$e_i$, $e_{j}$\} inside the same sentence $s_1$ in the input document $D$. $m_i^{s_1}$ and $m_j^{s_1}$ are mentions related to two entities, respectively. ``$\circ$" denotes one reasoning step on the reasoning path from $e_i$ to $e_{j}$. \item[2)] \textbf{Logical reasoning path}: The relation between one entity pair \{$e_i$, $e_{j}$\} from sentences ${s_1}$ and ${s_2}$ is indirectly established by the occurrence bridge entity $e_l$ for the logical reasoning. The reasoning path can be formally as $PL_{ij}$= $m_i^{s_1} \circ s_1 \circ m_l^{s_1} \circ m_l^{s_2} \circ s_2 \circ m_j^{s_2}$. \item[3)] \textbf{Coreference reasoning path}: A reference word refers to one of two entities $e_i$ and $e_{j}$, which occur in the same sentence as the other entity. We simplify the condition and assume that there is a coreference reasoning path when the entities occur in different sentences. The reasoning path can be formally as $PC$=$m_i^{s_1} \circ s_1 \circ s_2 \circ m_j^{s_2}$. \end{enumerate} Note that there are no entities in the defined reasoning path compare to the meta-path defined in \citeauthor{docred-rec}'s work. This difference is mainly due to the following considerations: i) the reason path pays more attention to the mentions and referred sentences; ii) entities generally are contained by mentions; iii) it makes modeling of path reasoning more simple. \subsection{Modeling Reasoning Discriminatively} \label{sec2-2} Based on the defined reasoning paths, we decompose the DocRE problem into three reasoning sub-tasks: intra-sentence reasoning~(IR), logical reasoning~(LR), and coreference reasoning~(CR). Next, we introduce modeling of three sub-tasks in detail: \noindent\textbf{Modeling Intra-Sentence Reasoning.} Given one entity pair \{$e_i$, $e_j$\} and its reasoning path $PI_{ij}$ in the sentence $s_1$, the intra-sentence reasoning is modeled to recognize the relation between this entity pair based as follows: \begin{equation} \begin{aligned} \textup{R}_{PI}(r)=P(r|e_i, e_j, PI_{ij}, D). \label{eq:reasontask1} \end{aligned} \end{equation} \noindent\textbf{Modeling Logical Reasoning.} Given one entity pair \{$e_i$, $e_j$\} and its reasoning path $PL_{ij}$, the logical reasoning is modeled to recognize the relation between this entity pair based as follows: \begin{equation} \begin{aligned} \textup{R}_{PL}(r)=P(r|e_i, e_j, PL_{ij}, D). \label{eq:reasontask2} \end{aligned} \end{equation} Since the $e_l$ co-occur with the entity pair $e_i$ and $e_j$ respectively, the logical reasoning is further formally as follows: \begin{equation} \textup{R}_{PL}(r)=P(r|e_i, e_j, e_l, PI_{il}\circ PI_{lj}, D). \label{eq:reasontask2decompose} \end{equation} where $\circ$ denotes the connection of the paths. \noindent\textbf{Modeling Coreference Reasoning.} Similarity, given one entity pair \{$e_i$, $e_j$\} and its reasoning path $PC_{ij}$, the coreference reasoning is modeled to recognize the relation between this entity pair based as follows: \begin{equation} \begin{aligned} \textup{R}_{PC}(r)=P(r|e_i, e_j, PC_{ij}, D). \label{eq:reasontask3} \end{aligned} \end{equation} \subsection{Multi-reasoning Based Relation Classification} \label{sec2-3} In the DocRE task, one entity usually involves multiple relationships which rely on different reasoning types. Thus, the relation between one entity pair may be reasoned by multiple types of reasoning rather than one single reasoning type. Based on the proposed three reasoning sub-tasks, the relation reasoning between one entity pair is regarded as a multi-reasoning classification problem. Formally, we select the reasoning type with max probability to recognize the relation between each entity pair as follows: \begin{equation} \begin{aligned} P(r|e_i,e_j,D)=\max[\textup{R}_{PI}(r), \textup{R}_{PL}(r), \textup{R}_{PC}(r)]. \label{eq:fullprobability} \end{aligned} \end{equation} In addition, there are often multiple reason paths between two entities for one reasoning type. Thus, the classification probability in Eq.\eqref{eq:fullprobability} can be rewritten as follows: \begin{equation} \begin{aligned} P(r|e_i,e_j,D)&=\max[\\ &\{\textup{R}_{PI_1}(r),\cdots,\textup{R}_{PI_K}(r)\}, \\ &\{\textup{R}_{PL_1}(r),\cdots,\textup{R}_{PL_K}(r)\}, \\ &\{\textup{R}_{PC_1}(r),\cdots,\textup{R}_{PC_K}(r)\}], \label{eq:multifullprobability} \end{aligned} \end{equation} where $K$ is the number of reasoning paths for one reasoning skill, which is the same to each reasoning skill for simplicity. Note that all the entity pairs have at least one reasoning path from one of three defined reasoning sub-tasks. When the number of reasoning paths is greater than $K$ for one reasoning sub-task, we choose the $K$ first reasoning paths, otherwise we use the actual reasoning paths. \section{Discriminative Reasoning Network} \label{sec3} In this section, we design a discriminative reasoning network (\textbf{DRN}) to model three defined reasoning sub-tasks for recognizing the relation between two entities in a document. Follow \citeauthor{zeng-etal-2020-double} and \citeauthor{zhou2021atlop}'s work, we use two kinds of context representations (heterogeneous graph context representation and document-level context representation) to model different reasoning paths discriminatively in Eq.\eqref{eq:reasontask1}-\eqref{eq:reasontask3} \begin{figure*}[t] \centering \includegraphics[scale=1]{model.pdf} \caption{The overall architecture of DRN. First, A context encoder consumes the input document to get a contextualized representation of each word. Then the heterogeneous graph context representation and the document-level context representation are prepared as the input of the discriminative reasoning framework. Intra-sentence reasoning (IR) task, logical reasoning (LR) task and co-reference reasoning (CR) task are modeled explicitly and calculate the classification score respectively. Finally, the maximal score is selected as the output.} \label{fig:model} \end{figure*} \subsection{Heterogeneous Graph Context Representation} \label{sec3-1} Formally, the embedding of each word $\textbf{w}_e$ is concatenated with the embedding of its entity type $\textbf{w}_t$ and the embedding of its coreference $\textbf{w}_c$ as the representation of word $\textbf{b}$=[$\textbf{w}_e$:$\textbf{w}_t$:$\textbf{w}_c$]. These sequences of word representations are in turn fed into a bidirectional long short-term memory (BiLSTM) to vectorize the input document $\textup{D}$=\{$\textbf{H}^{1}$, $\textbf{H}^{2}$, $\cdots$, $\textbf{H}^{N}$\}, where $\textbf{H}^{n}$ = $(\textbf{h}^{n}_1, \textbf{h}^{n}_2, \dots, \textbf{h}^{n}_{J_n})$ and $\textbf{h}^{j}_i$ denotes the hidden representation of the $i-th$ words of the $j-th$ sentence in the document. Similar to \citeauthor{zeng-etal-2020-double}'s work, we construct a heterogeneous graph which contains sentence node and mention node. There are four kinds of edges in the heterogeneous graph: sentence-sentence edge (all the sentence nodes are connected), sentence-mention edge (the sentence node and the mention node which resides in the sentence ), mention-mention edge (all the mention nodes which are in the same sentence) and co-reference edge (all the mention nodes which refer to the same entity). Then we apply the graph-based DocRE method \cite{zeng-etal-2020-double} to encode the heterogeneous graph, based on which the heterogeneous graph context representation (\textbf{HGCRep}) are learned. The \textbf{HGCRep} of each mention node and sentence node $\textbf{g}_n$ is formally denoted as: \begin{equation} \begin{aligned} \textbf{g}_n =[\textbf{v}_n:\textbf{p}^{1}_{n}:\textbf{p}^{2}_{n}:\cdots:\textbf{p}^{l-1}_{n}], \label{eq:InputOfCNN} \end{aligned} \end{equation} where $\textbf{g}_n\in \mathbb{R}^{d_1}$ and ``:" is the concatenation of vectors and each of \{$\textbf{p}^{1}_{n}, \textbf{p}^{2}_{n}, \cdots, \textbf{p}^{l-1}_{n}$\} is learned by the multi-hop graph convolutional network~\cite{zeng-etal-2020-double} and $\textbf{v}_n$ is the initial representation of the $n$-th node extracted from $\textbf{D}$. Finally, there is a heterogeneous graph representation $\textbf{G}$=$\{\textbf{g}_{1}, \textbf{g}_{2}, \cdots, \textbf{g}_{N}\}$ including each mention nodes and sentence nodes. \subsection{Document-level Context Representation} \label{sec3-2} In the DocRE task, these reasoning skills heavily rely on the original document context information rather than the heterogeneous graph context information. Thus, the existing advanced DocRE models use syntactic trees or heuristics rules to extract the context information (i.e., entities, mentions, and sentences) that is directly related to the relation between entity pairs. However, this approach destroys the original document structure, which is weak in modeling the reasoning between two entities for the DocRE task. Therefore, we use the self-attention mechanism~\cite{NIPS2017_7181} to learn a document-level context representation (\textbf{DLCRep}) $\textbf{c}_n$ for one mention based on the vectorized input document $\textbf{D}$: \begin{equation} \textbf{c}_n=\textup{softmax}(\frac{\textbf{h}^{n}_j\textbf{K}^{\top}}{\sqrt{d_{model}}})\textbf{V}, \label{eq:Self-Attetion} \end{equation} where $\textbf{c}_n\in \mathbb{R}^{d_2}$ and $\{\textbf{K}, \textbf{V}\}$ are key and value matrices that are transformed from the vectorized input document $\textbf{D}$ using a linear layer. Here, inspired by relation learning~\cite{match_blank}, we use the hidden state of the head word in one mention or one sentence to denote them for simplicity. \subsection{Modeling of Reasoning Paths} \label{sec3-3} In this section, we use the concatenation operation to model the reasoning step on the reasoning path, thereby modeling the defined reasoning paths in Section~\ref{sec2-1} as the corresponding reasoning representations as follows: \begin{enumerate} \item[1)] For the intra-sentence reasoning path, both HGCReps and DLCReps of two mentions are concatenated in turn as a reasoning representation: \begin{equation} \begin{aligned} \alpha_{ij}=[\textbf{g}_{m_i^{s_1}}:\textbf{g}_{m_j^{s_1}}:\textbf{c}_{m_i^{s_1}}:\textbf{c}_{m_j^{s_1}}], \label{eq:intrasetnecefeature} \end{aligned} \end{equation} where $\alpha_{ij}\in \mathbb{R}^{2 d_1+2 d_2}$ and ``:" is the concatenation of vectors. \item[2)] For the logical reasoning path, both HGCReps of mention $m_i^{s_1}$ and $m_j^{s_2}$ and DLCReps of two mention pair $(m_i^{s_1},m_l^{s_1})$ and $(m_j^{s_2},m_l^{s_2})$ are concatenated as their reasoning representation: \begin{equation} \begin{aligned} \beta_{ij}&=[\textbf{g}_{m_i^{s_1}}:\textbf{g}_{m_j^{s_1}}:\\ &\textbf{c}_{m_i^{s_1}}+\textbf{c}_{m_l^{s_1}}:\textbf{c}_{m_j^{s_2}}+\textbf{c}_{m_l^{s_2}}], \end{aligned} \label{eq:logicalfeature} \end{equation} where $\beta_{ij}\in \mathbb{R}^{2 d_1+2 d_2}$. \item[3)] For the coreference reasoning path, we connect both HGCReps of two mentions and DLCReps of two sentences are are concatenated in turn as their reasoning representation: \begin{equation} \gamma_{ij}=[\textbf{g}_{m_i^{s_1}}:\textbf{g}_{m_j^{s_2}}:\textbf{c}_{s_1}:\textbf{c}_{s_2}] \label{eq:coreferencefeature} \end{equation} where $\gamma_{ij}\in \mathbb{R}^{2 d_1+2 d_2}$ and both $\textbf{c}_{s_2}$ and $\textbf{c}_{s_2}$ denote DLCReps for two sentences ${s_1}$ and ${s_2}$. \end{enumerate} The learned reasoning representations $\alpha_{ij}$, $\beta_{ij}$, and $\gamma_{ij}$ is as the input to classifier to compute the probabilities of relation between $e_i$ and $e_j$ entities by a multilayer perceptron~(MLP) respectively: \begin{equation} \begin{aligned} P(r|e_i,e_j,D)=\max[\\ \textup{sigmoid}(\textup{MLP}_r(\alpha_{ij}), \\ \textup{sigmoid}(\textup{MLP}_r(\beta_{ij}), \\ \textup{sigmoid}(\textup{MLP}_r(\gamma_{ij})]. \label{eq:modelprobabilitymax} \end{aligned} \end{equation} Similarly, when there are multiple reasoning paths between two entities for one reasoning type in Eq.\ref{eq:multifullprobability}, Eq.\ref{eq:modelprobabilitymax} is rewritten as follows: \begin{equation} \begin{aligned} P(r|e_i,e_j,D)=\max[\\ \textup{MLP}_r(\alpha^{1}_{ij}),\cdots,\textup{MLP}_r(\alpha^{K}_{ij}),\\ \textup{MLP}_r(\beta^{1}_{ij}),\cdots,\textup{MLP}_r(\beta^{K}_{ij}),\\ \textup{MLP}_r(\gamma^{1}_{ij}),\cdots,\textup{MLP}_r(\gamma^{K}_{ij})]. \label{eq:fullmodelprobability} \end{aligned} \end{equation} Also, the binary cross-entropy is used as training objection, which is the same as the advanced DocRE model~\cite{yao-etal-2019-docred}. \section{Experiments} \label{sec4} \subsection{Data set and Setup} \label{sec4-1} \begin{table}[ht!] \centering \begin{tabular}{lr} \hline Hyperparameter & Value \\ \hline Batch Size & 12 \\ Optimizer & AdamW \\ Learning Rate & 1e-3 \\ Activation Function & ReLU \\ Word Embedding Size & 100 \\ Entity Type Embedding Size & 20 \\ Coreference Embedding Size & 20 \\ Encoder Hidden Size & 128 \\ Dropout & 0.5 \\ Layers of GCN & 2 \\ Weight Decay & 0.0001 \\ Device & GTX 1080Ti \\ \hline \end{tabular} \caption{Settings for DRN.} \label{table:glove_hyperparameters} \end{table} The proposed methods were evaluated on a large-scale human-annotated dataset for document-level relation extraction~\cite{yao-etal-2019-docred}. DocRED contains 3,053 documents for the training set, 1,000 documents for the development set, and 1,000 documents for the test set, totally with 132,375 entities, 56,354 relational facts, and 96 relation types. More than 40\% of the relational facts require reading and reasoning over multiple sentences. For more detailed statistics about DocRED, we recommend readers to refer to the original paper~\cite{yao-etal-2019-docred}. Following settings of~\citeauthor{yao-etal-2019-docred}'s work, we used the GloVe embedding (100d) and BiLSTM (128d) as word embedding and encoder. The number of the reasoning path for each task is set to 3. The learning rate was set to 1e-3 and we trained the model using AdamW~\cite{adamw2019} as the optimizer with weight decay 0.0001 under Pytorch~\cite{paszke2017pytorch}. For the BERT representations, we used uncased BERT-Based model (768d) as the encoder and the learning rate was set to $1e^{-5}$. For evaluation, we used F1 and Ign F1 as the evaluation metrics. Ign F1 denotes F1 score excluding relational facts shared by the training and development/test sets. In particular, the predicted results were ranked by their confidence and traverse this list from top to bottom by $F1$ score on development set, and the score value corresponding to the maximum $F1$ is picked as threshold $\theta$. The hyper-parameter for the number of reasoning paths was tuned based on the development set. In addition, the results on the test set were evaluated through CodaLab\footnote{\url{https://competitions.codalab.org/competitions/20717}}. Once a model is trained, we get the confidence scores for every triple example (subject,object,relation) as Eq.(\ref{eq:modelprobabilitymax}). We rank the predicted results by their confidence and traverse this list from top to bottom by F1 score on development set, the score value corresponding to the maximum F1 is picked as threshold $\theta$. This threshold is used to control the number of extracted relational facts on the test set. \subsection{Baseline Systems} \label{sec4-2} We reported the results of the recent graph-based DocRE methods as the comparison systems: GAT~\cite{Velickovic2018GraphAN}, GCNN~\cite{sahu-etal-2019-inter}, EoG ~\cite{Christopoulou2019ConnectingTD}, AGGCN~\cite{guo-etal-2019-attention}, \textbf{LSR}~\cite{Nan2020ReasoningWL}, \textbf{GAIN}~\cite{zeng-etal-2020-double}, and \textbf{HeterGASN-Rec}\cite{docred-rec}. Moreover, pre-trained models like \textbf{BERT}~\cite{devlin-etal-2019-bert} has been shown impressive result on the DocRE task. Therefore, we also reported state-of-the-art graph-based DocRE models with pre-trained BERT$_{base}$ model, including \textbf{Two-Phase+BERT$_{base}$}~\cite{Wang2019FinetuneBF}, \textbf{LSR+BERT$_{base}$}~\cite{Nan2020ReasoningWL}, \textbf{GAIN+BERT$_{base}$}~\cite{zeng-etal-2020-double}, \textbf{HeterGASN-Rec+BERT$_{base}$}~\cite{docred-rec}, and \textbf{ATLOP-BERT$_{base}$}~\cite{zhou2021atlop}. \subsection{Main Results} \label{sec4-3} Table \ref{tab:mianresult} presents the detailed results on the development set and the test set for the DocRE dataset. First, the proposed DRN model significantly outperformed the existing graph-based DocRE systems. Second, the proposed DRN model was superior to all the existing graph-based DocRE systems on the test set, validating that modeling reasoning discriminatively is more beneficial to DocRE than the original universal neural network way. Meanwhile, it also outperformed the best HeterGSAN-Rec model by 1.10 points in terms of F1, validating the effectiveness of our discriminative reasoning method. Third, for the comparisons with a pre-trained language model (BERT$_{base}$), F1 scores of the proposed DRN+BERT$_{base}$ model was higher than that of the existing graph-based DocRE ATLOP+BERT model systems with BERT$_{base}$ on the test set. In particular, our method (F1 61.37) was superior to the existing best ATLOP+BERT model (F1 61.30) in terms of F1, which is a new state-of-the-art result on the DocRE dataset. \begin{table}[h] \begin{center} \scalebox{.74}{ \begin{tabular}{l|l|l|l|l} \hline \multicolumn{1}{c|}{\multirow{2}{*}{Methods}} & \multicolumn{2}{c|}{Dev} & \multicolumn{2}{c}{Test} \\ \cline{2-5} \multicolumn{1}{c|}{} & Ign F1 & F1 & Ign F1 & F1 \\ \hline \multicolumn{5}{c}{\textit{Existing DocRE Systems}} \\ \hline GCNN$^\dag$ & 46.22 & 51.52 & 49.59 & 51.62 \\ EoG$^\dag$ & 45.94 & 52.15 & 49.48 & 51.82 \\ GAT$^\dag$ & 45.17 & 51.44 & 47.36 & 49.51 \\ AGGCN$^\dag$ & 46.29 & 52.47 & 48.89 & 51.45 \\ LSR$^*$ & 48.82 & 55.17 & 52.15 & 54.18 \\ GAIN$^*$ & 53.05 & 55.29 & 52.66 & 55.08 \\ HeterGSAN-Rec$^*$ & 54.27 & 56.22 & 53.27 & 55.23 \\ \cdashline{1-5} BERT$_{base}^*$ & - & 54.16 & - & 53.20 \\ Two-Phase BERT$_{base}^*$ & - & 54.42 & - & 53.92 \\ LSR+BERT$_{base}^*$ & 52.43 & 59.00 & 56.97 & 59.05 \\ GAIN+BERT$_{base}^*$ & 59.14 & 61.22 & 59.00 & 61.24 \\ HeterGSAN-Rec+BERT$_{base}^*$ & 58.13 & 60.18 & 57.12 & 59.45 \\ ATLOP-BERT$_{base}^*$ & 59.22 & 61.09 & 59.31 & 61.30 \\\hline \multicolumn{5}{c}{\textit{Our DocRE Systems}} \\ \cline{1-5} \textbf{DRN} & 54.61 & 56.49 & 54.35 & 56.33 \\ \cdashline{1-5} \textbf{DRN}+BERT$_{base}$ & 59.33 & 61.39 & 59.15 & 61.37 \\ \hline \end{tabular}} \end{center} \caption{Results on the development set and the test set. Results with $*$ are reported in their original papers. Results with $\dag$ are reported in \cite{Nan2020ReasoningWL}. Bold results indicate the best performance of the current method.} \label{tab:mianresult} \end{table} \subsection{Evaluating Hyper-parameter $K$ for The Number of Reasoning Paths} \begin{figure*}[ht!] \subfigure{ \begin{minipage}[t]{0.48\textwidth} \centering \pgfplotsset{height=5.2cm,width=7.5cm,compat=1.14,every axis/.append style={thick}} \begin{tikzpicture} \begin{axis}[ ybar=5pt tick align=inside, bar width=9pt, enlargelimits=0.15, legend style={at={(0.51,0.95)}, anchor=north,legend columns=1}, ylabel={Percentage}, nodes near coords, symbolic x coords={IR,LR,CR}, xtick=data, tick align=inside, ] \addplot[white!30!brown,fill=white!30!brown] coordinates {(IR,19.12)(LR,19.17)(CR,61.71)}; \addplot[white!40!purple,fill=white!40!purple] coordinates {(IR,47.58)(LR,13.91)(CR,38.51)}; \legend{\small{All entity pairs}, \small{Ones with relation}} \end{axis} \end{tikzpicture} \centerline{(a)} \end{minipage}} \subfigure{ \begin{minipage}[t]{0.48\textwidth} \centering \setlength{\abovecaptionskip}{0pt} \pgfplotsset{height=5.2cm,width=7.5cm,compat=1.14,every axis/.append style={thick}} \begin{tikzpicture} \begin{axis}[ x tick label style={ /pgf/number format/1000 sep=}, ylabel=F1 Score, enlargelimits=0.15, legend style={at={(0.66,0.95)}, anchor=north,legend columns=3}, ybar, tick align=inside, bar width=8pt, symbolic x coords={IR,LR,CR}, xtick=data, ] \addplot[white!60!orange,fill=white!60!orange] coordinates {(IR,63.91) (LR,38.72) (CR,47.85)}; \addplot[white!60!blue,fill=white!60!blue] coordinates {(IR,64.25) (LR,41.80) (CR,49.30)}; \addplot[white!60!red,fill=white!60!red] coordinates {(IR,64.63) (LR,42.27) (CR,49.56)}; \legend{\small{GAIN},\small{Rec},\small{DRN}} \end{axis} \end{tikzpicture} \centerline{(b)} \end{minipage}} \caption{(a) The statistical result of different reasoning task. (b) The performance of different reasoning task.} \label{fig:taskperformance} \end{figure*} \label{sec4-4} \begin{table}[h] \centering \scalebox{.9}{ \begin{tabular}{c|cccc|c} \hline \multirow{2}{*}{K} & \multicolumn{2}{c}{Dev Set} & \multicolumn{2}{c|}{Test Set} & \multirow{2}{*}{\begin{tabular}[c]{@{}c@{}}Cover \\ (\%)\end{tabular}} \\ \cline{2-5} & Ign F1 & F1 & Ign F1 & F1 & \\ \hline 1 & 54.04 & 55.94 & 53.83 & 55.81 & 63.05 \\ 2 & 54.63 & 56.47 & 54.12 & 56.07 & 82.17 \\ 3 & 54.61 & 56.49 & 54.35 & 56.33 & 90.40 \\ 4 & 54.52 & 56.34 & 54.06 & 55.93 & 95.22 \\ \textgreater{}4 & 54.31 & 56.25 & 53.97 & 55.84 & 100 \\ \hline \end{tabular} } \caption{The effect of the number of reasoning paths $K$ for the proposed DRN model.} \label{table:max_path} \end{table} To evaluate the effect of the number of reasoning path $K$ in Eq.\ref{eq:multifullprobability}, we reported the results for the different number of reasoning path $K$, as shown in Table \ref{table:max_path}. When $K$ increased from 1 to 3, F1 scores of the proposed DRN model gradually improved from 55.81 to 56.33 on the test set and the percentage of covered reasoning paths reaches 90.40\%. As the hyper-parameter $K$ continues to increase, F1 scores began to drop on the dev and test sets. On the one hand, the reason may be that the reasoning information provided by too many reasoning paths is duplicated, even noises in the remaining 9.60\% reasoning paths. On the other hand, the hyper-parameter $K$=3 can make the proposed DRN gain the highest F1 score on the dev and test sets. Therefore, we set the hyper-parameter $K$ to three in our main results in Table~\ref{tab:mianresult}. \subsection{Ablation Experiments} In the proposed DRN model, we model different reasoning tasks discriminatively using HGCRep and DLCRep, and we choose the highest scores as the final results. Instead of using the discriminative reasoning framework, previous work averaged the mention representation (HGCRep or DLCRep) to get the entity representation and concatenate the two entity representation to classify the relation, which we denote as Uniform model. Table \ref{table:ablation} shows ablation experiments of the framework and different reasoning context on the test set. It is noted that Uniform model with the discriminative reasoning framework is our DRN model. First, the DocRE models benefit from our discriminative reasoning framework no matter what the reasoning context is used. Specially, the F1 score of the model with the framework was averagely 1.21 points superior to the Uniform model on the test set no matter what context representation is used, which illustrated the effectiveness of the framework. \begin{table}[h] \begin{center} \scalebox{.83}{ \begin{tabular}{l|cl|cl|c} \hline \multicolumn{1}{c|}{Model} & \multicolumn{2}{c|}{\begin{tabular}[c]{@{}c@{}}without \\ framework\end{tabular}} & \multicolumn{2}{c|}{\begin{tabular}[c]{@{}c@{}}with \\ framework\end{tabular}} & Delta \\ \cline{2-6} & \multicolumn{1}{l}{Ign F1} & F1 & \multicolumn{1}{l}{Ign F1} & F1 & \multicolumn{1}{l}{Ign F1} \\ \hline Uniform & 53.68 & 55.79 & 54.35 & 56.33 & +0.83 \\ -DLCReps & 51.82 & 53.83 & 52.96 & 55.01 & +1.33 \\ -HGCReps & 51.21 & 53.36 & 52.35 & 54.13 & +0.97 \\ -Both & 44.73 & 51.06 & 50.68 & 52.78 & +1.71 \\ \hline \end{tabular}} \caption{Ablation experiments.} \label{table:ablation} \end{center} \end{table} Second, when we gradually remove DLCRep and HGCRep from the Uniform and the proposed DRN model, both of the model's performance drops. Specially, F1 scores of DRN without DLCRep dropped by 1.32 while F1 scores of DRN without HGCRep dropped by 2.20 respectively. This indicates that both DLCRep and HGCRep play an important role in capturing the information of nodes on the reasoning paths. When removing both of DLCPeps and HGCReps from the DRN model, the model was degraded to the BiLSTM model with our discriminative reasoning framework. Obviously, F1 scores drastically decreased on the test sets, confirming the necessity of learning DLCRep and HGCRep for modeling reasoning discriminatively. \subsection{Analysis of the Reasoning Tasks} \begin{figure*}[h!] \centering \includegraphics[scale=0.89]{casestudy.pdf} \caption{Case study.} \label{fig:casestudy} \end{figure*} In this section, we first showed the percent of all entity pairs (396,790) and entity pair with relation (12,332) on the dev set selected for three defined reasoning tasks through max operation in Eq.\eqref{eq:modelprobabilitymax}, as shown in Figure~\ref{fig:taskperformance}(a). For example, IR, LR, and CR are the intra-Sentence reasoning task, the logical reasoning task, and the coreference reasoning task, respectively. The percentages of IR, LR, and CR which is selected for all the entity pair are 19.12\%, 19.17\%, and 61.71\% for all entity pairs, respectively. This indicates that our defined three reasoning skills can completely cover all entity pairs regardless of whether these entity pairs have relationships or not. Also, the percentages of IR, LR, and CR are 47.58\%, 13.91\%, and 38.51\% for entity pairs with relation, respectively. This is consistent with the statistical result in the \citeauthor{yao-etal-2019-docred}'s work that more than 40.7\% relational facts can only be extracted from multiple sentences, validating that our method can model different reasoning skills discriminatively on the DocRE dataset. Moreover, Figure \ref{fig:taskperformance}(b) showed the results of HerterGSAN-Rec (abbreviated as Rec), GAIN, and our DRN models on three different reasoning tasks. As seen, F1 scores of the proposed DRN model are higher than that of Rec and GAIN models over all three tasks. This means that modeling reasoning types explicitly can effectively advance the DocRE. For all DocRE models, F1 scores of LR task and CR task were far inferior to that of IR task, which is consistent with the intuitive perception that the inter-sentence reasoning is more difficult than the intra-sentence reasoning. \subsection{Analysis of the Reasoning Type} \begin{table}[h] \centering \scalebox{.8}{ \begin{tabular}{cccccc} \hline \multicolumn{6}{c}{Confusion Matrix} \\ \hline & \multicolumn{1}{c|}{} & \multicolumn{3}{c|}{Truth} & \\ \cline{3-6} & \multicolumn{1}{c|}{} & IR & LR & \multicolumn{1}{c|}{CR} & Total \\ \hline \multicolumn{1}{c|}{\multirow{4}{*}{Predict}} & \multicolumn{1}{c|}{IR} & 321 & 36 & \multicolumn{1}{c|}{12} & 369 \\ \multicolumn{1}{c|}{} & \multicolumn{1}{c|}{LR} & 25 & 88 & \multicolumn{1}{c|}{29} & 142 \\ \multicolumn{1}{c|}{} & \multicolumn{1}{c|}{CR} & 88 & 129 & \multicolumn{1}{c|}{188} & 405 \\ \cline{2-6} \multicolumn{1}{c|}{} & \multicolumn{1}{c|}{Total} & 434 & 253 & \multicolumn{1}{c|}{229} & \\ \hline \hline \multicolumn{6}{c}{Metric} \\ \hline \multicolumn{2}{c|}{\multirow{2}{*}{}} & \multicolumn{1}{c|}{IR} & \multicolumn{1}{c|}{LR} & \multicolumn{1}{c|}{CR} & \\ \cline{1-6} \multicolumn{2}{c|}{} F1 Scores & 79.95 & 38.77 & \multicolumn{1}{c|}{44.87} & \\ \cline{3-6} \hline \end{tabular} } \caption{Confusion matrix of different reasoning types.} \label{table:reasoningtype} \end{table} To further show the selected different reasoning types in Eq.\eqref{eq:modelprobabilitymax}, we randomly sampled 72 documents from the dev set which contain 916 relation instances, and we ask three human to annotate the reasoning types of all the entity pairs with relation in the sampled document according to three defined reasoning types, including the intra-sentence reasoning, the logical reasoning, and the coreference reasoning (The annotation data can be found in \url{https://github.com/xwjim/DRN}). Table \ref{table:reasoningtype} shows the number and F1 scores of each selected reasoning types on the sampled 72 documents. As seen, F1 scores of IR, LR, and CR are 79.95\%, 38.77\%, and 44.87\%, respectively, indicating that modeling reasoning discriminatively is working during selecting of reasoning paths in Eq.\eqref{eq:modelprobabilitymax}. Also, our method is the capacity of recognizing not only the intra-sentence reasoning but also the intra-sentence reasoning. In addition, there is a certain percentage of the mistakenly selected reasoning types, indicating that our method may have more room for improvement in the future. \subsection{Case Study} Figure \ref{fig:casestudy} shows the relation classification about two entity pairs for our DRN model. For the first entity pair \{``\textit{Superman}"\} and \{``\textit{May 26,2002}"\}, there are reasoning paths for Task2 and Task3, and their scores are 1.7604, and 0.2841,respectively As a result, Task2 was used to predict the relation ``\{\textit{publication date}\}" between \{``\textit{Superman}"\} and \{``\textit{May 26,2002}"\} correctly. Meanwhile, the selection of Task2 is consistent with the ground-truth logical reasoning type. Moreover, the above reasoning processing is also similar to the entity pair \{``\textit{The Eminem show}"\} and \{``\textit{Eminem}"\} with three reasoning types. \section{Related Work} Early research efforts on relation extraction concentrate on predicting the relation between two entities with a sentence~\cite{zeng-etal-2014-relation,zeng-etal-2015-distant,wang-etal-2016-relation,sorokin-gurevych-2017-context,reinclass,Song_2019,wei2019novel}. These approaches do not consider interactions across mentions and ignore relations expressed across sentence boundaries. The semantics of a document context is coherent and a part of relation can only be extracted among sentences. However, as large amounts of relationships are expressed by multiple sentences, recent work starts to explore document-level relation extraction. People begin to consider the relation between disease and chemicals in the entire document of biomedical domain \cite{quirk-poon-2017-distant,DBLP:journals/corr/abs-1810-05102,zhang-etal-2018-graph,Christopoulou2019ConnectingTD,zhu-etal-2019-graph}. A large-scale general-purpose dataset for DocRE constructed from Wikipedia articles has been proposed in \cite{yao-etal-2019-docred}, which has advanced the DocRE a lot. Most approaches on DocRE are based on document graphs, which were introduced by \citeauthor{quirk-poon-2017-distant}. Specifically, they use words as nodes and construct a homogenous graph using syntax parsing tools and a graph neural network is used to capture the document information. This document graph provides a unified way of extracting the features for entity pairs. Later work extends the idea by improving neural architectures~\cite{DBLP:journals/tacl/PengPQTY17,verga-etal-2018-simultaneously,DBLP:journals/corr/abs-1810-05102} or adding more types of edges~\cite{Christopoulou2019ConnectingTD}. In the \citeauthor{Christopoulou2019ConnectingTD}'s work, the author construct the graph which contains different granularities (sentence, mention, entity) through co-occurrence and heuristic rule to model the graph without external tools. More recent most of the approach \cite{Christopoulou2019ConnectingTD,zeng-etal-2020-double,docred-rec} constructs heterogeneous graph through co-occurrence and heuristic rule to model the graph without external tools. In the \cite{zeng-etal-2020-double} constructed double graphs in different granularity to capture document-aware features and the interaction between entities. In the \cite{docred-rec} introduced a reconstructor to reconstruct the path in the graph to guide the model to learning a good node representation. Other attempts focus on the multi-entity and multi-label problems ~\cite{zhou2021atlop}. \citeauthor{zhou2021atlop} proposed two techniques to solve the problems, adaptive thresholding and localized context pooling. \section{Conclusion} In this paper, we propose a novel discriminative reasoning framework to consider different reasoning types explicitly. We use meta-path strategy to extract the reasoning path for different reasoning types. Based on the framework, we propose a Discriminative Reasoning Network~(DRN), in which we use both the heterogeneous graph context and the document-level context to represent different reasoning paths. The ablation study validates the effectiveness of our discriminative framework and different modules on the large-scale human-annotated DocRE dataset. In particular, our method archives a new state-of-the-art performance on the DocRE dataset. In the future, we will explore more diverse structure information~\cite{AAAI1816060,9097389,Cohen2020Scalable} from the input document for the discriminative reasoning framework, and apply the proposed approach to other NLP tasks~\cite{zhang-etal-2020-two,chen-etal-2020-aspect,zhang2020sg}. \section*{Acknowledgments} We are grateful to the anonymous reviewers, area chair and Program Committee for their insightful comments and suggestions. The corresponding authors are Kehai Chen and Tiejun Zhao. The work of this paper is funded by the project of National Key Research and Development Program of China (No. 2020AAA0108000). \bibliographystyle{acl_natbib}
{'timestamp': '2021-06-04T02:09:15', 'yymm': '2106', 'arxiv_id': '2106.01562', 'language': 'en', 'url': 'https://arxiv.org/abs/2106.01562'}
arxiv
\section{Introduction} \citet{mccarthy1960programs} in his seminal work outlined \emph{advice taker}, a hypothetical machine that takes declarative knowledge as input and incorporates it in its decision-making. This vision, however, remains elusive due to many challenges that are at the heart of artificial intelligence, such as knowledge representation, reasoning, belief updates, etc. Now after several decades, thanks in part to pretrained neural language models~\cite{liu2019roberta,lewis2019bart,raffel2020exploring}, we have high quality systems for many challenge tasks that seemed impossible just a few years ago~\cite{wang2019superglue,rulertaker20}. Motivated by this success, we revisit an aspect of \citeauthor{mccarthy1960programs}'s vision about machines that can revise their behavior when provided with appropriate knowledge. To ground this idea in an NLP application, we study it in the context of mitigating biased behavior of QA models. \begin{figure} \centering \includegraphics[scale=0.73,clip=true]{figures/intro-figure3.png} \caption{An example instance of how textual interventions are expected to change model behavior.} \label{fig:intro:example} \end{figure} \begin{comment} We revisit the idea of learning from instructions in the context of social biases observed in the behavior of QA. As shown in several prior works, LMs are thoroughly contaminated with social stereotypes which are carried over to downstream applications~\cite{zhao2018gender,sheng2019woman,dev2019biasinf,zhang2020hurtful}. With the increasing prevalence of such models in real applications, the ability to correct a problematic behavior has become of interest. \end{comment} We introduce \textsc{LEI}{}, a benchmark to study the ability of models to understand \emph{interventions} and amend their predictions. To build this benchmark, we begin with under-specified scenarios that expose model biases~\cite{li2020unqovering}. For example, consider the question in Fig.~\ref{fig:intro:example} (top) where the QA system shows strong preference towards one of the subjects (\emph{Adam}), even though the context does not provide any information to support either subject. We then add bias-mitigating \emph{ethical interventions}, as shown in Fig.~\ref{fig:intro:example} (middle), that convey the equitable judgement in the context of the provided story (e.g., not conditioning `hiring' on guessing applicants' gender). If a model successfully learns to amend its predictions based on such interventions, it can reduce the stereotypical biases in these models. To further verify the model's ability to truly understand the interventions, we add different controls such as a bias-amplifying \emph{adversarial} intervention (i.e., an anti-ethical recommendation), as shown in Fig.~\ref{fig:intro:example} (bottom), where the model is expected to behave in a biased manner. We use three classes of interventions across three domains to build our \textsc{LEI}{} framework.\footnote{\changed{Throughout this work, we use ``domain'' to refer to various dimensions of bias: gender bias, ethnic bias, etc.}} We evaluate recent pre-trained languages models on \textsc{LEI}{} to empirically study the extent to which it is possible to \emph{intervene} in a model's decision making and amend its predictions. Reading-comprehension models have been shown to reason and adapt to unseen instructional input and rules~\cite{brown2020language,hendrycks2020measuring}. Despite such success stories, our experiments indicate: (1) zero-shot evaluation of existing powerful models (e.g., RoBERTa) show little to no success; (2) few-shot training improves model's in-domain behavior; however, its out-of-domain generalization remains limited---an indication of the task's difficulty. \begin{comment} We use \textsc{LEI}{} to empirically study the extent to which it is possible to \emph{intervene} in a model's decision making and amend its predictions. Expecting models to respect interventions written in natural language is a slight deviation from the conventional norm of generalization. For example, a QA system is expected to be evaluated on the same kind of inputs it has seen during training. However, feeding interventions as part of the input to a model, not only changes the input distribution\tushar{Is something missing here? "not only ... but also ...?"}. While a challenging task, we feel this is a reasonable degree of generalization expected from models, given that these models are shown to reason over rules~\cite{rulertaker20} and also generalize to unseen instructional inputs~\cite{brown2020language,hendrycks2020measuring}. Despite all such successes, we expect (and empirically show) that \textsc{LEI}{} is challenging to models since ethical interventions typically contains high-level notions that are not so easy to generalize over. \end{comment} \noindent{\bf Contributions.} We introduce the problem of intervening in model predictions via suggestions posed in natural language. We investigate the extent to which ethical principles can be communicated in purely natural-language format. To our knowledge, this is the first work to formalize and study the effectiveness of natural language interventions to amend model behavior. We build upon existing benchmarks for social stereotypes and introduce \textsc{LEI}{}, a benchmark for studying ethical interventions. We demonstrate that even the best technology of today fails to appropriately respond to simply stated natural language interventions. We therefore present \textsc{LEI}{} as a language understanding challenge for the community. \section{\textsc{LEI}: Linguistic Ethical Interventions} \label{sec:task} We first describe the general task of natural language interventions followed by our proposed \underline{L}inguistic \underline{E}thical \underline{I}nterventions (\textsc{LEI}{}) task. \subsection{Natural Language Interventions} \label{subsec:interventions} We consider the reading comprehension QA setting where the input is a context $c$ and a question $q$, and the task is to produce a span in $c$ that answers $q$. We assume a model $M$ assigns a score $s(x)$ to each span $x$ in $c$, and outputs the span with the highest score; we refer to this as $M$'s \emph{behavior} on $q$. A natural language intervention $I$ is a (natural language) text that can be appended to $c$ as additional input in order to change $M$'s behavior on $q$. For simplicity, we focus on two potential answer candidate spans, $x_1$ and $x_2$. The \emph{desired behavior} with intervention $I$ can be viewed as a property or a predicate defined over $s(x_1)$ and $s(x_2)$, and captures their ideal absolute or relative values. This simple but general framing allows one to define various kinds of interventions and the corresponding desired behavior. For instance, consider an \emph{underspecified question}~\cite{li2020unqovering} where there is no information in $c$ to prefer $x_1$ over $x_2$, or vice versa, as the answer to $q$. Models (and humans!), however, may be incorrectly biased towards choosing one candidate, say $x_b$. We can define the desired behavior under a \emph{bias-mitigating intervention} as $s(x_1) = s(x_2)$. As we discuss later, without sufficient care, a model may easily learn this desired behavior based solely on dataset artifacts, without learning to understand interventions. To help alleviate this issue, we consider multiple controls: \emph{bias-amplifying interventions} where the desired behavior is $s(x_b) = 1$, and \emph{irrelevant interventions} under which $s(x_1)$ and $s(x_2)$ should remain unchanged. Similarly, we can have \emph{specified questions} as a control, where $c$ contains enough information to support $x_a$ as the correct answer. Here the desired behavior---even under a bias-mitigating intervention---is that $x_a$ is the chosen answer. \begin{figure}[t] \centering \includegraphics[scale=0.80, trim=6.4cm 5.4cm 3cm 3.1cm, clip=true]{figures/interventions-type-2.pdf} \caption{An example question in our study, along with three types of the intervention sentences.} \label{fig:interventions:examples} \end{figure} \begin{figure*}[t] \centering \includegraphics[scale=0.36, trim=0cm 0.34cm 0cm 0.0cm, clip=true]{figures/interventions-2.png} \caption{An illustration of how questions and interventions are connected to each other via thematic categories.} \label{fig:interventions} \end{figure*} \changed{ \subsection{Dataset Construction} In this section we describe the process with which we build upon and augment the recent work of} \citet{li2020unqovering}, which provides a collection of templated questions in order to quantify stereotypical biases in QA models (see the top portion of Fig.~\ref{fig:interventions:examples}). Each instance \added{in \textsc{UnQover}} consists of a context or paragraph $p$ and a question $q$. $p$ is a short story about two actors that represent two \emph{subjects} from a \emph{domain} of interest (e.g., Atheist and Buddhist in Fig.~\ref{fig:interventions:examples}, from the domain `religion'). $q$ queries the association of the subjects with an \emph{attribute} (e.g., sneaking across the border) with each attribute associated with a category $c$. The question is designed to be \emph{underspecified}, i.e., $p$ does not have any information \added{that would support preferring} one subject over the other w.r.t.\ the attribute in $q$. These instances are created by instantiating templates of paragraphs, with pre-determined lists of subjects (human names, religion names, ethnicity names); cf.~\citet{li2020unqovering} for more details. \changed{ \paragraph{Augmenting Questions with Thematic Categories and Interventions.} We use \added{questions from} \citet{li2020unqovering}'s dataset \added{spanning} three domains: religion, ethnicity and gender. We augment \added{these questions} with additional ethical \added{judgment} questions (e.g., \emph{who should receive a pay raise?}). Additionally, we label each question with one of 6 thematic categories \added{(see Fig.~\ref{fig:interventions}, middle column)} that indicate the nature of the ethical issue addressed by the question, such as \emph{poverty} or \emph{success}. Next, we write 8 different interventions for each thematic category (4 ethical, 4 adversarial) for each bias class (gender, religion, and ethnicity). To build the dataset $\mathbb{Q}$, we create a cross product of questions and interventions associated with the same thematic category (cf.~Fig.~\ref{fig:interventions}). This process leads to three classes of interventions: \emph{ethical}, \emph{adversarial}, and \emph{irrelevant} as shown in Fig.~\ref{fig:interventions:examples}. Note that the \emph{irrelevant} interventions are \emph{ethical} interventions but misaligned with the context, i.e., they discuss ethical topics unrelated to the question/context. For example, in the example in Fig.~\ref{fig:interventions:examples}, the context paragraph is about `religion' while the irrelevant intervention is about `gender'. We incorporate such interventions \added{as a control} to identify models that ignore the context when responding to interventions. } \paragraph{Under-specified Sets.} Overall, we create a total of $312$ interventions for the three bias domains.\footnote{We use expert annotation (authors) throughout. Crowdsourcing would have required training and verification to ensure annotation quality. Further, we augment at the level of QA templates \cite{li2020unqovering}, making it a small scale effort.} To build the LEI dataset, we create a cross-product of all questions in $\mathbb{Q}$ with all interventions in the same thematic category, resulting in question sets $\mathbb{Q}_E, \mathbb{Q}_A, \mathbb{Q}_I$ augmented with the three kinds of interventions, respectively. \paragraph{Specified Sets.} As yet another control, we introduce a set $\mathbb{Q}_N$ of \emph{non-ethical, specified questions}, where $p$ mentions a protected domain (e.g., religion) but, at the same time, also provides sufficient information \changed{that reveals the answer to the accompanying question, i.e., there \underline{is} a valid answer with no ethical issues.} For example, in Fig.~\ref{fig:interventions:examples}, the addition of \emph{`The Atheist man forgot to bring his passport but still managed to cross the border with a fake ID'} to \changed{ the context unambiguously reveals the answer to the question (`atheist', in this example). Therefore, in such examples, preferring a subject over another is \emph{not} a matter of ethical fairness. } Appendix~\ref{appendix:non-ethical} provides examples of \changed{the templates that were used to build our non-ethical, specified context questions.} \subsection{The \textsc{LEI}{} Challenge} We next describe our proposed \underline{l}inguistic \underline{e}thical \underline{i}nterventions (\textsc{LEI}{}) task. Given a QA model $M$ designed for benchmarks $D$, the goal is to have $M$ behave as follows: \begin{compactitem} \item \emph{Ethical interventions:} no subject bias, i.e., $s(x_1) = s(x_2)$ for questions in $\mathbb{Q}_E$; \item Control \#1, \emph{Adversarial interventions:} $s(x_b) = 1$ for questions in $\mathbb{Q}_A$; \item Control \#2, \emph{Irrelevant inter.:} $s(x_1), s(x_2)$ remain the same on questions in $\mathbb{Q}_I$ as in $\mathbb{Q}$; \item Control \#3, \emph{Specified context:} $M$ should choose $x_a$ as the answer for questions in $\mathbb{Q}_N$; \item Control \#4, \emph{Utility as a QA model:} $M$ should more or less retain its original accuracy on $D$. \end{compactitem} Here $x_b$ and $x_a$ are as defined in Sec.~\ref{subsec:interventions} and the controls discourage models from taking shortcuts. \changed{ \paragraph{Desired Model Behavior.} Doing well on these questions, especially in the presence of ethical interventions, requires models to infer \emph{when} the provided intervention applies to the context and to remain an effective QA model. In contrast to the ethical questions, for \emph{specified} questions, the ideal behavior for a model is to retain its performance on the original task(s) it was trained for. } \changed{ \subsection{Quality Assessment} We conducted a pilot study on 60 randomly selected instances (question+context+intervention). Our human annotators rarely disagreed with the gold annotation (only on 1 instance, out of 60), in terms of the intervention category (ethical, adversarial, or irrelevant). } \changed{ \subsection{Experimental Setup} } \paragraph{Evaluation Metric.} Measuring whether a model meets the desired properties w.r.t.\ the ethical domain under consideration requires extra care. \citet{li2020unqovering} showed that directly using model scores can be misleading, as these scores typically include confounding factors such as position bias that heavily contaminate model behavior. We therefore use their bias assessment metrics which explicitly account for such confounding factors. Specifically, we use the $\mu(\cdot)$ metric defined by \citet[Section 4.3]{li2020unqovering}, which captures how favorably does a model prefer one subject over another across all attributes, aggregated across all intervention templates and subjects. The desired behavior under this metric is $\mu = 0$ for ethical interventions, $\mu = 1$ for adversarial interventions and specified context, and an unchanged $\mu$ value for irrelevant interventions. For QA model, we simply use model accuracy as the metric. \begin{comment} In particular, we use the comparative measure of bias score $\mathbb{C}(x_1, x_2, q, \tau)$~\cite[Section 4.2; Eq. 6]{li2020unqovering} which measures how much $x_1$ is preferred over $x_2$ by the given model in the context of template $\tau$ and question $q \in \mathbb{Q}$. Using this metric, we define the model bias score as: \begin{equation} \theta = \avg_{x_1, x_2} \max_{q} \left|\avg_{\tau} \mathbb{C}(x_1, x_2, q, \tau) \right| \end{equation} \daniel{do we need to say how is this similar to/different from mu?} \end{comment} \paragraph{Data Splits.} As for our dev and test splits, we create splits of data with \emph{unseen} questions, subjects and interventions. This is to ensure no leakage in terms of these fillers when later in Sec.~\ref{sec:exp} we explore few-shot fine-tuning on our data. \section{Experiments} \label{sec:exp} How do transformer-based QA models respond out-of-the-box to interventions? How does their behavior change with few-shot fine tuning on various kinds of interventions? To assess this, we use RoBERTa-large~\cite{liu2019roberta} fine-tuned on SQuAD~\cite{rajpurkar-etal-2016-squad} as our base model. Appendix~\ref{appendix:model:specs} includes further details (encoding, training loss, model selection, etc.). \paragraph{Zero-Shot Evaluation.} Several recent papers have shown that one can alter the behavior of today's powerful language models by simply changing their input (see Sec.~\ref{sec:related:work}). Given the simple language of our interventions, is our base QA model perhaps already a good ethical-advice taker? \begin{figure}[t] \centering \includegraphics[scale=0.59,trim=0.2cm 0.1cm 0cm 0cm]{figures/zero-shot-roberta-1.pdf} \caption{Zero-shot evaluation on \textsc{LEI}{}. RoBERTa, out-of-the-box, does \emph{not} understand ethical interventions. } \label{fig:zero:shot} \end{figure} \begin{figure*}[t] \centering \includegraphics[scale=0.40,trim=0.7cm 0cm 0cm 0cm]{figures/figures-1-w1.pdf} \caption{The results of fine-tuning RoBERTa on our task as a function of training data size. While more training data helps with within-domain generalization (left), there is little generalization to different domains (right). } \label{fig:fine:tuning} \end{figure*} As Fig.~\ref{fig:zero:shot} shows, this is \emph{not} the case---a strong QA model based on RoBERTa-Large does not understand ethical suggestions. Neither do ethical interventions lower the $\mu$ value, nor are the control conditions met. We observed a similar behavior even with the largest T5 model (see Appendix~\ref{appendix:zeroshot:t5}), showing that current models, regardless of size, fail to respond meaningfully to interventions. \paragraph{Few-Shot Fine-Tuning.} Can few-shot intervention training \emph{familiarize} the model enough with the problem~\cite{liu2019inoculation} to improve its behavior? To gain an accurate measure of the model's generalization to unseen data, we fine-tune it on one bias domain (`religion') and evaluate it on the other two bias domains. Among these, while `ethnicity' and `gender' domains are unseen, `ethnicity' is more similar to the `religion' domain and hence might benefit more from the fine-tuning. Within-domain evaluation on `religion' domain (Fig. \ref{fig:fine:tuning}; left) indicates that the model can learn to behave according to the interventions (in particular, low bias for $\mathbb{Q}_E$ and high bias for $\mathbb{Q}_A$), even though it has \emph{not} seen the subjects, questions, and interventions in this domain. Note that the model has learned this behavior while retaining its high score on SQuAD, as also shown in the figure. The desired behavior somewhat generalizes to the `ethnicity' domain (Fig.~\ref{fig:fine:tuning}; middle), which benefits from similarity to the `religion' domain. However, there is next to no generalization to the `gender' domain (Fig.~\ref{fig:fine:tuning}; right) even though the model is now `familiar' with the notion of interventions. While models can learn the right behavior within domain with a few thousand examples, they struggle to distinguish irrelevant interventions and their generalization is still an open problem. \changed{ \paragraph{Evaluation on Specified Context Instances.} Finally we evaluate the model on specified context questions and observe trends indicating \emph{limited} generalization to these scenarios. Since the context of these questions reveals the answer. a model is justifiably expected to prefer the subject specified by the context (hence, a high $\mu$ score). \begin{figure}[t] \centering \includegraphics[scale=0.55,trim=0.9cm 0cm 0cm 0.2cm]{figures/specified_trends.pdf} \caption{Evaluations on \emph{specified} instances, \changed{where a model is expected to have a high $\mu$ score because it should prefer the subject specified by the context (female for one curve and male for the other). However, it struggles to do so. } } \label{fig:specified:eval} \end{figure} Here, we evaluate the models RoBERTa models on two subsets of the gender data: a subset where a \emph{male} name is the answer specified from the context; and similarly, another subset with \emph{female} names. Fig.~\ref{fig:specified:eval} shows the results on these two subsets, indicating limited generalization to questions with specified scenarios, too. The model clearly has difficulty understanding when to incorporate and when to ignore ethical interventions. } \section{Related Work} \label{sec:related:work} A range of recent works are based on the general idea of models revising their behavior according to changes in their input~\cite{wallace2019universal,gardner2020evaluating,emelin2020moral,ye2021zero,schick2020few,sheng2020towards}. For example, \citet{rudinger2020thinking} explore a model's ability to alter its confidence upon observing new facts. \citet{rulertaker20} show that models can take in rules and perform soft reasoning on them. This is also remotely relevant to the literature on \emph{learning from instructions} which expect a model to adapt its behavior according declarative instructions~\cite{weller2020learning,efrat2020turking,mishra2021natural}. Our work also touches upon the fairness literature ~\cite[e.g.,][]{debias2,dev2019biasinf,chang2019bias,blodgett-etal-2020-language,sun2019mitigating}. We view this problem domain as a case study for the \emph{interventions} paradigm; given the limited generalization to unseen domains, we are not drawing direct comparisons with the rich literature on bias mitigation. \begin{comment} \paragraph{Bias mitigation algorithms.} The language representations learn stereotypes often enmeshed in the massive body of text used to train them~\cite{sun2019mitigating}. These biases are subsequently passed on to downstream tasks such as co-reference resolution~\cite{rudinger2018gender,zhao2018gender}, textual entailment~\cite{dev2019biasinf}, and translation~\cite{stanovsky2019evaluating}. \cite{dinan2019queens} \cite{sheng2020towards} \cite{kumar2020nurse} \cite{shin2020neutralizing} \cite{fisher2020debiasing} \cite{ma2020powertransformer} prior approaches have often focused on discovering biases by recognizing when a model is \emph{categorically incorrect}~\cite{stanovsky2019evaluating,dev2019biasinf,nadeem2020stereoset}. Such approaches, by design, are unable to identify biases not strong enough to change the predicted category. Instead, by using underspecified questions to compare two potential candidates, we make it easier to surface underlying stereotypes in the model. Some recent works have focused on biases in downstream tasks, in the form of \emph{prediction-based} analysis where changes in the predicted labels can be used to discover biases. Arguably this setting is more natural, as it better aligns with how systems are used in real life. Several notable examples are coreference resolution~\cite{rudinger2018gender,zhao2018gender,kurita2019quantifying}, machine translation~\cite{stanovsky2019evaluating,cho2019measuring}, textual entailment~\cite{dev2019biasinf}, language generation~\cite{sheng2019woman}, or clinical classification~\cite{zhang2020hurtful}. UnQover is similar in spirit where we also rely on model predictions. But we use underspecified inputs to probe comparative biases in QA as well as the underlying LMs. By using the model scores (instead of just changes in labels) in this underspecified setting, we can reveal hard to observe stereotypes inherent in model parameters. bias mitigation techniques~\cite[e.g.,][]{debias2,dev2019biasinf,ravfogel2020null,dev2020oscar}. \end{comment} \section{Conclusion} We introduced the problem of natural language interventions, and studied this paradigm in the context of social stereotypes encoded in reading-comprehension systems. We proposed \textsc{LEI}{}, a new language understanding task where the goal is to amend a QA model’s unethical behavior by communicating context-specific principles to it as part of the input. Our empirical results suggest that state-of-the-art large-scale LMs do not know how to respond to these interventions. While few-shot learning improves the models' ability to correctly amend its behavior, these models do not generalize to interventions from a new domain. We believe our \textsc{LEI}{} task will enable progress towards the grand long-envisioned goal of \emph{advice-taker} system. \section*{Acknowledgments} This work was supported by AI2 (JZ's part-time internship) and Microsoft Ph.D. Research Fellowship. The authors thank Peter Clark and the anonymous reviewers for helpful input, and the Beaker team for their support with experiments. \section*{Ethics and Broader Implications} This paper presents a new task of introducing natural language interventions to reduce social stereotypes in model predictions. We believe this task and the accompanying dataset will enable future research on teaching machines to respect ethical suggestions like humans do. We acknowledge several limitations of the proposed techniques. First, as discussed in the literature (e.g., by \citet{gonen2019lipstick}), completely removing bias from a learning model is difficult, if not impossible. Even if a model performs perfectly as evaluated by our LEI dataset, it may still exhibit biases. Second, the interventions themselves may contain human biases. We suggest interventions should be designed and approved by ethics experts; how to do this well is out of our scope. Third, due to limited resources, the list of subjects present in the dataset is not exhaustive and does not represent all different genders, races, or religions. Finally, explainability is essential for models claiming to be capable of taking natural language ethical advice. Designing explainable advice-taking NLP technology remains an important future research direction. \bibliographystyle{acl_natbib} \section{Introduction} \citet{mccarthy1960programs} in his seminal work outlined \emph{advice taker}, a hypothetical machine that takes declarative knowledge as input and incorporates it in its decision-making. This vision, however, remains elusive due to many challenges that are at the heart of artificial intelligence, such as knowledge representation, reasoning, belief updates, etc. Now after several decades, thanks in part to pretrained neural language models~\cite{liu2019roberta,lewis2019bart,raffel2020exploring}, we have high quality systems for many challenge tasks that seemed impossible just a few years ago~\cite{wang2019superglue,rulertaker20}. Motivated by this success, we revisit an aspect of \citeauthor{mccarthy1960programs}'s vision about machines that can revise their behavior when provided with appropriate knowledge. To ground this idea in an NLP application, we study it in the context of mitigating biased behavior of QA models. \begin{figure} \centering \includegraphics[scale=0.73,clip=true]{figures/intro-figure3.png} \caption{An example instance of how textual interventions are expected to change model behavior.} \label{fig:intro:example} \end{figure} \begin{comment} We revisit the idea of learning from instructions in the context of social biases observed in the behavior of QA. As shown in several prior works, LMs are thoroughly contaminated with social stereotypes which are carried over to downstream applications~\cite{zhao2018gender,sheng2019woman,dev2019biasinf,zhang2020hurtful}. With the increasing prevalence of such models in real applications, the ability to correct a problematic behavior has become of interest. \end{comment} We introduce \textsc{LEI}{}, a benchmark to study the ability of models to understand \emph{interventions} and amend their predictions. To build this benchmark, we begin with under-specified scenarios that expose model biases~\cite{li2020unqovering}. For example, consider the question in Fig.~\ref{fig:intro:example} (top) where the QA system shows strong preference towards one of the subjects (\emph{Adam}), even though the context does not provide any information to support either subject. We then add bias-mitigating \emph{ethical interventions}, as shown in Fig.~\ref{fig:intro:example} (middle), that convey the equitable judgement in the context of the provided story (e.g., not conditioning `hiring' on guessing applicants' gender). If a model successfully learns to amend its predictions based on such interventions, it can reduce the stereotypical biases in these models. To further verify the model's ability to truly understand the interventions, we add different controls such as a bias-amplifying \emph{adversarial} intervention (i.e., an anti-ethical recommendation), as shown in Fig.~\ref{fig:intro:example} (bottom), where the model is expected to behave in a biased manner. We use three classes of interventions across three domains to build our \textsc{LEI}{} framework.\footnote{\changed{Throughout this work, we use ``domain'' to refer to various dimensions of bias: gender bias, ethnic bias, etc.}} We evaluate recent pre-trained languages models on \textsc{LEI}{} to empirically study the extent to which it is possible to \emph{intervene} in a model's decision making and amend its predictions. Reading-comprehension models have been shown to reason and adapt to unseen instructional input and rules~\cite{brown2020language,hendrycks2020measuring}. Despite such success stories, our experiments indicate: (1) zero-shot evaluation of existing powerful models (e.g., RoBERTa) show little to no success; (2) few-shot training improves model's in-domain behavior; however, its out-of-domain generalization remains limited---an indication of the task's difficulty. \begin{comment} We use \textsc{LEI}{} to empirically study the extent to which it is possible to \emph{intervene} in a model's decision making and amend its predictions. Expecting models to respect interventions written in natural language is a slight deviation from the conventional norm of generalization. For example, a QA system is expected to be evaluated on the same kind of inputs it has seen during training. However, feeding interventions as part of the input to a model, not only changes the input distribution\tushar{Is something missing here? "not only ... but also ...?"}. While a challenging task, we feel this is a reasonable degree of generalization expected from models, given that these models are shown to reason over rules~\cite{rulertaker20} and also generalize to unseen instructional inputs~\cite{brown2020language,hendrycks2020measuring}. Despite all such successes, we expect (and empirically show) that \textsc{LEI}{} is challenging to models since ethical interventions typically contains high-level notions that are not so easy to generalize over. \end{comment} \noindent{\bf Contributions.} We introduce the problem of intervening in model predictions via suggestions posed in natural language. We investigate the extent to which ethical principles can be communicated in purely natural-language format. To our knowledge, this is the first work to formalize and study the effectiveness of natural language interventions to amend model behavior. We build upon existing benchmarks for social stereotypes and introduce \textsc{LEI}{}, a benchmark for studying ethical interventions. We demonstrate that even the best technology of today fails to appropriately respond to simply stated natural language interventions. We therefore present \textsc{LEI}{} as a language understanding challenge for the community. \section{\textsc{LEI}: Linguistic Ethical Interventions} \label{sec:task} We first describe the general task of natural language interventions followed by our proposed \underline{L}inguistic \underline{E}thical \underline{I}nterventions (\textsc{LEI}{}) task. \subsection{Natural Language Interventions} \label{subsec:interventions} We consider the reading comprehension QA setting where the input is a context $c$ and a question $q$, and the task is to produce a span in $c$ that answers $q$. We assume a model $M$ assigns a score $s(x)$ to each span $x$ in $c$, and outputs the span with the highest score; we refer to this as $M$'s \emph{behavior} on $q$. A natural language intervention $I$ is a (natural language) text that can be appended to $c$ as additional input in order to change $M$'s behavior on $q$. For simplicity, we focus on two potential answer candidate spans, $x_1$ and $x_2$. The \emph{desired behavior} with intervention $I$ can be viewed as a property or a predicate defined over $s(x_1)$ and $s(x_2)$, and captures their ideal absolute or relative values. This simple but general framing allows one to define various kinds of interventions and the corresponding desired behavior. For instance, consider an \emph{underspecified question}~\cite{li2020unqovering} where there is no information in $c$ to prefer $x_1$ over $x_2$, or vice versa, as the answer to $q$. Models (and humans!), however, may be incorrectly biased towards choosing one candidate, say $x_b$. We can define the desired behavior under a \emph{bias-mitigating intervention} as $s(x_1) = s(x_2)$. As we discuss later, without sufficient care, a model may easily learn this desired behavior based solely on dataset artifacts, without learning to understand interventions. To help alleviate this issue, we consider multiple controls: \emph{bias-amplifying interventions} where the desired behavior is $s(x_b) = 1$, and \emph{irrelevant interventions} under which $s(x_1)$ and $s(x_2)$ should remain unchanged. Similarly, we can have \emph{specified questions} as a control, where $c$ contains enough information to support $x_a$ as the correct answer. Here the desired behavior---even under a bias-mitigating intervention---is that $x_a$ is the chosen answer. \begin{figure}[t] \centering \includegraphics[scale=0.80, trim=6.4cm 5.4cm 3cm 3.1cm, clip=true]{figures/interventions-type-2.pdf} \caption{An example question in our study, along with three types of the intervention sentences.} \label{fig:interventions:examples} \end{figure} \begin{figure*}[t] \centering \includegraphics[scale=0.36, trim=0cm 0.34cm 0cm 0.0cm, clip=true]{figures/interventions-2.png} \caption{An illustration of how questions and interventions are connected to each other via thematic categories.} \label{fig:interventions} \end{figure*} \changed{ \subsection{Dataset Construction} In this section we describe the process with which we build upon and augment the recent work of} \citet{li2020unqovering}, which provides a collection of templated questions in order to quantify stereotypical biases in QA models (see the top portion of Fig.~\ref{fig:interventions:examples}). Each instance \added{in \textsc{UnQover}} consists of a context or paragraph $p$ and a question $q$. $p$ is a short story about two actors that represent two \emph{subjects} from a \emph{domain} of interest (e.g., Atheist and Buddhist in Fig.~\ref{fig:interventions:examples}, from the domain `religion'). $q$ queries the association of the subjects with an \emph{attribute} (e.g., sneaking across the border) with each attribute associated with a category $c$. The question is designed to be \emph{underspecified}, i.e., $p$ does not have any information \added{that would support preferring} one subject over the other w.r.t.\ the attribute in $q$. These instances are created by instantiating templates of paragraphs, with pre-determined lists of subjects (human names, religion names, ethnicity names); cf.~\citet{li2020unqovering} for more details. \changed{ \paragraph{Augmenting Questions with Thematic Categories and Interventions.} We use \added{questions from} \citet{li2020unqovering}'s dataset \added{spanning} three domains: religion, ethnicity and gender. We augment \added{these questions} with additional ethical \added{judgment} questions (e.g., \emph{who should receive a pay raise?}). Additionally, we label each question with one of 6 thematic categories \added{(see Fig.~\ref{fig:interventions}, middle column)} that indicate the nature of the ethical issue addressed by the question, such as \emph{poverty} or \emph{success}. Next, we write 8 different interventions for each thematic category (4 ethical, 4 adversarial) for each bias class (gender, religion, and ethnicity). To build the dataset $\mathbb{Q}$, we create a cross product of questions and interventions associated with the same thematic category (cf.~Fig.~\ref{fig:interventions}). This process leads to three classes of interventions: \emph{ethical}, \emph{adversarial}, and \emph{irrelevant} as shown in Fig.~\ref{fig:interventions:examples}. Note that the \emph{irrelevant} interventions are \emph{ethical} interventions but misaligned with the context, i.e., they discuss ethical topics unrelated to the question/context. For example, in the example in Fig.~\ref{fig:interventions:examples}, the context paragraph is about `religion' while the irrelevant intervention is about `gender'. We incorporate such interventions \added{as a control} to identify models that ignore the context when responding to interventions. } \paragraph{Under-specified Sets.} Overall, we create a total of $312$ interventions for the three bias domains.\footnote{We use expert annotation (authors) throughout. Crowdsourcing would have required training and verification to ensure annotation quality. Further, we augment at the level of QA templates \cite{li2020unqovering}, making it a small scale effort.} To build the LEI dataset, we create a cross-product of all questions in $\mathbb{Q}$ with all interventions in the same thematic category, resulting in question sets $\mathbb{Q}_E, \mathbb{Q}_A, \mathbb{Q}_I$ augmented with the three kinds of interventions, respectively. \paragraph{Specified Sets.} As yet another control, we introduce a set $\mathbb{Q}_N$ of \emph{non-ethical, specified questions}, where $p$ mentions a protected domain (e.g., religion) but, at the same time, also provides sufficient information \changed{that reveals the answer to the accompanying question, i.e., there \underline{is} a valid answer with no ethical issues.} For example, in Fig.~\ref{fig:interventions:examples}, the addition of \emph{`The Atheist man forgot to bring his passport but still managed to cross the border with a fake ID'} to \changed{ the context unambiguously reveals the answer to the question (`atheist', in this example). Therefore, in such examples, preferring a subject over another is \emph{not} a matter of ethical fairness. } Appendix~\ref{appendix:non-ethical} provides examples of \changed{the templates that were used to build our non-ethical, specified context questions.} \subsection{The \textsc{LEI}{} Challenge} We next describe our proposed \underline{l}inguistic \underline{e}thical \underline{i}nterventions (\textsc{LEI}{}) task. Given a QA model $M$ designed for benchmarks $D$, the goal is to have $M$ behave as follows: \begin{compactitem} \item \emph{Ethical interventions:} no subject bias, i.e., $s(x_1) = s(x_2)$ for questions in $\mathbb{Q}_E$; \item Control \#1, \emph{Adversarial interventions:} $s(x_b) = 1$ for questions in $\mathbb{Q}_A$; \item Control \#2, \emph{Irrelevant inter.:} $s(x_1), s(x_2)$ remain the same on questions in $\mathbb{Q}_I$ as in $\mathbb{Q}$; \item Control \#3, \emph{Specified context:} $M$ should choose $x_a$ as the answer for questions in $\mathbb{Q}_N$; \item Control \#4, \emph{Utility as a QA model:} $M$ should more or less retain its original accuracy on $D$. \end{compactitem} Here $x_b$ and $x_a$ are as defined in Sec.~\ref{subsec:interventions} and the controls discourage models from taking shortcuts. \changed{ \paragraph{Desired Model Behavior.} Doing well on these questions, especially in the presence of ethical interventions, requires models to infer \emph{when} the provided intervention applies to the context and to remain an effective QA model. In contrast to the ethical questions, for \emph{specified} questions, the ideal behavior for a model is to retain its performance on the original task(s) it was trained for. } \changed{ \subsection{Quality Assessment} We conducted a pilot study on 60 randomly selected instances (question+context+intervention). Our human annotators rarely disagreed with the gold annotation (only on 1 instance, out of 60), in terms of the intervention category (ethical, adversarial, or irrelevant). } \changed{ \subsection{Experimental Setup} } \paragraph{Evaluation Metric.} Measuring whether a model meets the desired properties w.r.t.\ the ethical domain under consideration requires extra care. \citet{li2020unqovering} showed that directly using model scores can be misleading, as these scores typically include confounding factors such as position bias that heavily contaminate model behavior. We therefore use their bias assessment metrics which explicitly account for such confounding factors. Specifically, we use the $\mu(\cdot)$ metric defined by \citet[Section 4.3]{li2020unqovering}, which captures how favorably does a model prefer one subject over another across all attributes, aggregated across all intervention templates and subjects. The desired behavior under this metric is $\mu = 0$ for ethical interventions, $\mu = 1$ for adversarial interventions and specified context, and an unchanged $\mu$ value for irrelevant interventions. For QA model, we simply use model accuracy as the metric. \begin{comment} In particular, we use the comparative measure of bias score $\mathbb{C}(x_1, x_2, q, \tau)$~\cite[Section 4.2; Eq. 6]{li2020unqovering} which measures how much $x_1$ is preferred over $x_2$ by the given model in the context of template $\tau$ and question $q \in \mathbb{Q}$. Using this metric, we define the model bias score as: \begin{equation} \theta = \avg_{x_1, x_2} \max_{q} \left|\avg_{\tau} \mathbb{C}(x_1, x_2, q, \tau) \right| \end{equation} \daniel{do we need to say how is this similar to/different from mu?} \end{comment} \paragraph{Data Splits.} As for our dev and test splits, we create splits of data with \emph{unseen} questions, subjects and interventions. This is to ensure no leakage in terms of these fillers when later in Sec.~\ref{sec:exp} we explore few-shot fine-tuning on our data. \section{Experiments} \label{sec:exp} How do transformer-based QA models respond out-of-the-box to interventions? How does their behavior change with few-shot fine tuning on various kinds of interventions? To assess this, we use RoBERTa-large~\cite{liu2019roberta} fine-tuned on SQuAD~\cite{rajpurkar-etal-2016-squad} as our base model. Appendix~\ref{appendix:model:specs} includes further details (encoding, training loss, model selection, etc.). \paragraph{Zero-Shot Evaluation.} Several recent papers have shown that one can alter the behavior of today's powerful language models by simply changing their input (see Sec.~\ref{sec:related:work}). Given the simple language of our interventions, is our base QA model perhaps already a good ethical-advice taker? \begin{figure}[t] \centering \includegraphics[scale=0.59,trim=0.2cm 0.1cm 0cm 0cm]{figures/zero-shot-roberta-1.pdf} \caption{Zero-shot evaluation on \textsc{LEI}{}. RoBERTa, out-of-the-box, does \emph{not} understand ethical interventions. } \label{fig:zero:shot} \end{figure} \begin{figure*}[t] \centering \includegraphics[scale=0.40,trim=0.7cm 0cm 0cm 0cm]{figures/figures-1-w1.pdf} \caption{The results of fine-tuning RoBERTa on our task as a function of training data size. While more training data helps with within-domain generalization (left), there is little generalization to different domains (right). } \label{fig:fine:tuning} \end{figure*} As Fig.~\ref{fig:zero:shot} shows, this is \emph{not} the case---a strong QA model based on RoBERTa-Large does not understand ethical suggestions. Neither do ethical interventions lower the $\mu$ value, nor are the control conditions met. We observed a similar behavior even with the largest T5 model (see Appendix~\ref{appendix:zeroshot:t5}), showing that current models, regardless of size, fail to respond meaningfully to interventions. \paragraph{Few-Shot Fine-Tuning.} Can few-shot intervention training \emph{familiarize} the model enough with the problem~\cite{liu2019inoculation} to improve its behavior? To gain an accurate measure of the model's generalization to unseen data, we fine-tune it on one bias domain (`religion') and evaluate it on the other two bias domains. Among these, while `ethnicity' and `gender' domains are unseen, `ethnicity' is more similar to the `religion' domain and hence might benefit more from the fine-tuning. Within-domain evaluation on `religion' domain (Fig. \ref{fig:fine:tuning}; left) indicates that the model can learn to behave according to the interventions (in particular, low bias for $\mathbb{Q}_E$ and high bias for $\mathbb{Q}_A$), even though it has \emph{not} seen the subjects, questions, and interventions in this domain. Note that the model has learned this behavior while retaining its high score on SQuAD, as also shown in the figure. The desired behavior somewhat generalizes to the `ethnicity' domain (Fig.~\ref{fig:fine:tuning}; middle), which benefits from similarity to the `religion' domain. However, there is next to no generalization to the `gender' domain (Fig.~\ref{fig:fine:tuning}; right) even though the model is now `familiar' with the notion of interventions. While models can learn the right behavior within domain with a few thousand examples, they struggle to distinguish irrelevant interventions and their generalization is still an open problem. \changed{ \paragraph{Evaluation on Specified Context Instances.} Finally we evaluate the model on specified context questions and observe trends indicating \emph{limited} generalization to these scenarios. Since the context of these questions reveals the answer. a model is justifiably expected to prefer the subject specified by the context (hence, a high $\mu$ score). \begin{figure}[t] \centering \includegraphics[scale=0.55,trim=0.9cm 0cm 0cm 0.2cm]{figures/specified_trends.pdf} \caption{Evaluations on \emph{specified} instances, \changed{where a model is expected to have a high $\mu$ score because it should prefer the subject specified by the context (female for one curve and male for the other). However, it struggles to do so. } } \label{fig:specified:eval} \end{figure} Here, we evaluate the models RoBERTa models on two subsets of the gender data: a subset where a \emph{male} name is the answer specified from the context; and similarly, another subset with \emph{female} names. Fig.~\ref{fig:specified:eval} shows the results on these two subsets, indicating limited generalization to questions with specified scenarios, too. The model clearly has difficulty understanding when to incorporate and when to ignore ethical interventions. } \section{Related Work} \label{sec:related:work} A range of recent works are based on the general idea of models revising their behavior according to changes in their input~\cite{wallace2019universal,gardner2020evaluating,emelin2020moral,ye2021zero,schick2020few,sheng2020towards}. For example, \citet{rudinger2020thinking} explore a model's ability to alter its confidence upon observing new facts. \citet{rulertaker20} show that models can take in rules and perform soft reasoning on them. This is also remotely relevant to the literature on \emph{learning from instructions} which expect a model to adapt its behavior according declarative instructions~\cite{weller2020learning,efrat2020turking,mishra2021natural}. Our work also touches upon the fairness literature ~\cite[e.g.,][]{debias2,dev2019biasinf,chang2019bias,blodgett-etal-2020-language,sun2019mitigating}. We view this problem domain as a case study for the \emph{interventions} paradigm; given the limited generalization to unseen domains, we are not drawing direct comparisons with the rich literature on bias mitigation. \begin{comment} \paragraph{Bias mitigation algorithms.} The language representations learn stereotypes often enmeshed in the massive body of text used to train them~\cite{sun2019mitigating}. These biases are subsequently passed on to downstream tasks such as co-reference resolution~\cite{rudinger2018gender,zhao2018gender}, textual entailment~\cite{dev2019biasinf}, and translation~\cite{stanovsky2019evaluating}. \cite{dinan2019queens} \cite{sheng2020towards} \cite{kumar2020nurse} \cite{shin2020neutralizing} \cite{fisher2020debiasing} \cite{ma2020powertransformer} prior approaches have often focused on discovering biases by recognizing when a model is \emph{categorically incorrect}~\cite{stanovsky2019evaluating,dev2019biasinf,nadeem2020stereoset}. Such approaches, by design, are unable to identify biases not strong enough to change the predicted category. Instead, by using underspecified questions to compare two potential candidates, we make it easier to surface underlying stereotypes in the model. Some recent works have focused on biases in downstream tasks, in the form of \emph{prediction-based} analysis where changes in the predicted labels can be used to discover biases. Arguably this setting is more natural, as it better aligns with how systems are used in real life. Several notable examples are coreference resolution~\cite{rudinger2018gender,zhao2018gender,kurita2019quantifying}, machine translation~\cite{stanovsky2019evaluating,cho2019measuring}, textual entailment~\cite{dev2019biasinf}, language generation~\cite{sheng2019woman}, or clinical classification~\cite{zhang2020hurtful}. UnQover is similar in spirit where we also rely on model predictions. But we use underspecified inputs to probe comparative biases in QA as well as the underlying LMs. By using the model scores (instead of just changes in labels) in this underspecified setting, we can reveal hard to observe stereotypes inherent in model parameters. bias mitigation techniques~\cite[e.g.,][]{debias2,dev2019biasinf,ravfogel2020null,dev2020oscar}. \end{comment} \section{Conclusion} We introduced the problem of natural language interventions, and studied this paradigm in the context of social stereotypes encoded in reading-comprehension systems. We proposed \textsc{LEI}{}, a new language understanding task where the goal is to amend a QA model’s unethical behavior by communicating context-specific principles to it as part of the input. Our empirical results suggest that state-of-the-art large-scale LMs do not know how to respond to these interventions. While few-shot learning improves the models' ability to correctly amend its behavior, these models do not generalize to interventions from a new domain. We believe our \textsc{LEI}{} task will enable progress towards the grand long-envisioned goal of \emph{advice-taker} system. \section*{Acknowledgments} This work was supported by AI2 (JZ's part-time internship) and Microsoft Ph.D. Research Fellowship. The authors thank Peter Clark and the anonymous reviewers for helpful input, and the Beaker team for their support with experiments. \section*{Ethics and Broader Implications} This paper presents a new task of introducing natural language interventions to reduce social stereotypes in model predictions. We believe this task and the accompanying dataset will enable future research on teaching machines to respect ethical suggestions like humans do. We acknowledge several limitations of the proposed techniques. First, as discussed in the literature (e.g., by \citet{gonen2019lipstick}), completely removing bias from a learning model is difficult, if not impossible. Even if a model performs perfectly as evaluated by our LEI dataset, it may still exhibit biases. Second, the interventions themselves may contain human biases. We suggest interventions should be designed and approved by ethics experts; how to do this well is out of our scope. Third, due to limited resources, the list of subjects present in the dataset is not exhaustive and does not represent all different genders, races, or religions. Finally, explainability is essential for models claiming to be capable of taking natural language ethical advice. Designing explainable advice-taking NLP technology remains an important future research direction. \bibliographystyle{acl_natbib}
{'timestamp': '2021-06-04T02:04:47', 'yymm': '2106', 'arxiv_id': '2106.01465', 'language': 'en', 'url': 'https://arxiv.org/abs/2106.01465'}
arxiv
\section{Introduction} \input{intro.tex} \section{Related Work} \input{related_work.tex} \section{Model} \input{model.tex} \section{Dataset} \input{dataset.tex} \section{Experiments} \input{experiments.tex} \section{Conclusion} \input{conclusion.tex} \section*{Acknowledgements} \input{acknowledgements} \FloatBarrier \bibliographystyle{acl_natbib} \subsection{Experimental Setup} \label{sec:expt_setup} We compare the performance of different alignment methods using two evaluation tasks - \textbf{few-shot link prediction} and \textbf{analogical reasoning}. The few-shot link prediction task is designed to test the capability of the alignment model to inject the relational information present in text into the knowledge base embeddings. The train-test set for this task is constructed such that the test set contains triples corresponding to a subset of entities in the support set, but each of these entities is observed only once in the training triples set. Thus, the model is tasked to do link prediction on entities that occur rarely in the training set (hence the term ``few-shot''). The training and test sets consist of 260.1 M and 110.8 K triples respectively. For this setting, both entities of each triple in the test set are contained in the support set. The purpose of the analogical reasoning task is to test the information flow from the knowledge-base embeddings to the skip-gram embeddings. This task was first proposed in \citet{mikolov2013distributed} to test the syntactic and semantic information present in learned word embeddings. We choose the top 50 relations from the set of one-to-one and many-to-one relations based on the frequency of occurrence and construct a dataset of 1000 analogical reasoning examples for each relation. The 1st pair of entities is randomly chosen from the training triples set, as the pair of entities involved in that relation. The 2nd pair of entities is obtained from the test triples set. More formally, given a pair of entities $(h_1, t_1)$ and the head entity of the 2nd pair $(h_2)$, the task is to predict the tail entity $(t_2)$ of the 2nd pair by comparing the cosine similarity between the embedding of candidate entity $(\bm{e}_{t_2})$ and $(\bm{e}_{h_2} + \bm{e}_{t_1} - \bm{e}_{h_1})$. \noindent \textbf{Evaluation protocol.} For link prediction evaluation on a given test triple $(h, r, t)$, we corrupt either the head entity (by generating triplets like $(h^{'}, r, t)$) or the tail entity (by generating triplets like $(h, r, t^{'})$) of the triple and then rank the score of correct entity amongst all entities in the candidate set. Due to the extremely large entity vocabulary size in Wikidata, we restrict the size of the candidate set to a sample of 1000 entities whose types lie in the set of permissible domain/range types for that relation \cite{lerer2019pytorch, krompass2015type}. In cases where the number of such entities is less than 1000, we choose the entire set of those entities. In addition, we filter any positive triplets (triplets that exist in the KB) from the set of negative triplets for this evaluation, also known as \textit{filtered evaluation} setting. We report results on standard evaluation metrics - Mean Rank (MR), Hits@1, and Hits@10. For this task, we compare the TransE model and the KB-side embeddings of different alignment methods. For the analogical reasoning task, we report Mean Rank (MR), Hits@1, and Hits@10 by ranking the correct entity $t_2$ against the entities in the candidate set. The candidate set for the tail entity $t_2$ is a set of 1K entities sampled from the support set (excluding $h_1$, $h_2$ and $t_1$) according to the node degree. All reported metrics are macro-averaged over the results for different relations. Here, we compare the skip-gram model embeddings with the textual embeddings obtained from different alignment methods. \subsection{Implementation} The scale of the training data (both the Wikidata Knowledge Base and the Wikipedia corpus) is huge, so the efficient implementation of the model is a key challenge. For efficient implementation of the TransE model, we used the DGL-KE \cite{zheng2020dgl} library. It uses graph partitioning to train across multiple partitions of the knowledge base in parallel and incorporates engineering optimizations like efficient negative sampling to reduce the training time by orders of magnitude compared to naive implementations. The skip-gram model is implemented using PyTorch \cite{paszke2019pytorch} and Wikipedia2vec \cite{yamada2020wikipedia2vec} libraries. For training, we optimize the parameters of the TransE and skip-gram models alternately in each epoch. We use the Adagrad \cite{duchi2011adaptive} optimizer for the KBE model and SGD for the skip-gram model. For both models, the training is done by multiple processes asynchronously using the Hogwild \cite{niu2011hogwild} approach. This introduces additional challenges like synchronizing the weights of parameters among different training processes. We choose the values of balance parameter for each of the two evaluation tasks based on the performance of aligned KB and textual embeddings on a small set of analogy examples (disjoint from the analogy test set used in the main evaluation). Our implementation can serve as a good resource to do a similar large-scale analysis of KB-Text alignment approaches in the future. \input{overall_results_table.tex} \subsection{Overall Results} The overall results for the two evaluation tasks are given in Table~\ref{tab:results_overall}. For the few-shot link prediction task, we observe that all the alignment techniques lead to improved performance of the KB embeddings over the naive TransE baseline. The Same Embedding alignment approach performs the best followed by Entity Name alignment, Projection, and alignment using Wikipedia Anchors. The use of the same embeddings for the shared entities helps in propagating the factual knowledge present in the text to the KB more efficiently, so the Same Embedding alignment performs better than others. The Entity Name alignment approach is worse than the Same embedding alignment approach since the test set entities occur less often in the train set (as the dataset is few-shot). So, the name graph doesn't make a substantial difference here. For the analogical reasoning task, the results show that all alignment approaches obtain an improvement over the naive skip-gram baseline. The Entity Name alignment approach performs the best followed by Projection, Same Embedding alignment, and alignment using Wikipedia Anchors. The good performance of the Entity Name alignment approach could be explained by the fact that for every test analogy example $(e_{h_1}, e_{t_1}, e_{h_2}, e_{t_2})$, there is a relation $r$ present between the entity pairs $(e_{h_1}, e_{t_1})$ and $(e_{h_2}, e_{t_2})$, although that is unobserved. Since $e_h$ and $e_t$ also occur in the KB, due to the extra added triples, the KB reasoning process incorporates the relation $r$ in these embeddings, just like it does for KB entities $h$ and $t$. The other approaches viz. Same Embedding alignment, Projection, and Wikipedia Anchors don't have a mechanism for explicit KB reasoning like the Entity Name alignment approach. The Projection technique outperforms the Same Embedding alignment as the embeddings in the two spaces are less tightly coupled in the former, so it can take advantage of the complementary relational information in textual as well as the KB embeddings. \subsection{Fine-grained Analysis} In this section, we present a fine-grained analysis of the efficacy of the alignment methods w.r.t. changes in training data size and whether the test set entities belong to the support set. We also study the impact of balance parameter on the performance of the two evaluation tasks. Due to resource constraint, we do this analysis on two representative methods of different nature - Projection alignment and Same Embedding alignment. \noindent \textbf{Effect of Training data size.} To study and differentiate the impact of entities present in the support set on the performance of the few-shot link prediction task, we create two versions of the training set with different sizes: \begin{enumerate}[label=(\alph*)] \item \textit{Full version}: In this version of the training set, we include all triples in Wikidata which don't violate the few-shot property of the dataset. This is the same as the training set for the evaluation proposed in Section~\ref{sec:expt_setup}. \item \textit{Support version}: In this version of the training set, we exclude triples from the \textit{full} version whose either head or tail entity isn't present in the support set. \end{enumerate} Next, we try to analyze the impact of whether the head/tail entity of the test triple is present in the support set $\mathcal{S}$, on the few-shot link prediction performance. To this end, we create two versions of test sets: \begin{enumerate}[label=(\alph*)] \item \textit{Both in support}: Both head and tail entity of the triple lie in the support set. \item \textit{Missing support}: Atleast one out of the head/tail entity of the triple doesn't lie in the support set. \end{enumerate} The statistics for this dataset are given in Table~\ref{tab:dataset_stat}. \input{overall_balance_param_tbl.tex} \input{stats_tbl.tex} The results for the training data size analysis for different alignment methods on Test set (Both in support) are shown in Table~\ref{tab:few_shot_size_setting}. The results show that for both Projection and Same Embedding alignment approach, the performance is significantly better with using the full training set of triples instead of just the support set. This shows that triples involving non-support set entities play a vital role in helping learn better entity and relation representations which in turn helps in injecting textual information to the KB embeddings via alignment. \noindent \textbf{Effect of Support set for Test triples.} Here, we investigate the performance of the few-shot link prediction task for triples whose entities may not lie in the support set. The results for this evaluation are given in Table~\ref{tab:few_shot_missing_support}. We observe that there is no significant gain in performance for any of the alignment methods over the simple TransE baseline. This shows these alignment methods are only effective for triples whose both entities lie in the support set. \input{train_size_ablation_tbl.tex} \noindent \textbf{Effect of balance parameter.} In this analysis, we study the role of balance parameter for the Projection alignment method. This parameter controls the extent of alignment between the two embedding spaces. The higher the value of the balance parameter, the more the embedding tries to capture the entity information from the other embedding space, rather than its own. The results of this study are shown in Table~\ref{tab:overall_balance_param}. The peak performance for the few-shot link prediction task is obtained for balance parameter = 1e0 in terms of Hits@1 and Hits@10. Whereas, for the analogical reasoning task, the peak performance is obtained for balance parameter = 1e-3. This difference in the optimal value of the balance parameter can be explained by the fact that the skip-gram objective relies on cosine similarity which is more sensitive to changes in the values of vector embeddings than the TransE model. We show this analytically. Let $(h, r, t)$ be a KB triple and let $\bm{h}$, $\bm{r}$, and $\bm{t}$ denote the embeddings of $h$, $r$, and $t$ respectively. The partial derivative of score function of the triple w.r.t. $\bm{h}$ is given by \begin{align*} d_r(\bm{h}, \bm{t}) &= \norm{\bm{h}+\bm{r}-\bm{t}}_2 \\ \norm{\frac{\partial d_r(\bm{h}, \bm{t})}{\partial \bm{h}}}_2 &= \norm{\frac{(\bm{h} + \bm{r} - \bm{t})}{\norm{\bm{h}+\bm{r}-\bm{t}}_2}}_2 = 1 \end{align*} Similarly, let $(u, v)$ be an entity-word pair in the text corpus. Let $\bm{u}$ and $\bm{v}$ denote the embeddings of $u$ and $v$ respectively. The partial derivative of the score function for the entity-word pair $(u, v)$ w.r.t. $\bm{u}$ is given by \begin{align*} d(\bm{u}, \bm{v}) &= exp(\bm{u}^T \bm{v}) \\ \norm{\frac{\partial d(\bm{u}, \bm{v})}{\partial \bm{u}}}_2 &= \norm{(\bm{u}^T \bm{v}) \bm{v}}_2 = (\bm{u}^T \bm{v}) \norm{\bm{v}}_2 \end{align*} The value of $\norm{\frac{\partial d_r(\bm{h}, \bm{t})}{\partial \bm{h}}}_2$ equals 1 whereas for the skip-gram model, $\norm{\frac{\partial d(\bm{u}, \bm{v})}{\partial \bm{u}}}_2 = (\bm{u}^T \bm{v}) \norm{\bm{v}}_2$ which is greater than 1, as seen empirically. This shows that the skip-gram embeddings are more sensitive to delta changes in values of the parameters. For them to be reasonably assigned with their KB counterparts without losing the textual information, thus a lower value of balance parameter is optimal. \input{covid_tbl.tex} \subsection{Case study on COVID related triples} Recently, the COVID pandemic \cite{fauci2020covid} has been responsible for bringing a tremendous change in the lives of people across the globe. Through this case study, we demonstrate that aligning embedding representations can help us do knowledge base completion for recent events like COVID-19. We selected 4 relevant relations (``Risk factor'', ``Symptoms'', ``Medical Condition'' and ``Cause of Death'') with atleast 10 triples in the difference between March 2020 and December 2020 snapshots of Wikidata. We use the March 2020 Wikidata and December 2020 Wikipedia to train the alignment models and do link prediction on these triples. For each of the relations, we keep the COVID-19 entity (Entity ID: Q84263196) unchanged and corrupt the other entity in the triple. This would correspond to asking questions like ``What are the symptoms of COVID-19?'', ``Who died due to COVID-19?'' etc. The results are shown in Table~\ref{tab:covid_results_mr}. We observe that the Projection model obtains a decent improvement over the TransE model on the link prediction task on these triples in terms of Mean Rank. Similarly, the Same Embedding alignment model obtains outperforms the TransE baseline for three out of four relations. This case study gives a real-life use-case of how the text information can be injected into the KB embeddings using alignment in scenarios when such information is not yet curated in the KB in structured form. \subsection{Knowledge Base embedding model} We use the TransE model \cite{bordes2013translating} to learn the KB embeddings. We use the loss function proposed in \citet{sun2019rotate} as our KB embedding objective. \begin{equation*} \begin{aligned}[b] &\mathcal{L}_{KB} =\\ &\sum_{(\bm{h},\bm{r},\bm{t}) \in S\cup S^{'}} \textrm{log}(1+\textrm{exp}(y * (-\gamma + d_r(\bm{h}, \bm{t})))) \end{aligned} \end{equation*} Here, $d_r(\bm{h}, \bm{t}) = \norm{\bm{h}+\bm{r}-\bm{t}}_2$ denotes the score function for the triple $(h, r, t)$, $S$ denotes the set of positive triples and $S^{'}$ denotes the set of corrupted triples obtained by replacing the head or tail of a positive triple with a random entity. $\gamma$ is a hyper-parameter which denotes the margin and $y$ denotes the label (+1 for positive triple and -1 for negative triple). \subsection{Skip-gram model} The skip-gram model learns the embeddings of words and entities by modeling the word-word, word-entity and entity-entity co-occurrences. We use the skip-gram model proposed in \citet{yamada2016joint} for learning the word and entity representations. Let $\mathcal{W}$ and $\mathcal{E}$ denote the set of all words and entities in the vocabulary respectively and $c$ denote the size of the context window. \begin{itemize} \item \textbf{Word-Word co-occurrence model}: The skip-gram model is trained to predict the target word given a context word. Given a sequence of $N$ words $w_1, w_2, \cdots, w_N$, the skip-gram model maximizes the following objective: $$ \mathcal{L}_{ww} = \sum_{n=1}^N \sum_{-c\leq j \leq c;j\neq 0} \textrm{log}\;P(w_{n+j}|w_n)$$ where $ p(w_O|w_I) = \frac{exp({v^{'}_{w_I}}^T v_{w_O})}{\sum_{w \in \mathcal{W}} exp({v^{'}_{w_I}}^T v_{w})}$. Here, $v^{'}_w$ and $v_w$ denote the input and output representations of the word $w$ respectively. The input representations are used as the final representations for both words and entities. \item \textbf{Word-Entity co-occurrence model}: In the word-entity co-occurrence model, the model is trained to predict the context words of an entity pointed to by the target anchor. The training objective corresponding to the word-entity co-occurrences is \begin{align*} \mathcal{L}_{we} =\sum_{(e_i, C_{e_i})\in \mathcal{A}}\sum_{w_o\in C_{e_i}}\textrm{log}\;p(w_o|e_i) \end{align*} Here, $\mathcal{A}$ denotes the set of anchors in the corpus. Each anchor consists of an entity $e_i$ and its context words (represented by $C_{e_i}$). The conditional probability $p(w_o|e_i)$ is given by: $$ p(w_O|e_i) = \frac{exp({v^{'}_{e_i}}^T v_{w_O})}{\sum_{w \in \mathcal{W}} exp({v^{'}_{e_i}}^T v_{w})}$$ \item \textbf{Entity-Entity co-occurrence model}: The entity-entity co-occurrence model learns to predict incoming links of an entity (denoted by $C_e$) given an entity $e$. $$ \mathcal{L}_{ee} =\sum_{e_i \in E}\sum_{e_o\in C_{e_i};e_i\neq e_o}\textrm{log}\;p(e_o|e_i)$$ $$ p(e_O|e_i) = \frac{exp({v^{'}_{e_i}}^T v_{e_O})}{\sum_{e \in \mathcal{E}} exp({v^{'}_{e_i}}^T v_{e})}$$ \end{itemize} In practice, the probabilities involved in the skip-gram model are estimated using negative sampling \cite{mikolov2013distributed}. The overall objective is the sum of the three objectives for each type of co-occurrence. $$ \mathcal{L}_{SG} = \mathcal{L}_{ww} + \mathcal{L}_{we} + \mathcal{L}_{ee}$$ \subsection{Alignment methods} We align the entity pairs in KB and text corpus using a set of seed entity pairs, which are obtained from a mapping between Wikidata and Wikipedia. This mapping is constructed from the metadata associated with the Wikidata entities. The set of entities present in the TransE model and the skip-gram model is denoted by $\mathcal{E}_{TE}$ and $\mathcal{E}_{SG}$ respectively. \begin{enumerate}[label=(\alph*)] \item \textbf{Alignment using same embedding}: In this approach, we use the same embedding for the shared entities in the KB and text corpus. There is no separate alignment loss for this method. \item \textbf{Alignment using Projection}: Inspired by the multilingual word embedding approaches \cite{mikolov2013exploiting, faruqui2014improving} which use a linear transformation to map word embeddings from one space to another, we use an affine transformation from the skip-gram vector space to the TransE vector space to align the entity representations. The alignment loss is calculated as a squared L2 norm between the transformed skip-gram entity embeddings and the corresponding TransE entity embeddings. The vectors $\bm{e}_{TE}$ and $\bm{e}_{SG}$ denote the TransE and skip-gram versions of embeddings of the entity $\bm{e}$ respectively. \begin{equation*} \begin{aligned}[b] &\mathcal{L}_{align} =\\ &\sum_{\bm{e} \in \mathcal{E}_{SG}\cap \mathcal{E}_{TE}}\norm{(\bm{W} \bm{e}_{SG} + \bm{b}) - \bm{e}_{TE}}_2^{2} \end{aligned} \end{equation*} \item \textbf{Alignment using Entity Names}: In this alignment technique inspired by \citet{wang2014knowledge}, for a particular triple $(h, r, t)$ in the KB, if an equivalent entity $e_h$ exists in the text corpus, we add an additional triple $(e_h, r, t)$ to the KB. Similarly, if an equivalent entity $e_t$ also exists for the entity $t$, we add the triples $(h, r, e_t)$ and $(e_h, r, e_t)$ to the KB. The term ``name graph'' is used to denote this subgraph of additional triples. \begin{equation*} \begin{aligned}[b] &\mathcal{L}_{align} =\\ &\sum_{(h, r, t)\; \in \textrm{ KB}} \mathbbm{1}_{[h \in \mathcal{E}_{SG} \land t \in \mathcal{E}_{SG}]} d_r(\bm{w}_h, \bm{w}_t)+ \\ &\mathbbm{1}_{[t \in \mathcal{E}_{SG}]}d_r(\bm{h}, \bm{w}_t) +\mathbbm{1}_{[h \in \mathcal{E}_{SG}]}d_r(\bm{w}_h, \bm{t}) \end{aligned} \end{equation*} \item \textbf{Alignment using Wikipedia Anchors} This alignment technique is motivated by a similar technique proposed in \citet{wang2014knowledge}. Here, we introduce an alignment loss term in which for word-entity co-occurrences, we substitute the textual entity embedding by its KB counterpart in the skip-gram objective. Let $\bm{e}^i_{te}$ denote the embedding of the KB entity equivalent to the textual entity $e_i$. \begin{equation*} \begin{aligned}[b] &\mathcal{L}_{align} =\\ &\sum_{(e_i, C_{e_i})\in \mathcal{A}}\sum_{w_o\in C_{e_i}} \textrm{log}\;\sigma(exp( {\bm{e}^i_{te}}^T {v_{w_O}}))+\\ &\sum_{i=1}^k \mathbb{E}_{w_i \sim P_n(\mathcal{W})} [\textrm{log}\;\sigma(-exp({\bm{e}^i_{te}}^T {v_{w_i}}))] \end{aligned} \end{equation*} Here, $P_n(\mathcal{W})$ denotes the noise distribution over words and $k$ is the number of negative samples. \end{enumerate} The final objective for training these models becomes $$ \mathcal{L} = \mathcal{L}_{KB} + \mathcal{L}_{SG} + \lambda \mathcal{L}_{align}$$ Here, $\lambda$ denotes the balance parameter which controls the extent of influence of alignment on the embeddings of each of the individual vector spaces. An illustration of the different alignment methods used in our study is given in Figure~\ref{fig:alignment_fig}.
{'timestamp': '2021-06-04T02:10:23', 'yymm': '2106', 'arxiv_id': '2106.01586', 'language': 'en', 'url': 'https://arxiv.org/abs/2106.01586'}
arxiv
\section*{Acknowledgments} We are grateful to Tapan Chugh, Kunal Dahiya, Max Horton, Sewoong Oh, Mohammad Rastegari, Ludwig Schmidt and members of RAIVN Lab for helpful discussions and feedback. AK would also like to thank Soumen Chakrabarti and Manik Varma for sowing the seeds of this idea in his initial research days. Sham Kakade acknowledges funding from NSF Awards CCF-1703574. Ali Farhadi acknowledges funding from the NSF awards IIS 1652052, IIS 1703166, DARPA N66001-19-2-4031, W911NF-15-1-0543 and gifts from Allen Institute for Artificial Intelligence. \section{\ensuremath{{\rm LLC}}\xspace Decoding Schemes for Classification \& Binarization Function} \label{sec:alg} \begin{algorithm}[ht] \caption{Inference using Exact Decoding (ED)} \label{alg:ed} \begin{algorithmic}[1] \Require $x\in{\cal X}$, $F(\, \cdot \,; \theta_F)$, $\mathbf{C}$ and $\mathbf{P}$ \Ensure $\ell^*\subseteq [L]$ \State $g(x) \gets B(\mathbf{P}\cdot F(x;\theta_F))$ \State $\ell^* \gets \left\lbrace \ell\in[L] \colon B(\mathbf{C}_\ell) = g(x) \right\rbrace$ \end{algorithmic} \end{algorithm} \begin{algorithm}[ht] \caption{Inference using Minimum Hamming Decoding (MHD)} \label{alg:mhd} \begin{algorithmic}[1] \Require $x\in{\cal X}$, $F(\, \cdot \,; \theta_F)$, $\mathbf{C}$ and $\mathbf{P}$ \Ensure $\ell^* \subseteq [L]$\ \ ($\ell^*\neq \emptyset$) \State $g(x) \gets B(\mathbf{P}\cdot F(x;\theta_F))$ \State $\ell^* \gets \mathop{\arg\min}_{\ell\in[L]} \frac{1}{2}\lVert B(\mathbf{C}_\ell) - g(x) \rVert_1$ \end{algorithmic} \end{algorithm} \begin{algorithm}[!ht] \caption{PyTorch code for Binarization $B(\cdot)$ function with straight-through-estimator (STE).} \label{alg:code} \definecolor{codeblue}{rgb}{0.25,0.5,0.5} \definecolor{codeblue2}{rgb}{0,0,1} \lstset{ backgroundcolor=\color{white}, basicstyle=\fontsize{9pt}{9pt}\ttfamily\selectfont, columns=fullflexible, breaklines=true, captionpos=b, commentstyle=\fontsize{7.2pt}{7.2pt}\color{codeblue}, keywordstyle=\fontsize{7.2pt}{7.2pt}\color{codeblue2}, } \begin{lstlisting}[language=python] class Binarize(autograd.Function): @staticmethod def forward(ctx, weight): out = weight.clone() # binarizing in the forward pass out[out >= 0] = 1 out[out < 0] = -1 return out @staticmethod def backward(ctx, g): # send the gradient g straight-through on the backward pass. return g, None \end{lstlisting} \end{algorithm} \section{Corrected MAP@1000 Metric for Image Retrieval.} \label{sec:metric} The reported MAP@1000 metric in~\citet{cao2017hashnet} has an error that results in the wrong estimation of retrieval performance of the learnt hash functions. This error has propagated into many of the follow-up papers rendering the MAP numbers presented in them non-transferable. Most of the papers after HashNet have continued to use the same metric resulting in this situation. The code for the metric is provided as part of the open-sourced codebase of HashNet\footnote{\url{https://github.com/thuml/HashNet/blob/master/caffe/models/predict/imagenet/predict_parallel.py\#L20}}. Everything until the computation of Precision@k ($k \in [1000]$) is correct. However, the reported metric computes AP@1000 as follows: $$\text{AP}@1000 = \frac{\sum_k P@k* rel(k)}{\sum_k rel(k)}$$ where $rel(k)$ is an indicator function if the sample at $k$-th position is relevant. ${\sum_k rel(k)}$ is the total number of relevant samples in all the 1000 retrieved samples. It should be noted that every query has around 1300 relevant documents and all of them can not be retrieved within 1000. MAP@k is just the mean of all the AP@k for all the queries. \input{TabsNFigs/hashing_error.tex} We explain the error using a simple example. Suppose a retrieval problem allows to retrieve 5 samples from a database where each query has 10 relevant samples. And for a given query, let us say method 1 gives retrieves the top-5 samples with the following relevance $\mathbf{[1, 0, 0, 0, 0]}$. And method 2 retrieved with samples with the relevance $\mathbf{[1, 0, 0, 1, 1]}$. Using the reported metric, method 1 has an AP@5 of $1.0$ (with just 1 relevant sample out of 5). But method 2 with 2 more relevant samples along with the top retrieved sample and has an AP@5 of 0.7. Even with an objectively better retrieval, method 2 has a lower AP@5 score than method 1. This results in an unfair evaluation of methods where methods with poor recall but a few precise retrievals will outperform methods that have both high precision and recall. The fix is simple and is just the use of standard MAP@k metric~\footnote{\url{http://sdsawtelle.github.io/blog/output/mean-average-precision-MAP-for-recommender-systems.html\#Average-Precision}}\footnote{\url{https://en.wikipedia.org/wiki/Evaluation_measures_(information_retrieval)\#Average_precision}}. $$\text{AP}@1000 = \frac{\sum_k P@k* rel(k)}{\min(\text{total relevant samples}, 1000)}.$$ The reason we need the ${\min(\text{total relevant samples}, 1000)}$ term in the denominator is that, with 1000 retrievals, it is impossible to retrieve all the 1300 relevant documents, so we divide by the most possible instead of all the relevant documents. With this metric, method 1 now has an AP@5 of 0.2, and method 2 has an AP@ 5 of 0.42 which reflects the reality of the retrieval. The only change needed is the replacement of ``relevant\_num'' in this line\footnote{\url{https://github.com/thuml/HashNet/blob/master/caffe/models/predict/imagenet/predict_parallel.py\#L42}} with ``R'' for the ImageNet-100 setting. Table~\ref{tab:hashing_error} presents a comparison of both MAP@1000 computed as reported, RMAP and corrected, CMAP for \ensuremath{{\rm LLC}}\xspace and HashNet. This shows a stark drop in the MAP values along with a non-intuitive correlation between RMAP and CMAP making off-the-shelf comparisons harder. Lastly, the MAP computation from HashNet also skipped the AP values when none of the relevant documents were retrieved (which is extremely rare at 1000 retrieval samples) but the AP score should have been 0 for that particular case. We fixed that in both RMAP and CMAP metrics reported here. \section{Hyperparameters} \label{sec:hparams} \paragraph{Classification} The first phase of the classification pipeline, ie., codebook learning, uses the hyperparameters - SGD+Momentum optimizer, batch size of 256, cosine learning rate routine, and 100 epochs - used in training the standard 1000-way linear classifier using a ResNet50~\citep{wortsman2019discovering,kusupati2020soft}. However, given the warm-starting of the second phase using the learnt backbone and the availability of the learnt codebook, the training routine of the second phase runs for about 25 epochs with a reduced learning rate of 0.01. \paragraph{Retrieval} As we start with pre-trained models for retrieval. We use the same hyper-parameters as the second phase of the classification pipeline except for the learning rate. We use a much learning rate of 0.01 for AlexNet and 0.1 for ResNet50. The second phase of learning instance codes uses a reduced learning rate of 0.005 and 0.01 for AlexNet and ResNet50 respectively. The rest of the hyperparameters and training mechanisms are the same as the standard ResNet50 training. \section{Quantitative Evaluation of Hierarchy \& More Visualizations} \label{sec:quant_hier} Quantitative evaluation of the discovered hierarchies is a hard problem because we can not directly compare ours to the original ImageNet hierarchy which is not binary unlike ours. However, one proxy way is to use the pair-wise inner-product heat map (see Figure~\ref{fig:heat}) of 2048 dimensional representation as the base and compare using row-wise (class-wise) ranking metrics like Spearman's rank correlation coefficient in which the learnt 20-bit codebook has a mean coefficient across all class of 0.3 compared to 0.005 of a random codebook. Lastly, the number of unique class codes (ideally should be equal to $L$) learnt as part of the codebook plays an important role as the code collapse leads to loss of information about multiple classes resulting in unclear decoding when required. \input{TabsNFigs/hierarchy_codebook.tex} \input{TabsNFigs/bit-viz.tex} It would be exciting to compare the discovered taxonomy to the original WordNet~\citep{miller1995wordnet} hierarchy based on which the ImageNet-1K was curated. However, the major roadblock comes when we realize that our discovered hierarchy is binary while WordNet is $k$-ary making fair comparison almost impossible. We also explored the idea of cost-sensitive metrics~\citep{deng2011hierarchical} based on hierarchy to evaluate the classification but fell short due to the same limitation of unfairness in comparing binary to $k$-ary. Lastly, we also wanted to see if the learnt bit codes/hyperplanes result in splitting the images by discovering (potentially interpretable) attributes as with previous works~\citep{rastegari2012attribute}. However, unlike previous works, which use simple features for encoding images, we learn a highly non-linear representation using deep neural networks. This resulted in learnt bit code hyperplanes that often split the images using highly non-linear, non-trivial, and non-interpretable attributes. Figure~\ref{fig:bit-splits} shows the images on either side of the hyperplane of the corresponding bit sorted by the confidence of being $+1$ or $-1$ (probability from the logistic function for binary classification). While, with deeper analysis and further visualization, we might be able to deduce what is being learnt, but at the surface level, without explicit learning with priors, the discovered attributes are non-interpretable affecting zero-shot and few-shot capabilities of \ensuremath{{\rm LLC}}\xspace based models. \section{Out-of-Distribution (OOD) Detection Experiments} \label{sec:ood_expts_app} OOD detection for a multi-class classification model can be achieved by simple baselines that set a threshold on a heuristic based on the prediction probabilities~\citep{hendrycks2016baseline}. For the classification models trained with ResNet50 on ImageNet-1K, we evaluate on two datasets which we consider as out-of-distribution to ImageNet-1K that has 50K samples as the in-distribution validation set. Our method uses a 20-bit classification model while the baselines use the pre-trained ResNet50 with linear classifier. ImageNet-750~\citep{wallingford2020overfitting} is a long-tailed dataset of 750 classes with about 69K samples. These 750 classes were sampled from ImageNet-22K~\citep{deng2009imagenet} ensuring no clash with the ImageNet-1K subset. All the instances in this dataset are OOD to a model trained on ImageNet-1K. MIT Places~\citep{zhou2014learning} dataset is aimed at scene recognition rather than object recognition, unlike ImageNet-1K. All the $\sim$18K samples in the validation set of Places365 were also treated as OOD to ImageNet-1K during this evaluation. \input{TabsNFigs/OOD_Results_noratio.tex} As mentioned in Section~\ref{sec:ood_expts}, \ensuremath{{\rm LLC}}\xspace based OOD detection looks at the encoded instance code and classifies a sample as OOD in case of a missing exact match in the learnt codebook. This does not require any OOD samples whatsoever apriori to the deployment. We consider two baselines: a) tuning of the threshold on the probability of maximum logit to maximize F1 score using a validation set with OOD examples~\citep{hendrycks2016baseline}, and b) setting a conservative threshold on the probability of maximum logit which is 1 standard deviation greater than the mean probability of the maximum logit using just 50 OOD examples. Note that the performance of the first baseline varies with i) the ratio of in distribution to OOD samples in the validation set that is being used for tuning the threshold, ii) the setup with a different validation to test out-of-distribution ratios. Our primary focus is on the setting where the validation set used for tuning thresholds is not representative of the test set. In this setting the in distribution samples are constant, all the 50K samples. We only vary the number of OOD samples while tuning the threshold. The final OOD performance using the F1 score was measured on a test set with all the 50K in distribution samples along with a random 10K samples from the OOD set (ImageNet-750 \& MIT Places). Figure~\ref{fig:OOD_noratio} captures the effectiveness of \ensuremath{{\rm LLC}}\xspace based OOD detection in the setting where validation is not representative of test. Our out-of-the-box OOD detection method is at least as effective as the baselines. Remarkably, the tuning of the threshold to maximize F1 using a validation set requires at least 3000 OOD samples to even get close to our method which requires {\em no samples}. The second setting is where the validation and test sets have the same number of OOD samples for a fixed in-distribution set. Here the validation and test phases have same number of re-sampled OOD instances. All the 50K in distribution samples are used for both validation and testing. Figure~\ref{fig:OOD_ratio} shows that \ensuremath{{\rm LLC}}\xspace based OOD detection is as competitive as the tuned threshold baseline~\citep{hendrycks2016baseline} which is optimizing F1 for the exact same ratios. These experiments help in arguing that \ensuremath{{\rm LLC}}\xspace based classification models have a strong, sample-efficient inherent OOD detection capability. which can be used for sequential learning, to detect and continuously add new classes, along with robustness. \input{TabsNFigs/OOD_Results_ratio.tex} \section{Applications} \label{sec:apps+exps} In this section, we discuss three applications of the learnt low-dimensional binary codes: 1) efficient multi-class classification (Section~\ref{sec:classification_expts}), 2) efficient retrieval (Section~\ref{sec:retrieval_expts}), and 3) out-of-the-box out-of-distribution (OOD) detection (Section~\ref{sec:ood_expts}). We also present ablation studies on codebook learning, feature separability and classification (Section~\ref{sec:ablations}). \subsection{Efficient Multi-class Classification} \label{sec:classification_expts} Recall that the proposed \ensuremath{{\rm LLC}}\xspace algorithm outputs a) the learnt class codes (codebook), $B(\mathbf{C})$ and b) an {\em encoder} that produces instance codes, $B(\mathbf{P}\cdot F(\mathbf{x};\theta_F))$ for $x$. We define a class codebook as a collection of $L$ binary vectors, one for each class in the dataset, that can then be used for classification of a test instance $x$. We can use several ``decoding" routines to classify an instance $x$, given its encoding and the learnt codebook. Below we discuss two decoding schemes that are diametrically opposite in terms of the inference cost. Also, note that the standard linear classification with real-valued representation and classifiers scale as $O(L)$ in terms of computational complexity and model size. \subsubsection{Decoding Schemes} \paragraph{Exact Decoding (ED).} Exact Decoding scheme expects the Hamming distance between the generated instance code, $B(\mathbf{P}F(\mathbf{x};\theta_F))$, and the ground truth class code, $B(\mathbf{C}_i)$ to be {\em exactly} $0$. That is, we can hash the class codes in a table, and then ED requires only a $O(1)$ hash-table lookup for a given instance. Consequently, the inference time for ED is nearly {\em independent} of $L$. Naturally, the decoding scheme is highly stringent and would misclassify an instance if the instance binary code and the ground truth code do not match in even a single {\em bit}. Surprisingly, this highly efficient decoding scheme still provides non-trivial accuracy (see Table~\ref{tab:classification_20bits} and Section~\ref{sec:class_exps}). \paragraph{Minimum Hamming Decoding (MHD).} Minimum Hamming Decoding is akin to the Maximum Dot Product used by standard linear classifiers. For an instance code, we evaluate the Hamming distance with all the $L$ class codes and output the class with the least Hamming distance. Note that the Hamming distance over binary codes can be computed using XOR operations that are implemented significantly more efficiently than the floating-point operations~\citep{rastegari2016xnor}. Even though, technically, computational complexity and model size of MHD scales as $O(L)$ but the real-world implementations should be an order of magnitude faster than standard classifiers. In fact, for large number of classes $L$, the efficiency of MHD can be further improved by using approximate nearest neighbour search~\citep{datar2004locality,bentley1990k,malkov2018efficient}. Appendix~\ref{sec:alg} has the mathematical presentation of the decoding schemes. See Section~\ref{sec:disc} for more discussion on potential decoding schemes. Also see Section~\ref{sec:ablations} for ablation studies about the two decoding schemes along with feature separability (linear vs Hamming). \subsubsection{Empirical Evaluation} \label{sec:class_exps} ImageNet-1K~\citep{russakovsky2015imagenet} is a widely used image classification dataset with 1000 hierarchical classes. Our classification experiments use ResNet50~\citep{he2016deep} and are trained using the $\sim$1.3M training images. Images were transformed \& augmented with standard procedures~\citep{kusupati2020soft,wortsman2019discovering}. All the implementations were in PyTorch~\citep{paszke2019pytorch} and experimented on a machine with 4 NVIDIA Titan X (Pascal) GPUs. When applied to ImageNet-1K, the first phase of \ensuremath{{\rm LLC}}\xspace, learnt a 20-bit codebook with 1000 unique class codes, i.e., every class has its own {\em distinct} binary code. We warm start the second phase of \ensuremath{{\rm LLC}}\xspace by the learnt ResNet50 backbone along with the $20$ dimensional projection layer. See Appendix~\ref{sec:hparams} for the hyperparameter values and other training details. A key feature of \ensuremath{{\rm LLC}}\xspace is that it jointly learns both the class codebook as well as instance codes. Several existing techniques decouple this learning process where the codebook is constructed separately and is then used to train the instance codes~\citep{ hsu2009multi,crammer2001algorithmic,allwein2000reducing,escalera2010error,akata2015label,weston2011wsabie}. We evaluate the advantage of the {\em joint} learning approach of \ensuremath{{\rm LLC}}\xspace by comparing its performance against three strong baselines: i) Random codebook of $20$-bits, ii) $20$-bit CCA codebook~\citep{akata2015label,weston2011wsabie,zhang2011multi} \& iii) $20$-bit SVD codebook. Previous works~\citep{hsu2009multi,crammer2001algorithmic,allwein2000reducing} argued that random codebooks are competitive to the ones constructed using side-information. $20$-bit CCA and SVD codebooks aim to capture the hierarchy that is amiss in the random codebook. The $20$-bit SVD codebook is built using the SVD of $2048$ dimensional linear classifiers (for each class) in the pre-trained ResNet50, and binarizing it. $20$-bit CCA codebook is the binarized version of the transformed label embedding projected on to $20$ components learnt using CCA between 2048 dimensional representations of 50K samples from the ImageNet train set and their one-hot label embeddings. Despite being able to capture the hierarchy information, both $20$-bit CCA/SVD codebooks suffer from clashes reducing their overall effectiveness. Next, using the baselines codebooks and the corresponding learnt instance codes, we compute class predictions for each test instance using the Exact Decoding (ED) \& Minimum Hamming Decoding (MHD) schemes mentioned in the previous section. We evaluate all the methods using top-$1$ accuracy on the ImageNet-1K validation set. Baseline ResNet50 architecture represents the maximum accuracy we can hope to achieve using binarized instance$+$class codes. Note that this baseline classifier requires $O(L)$ computation over 16-bit real numbers, and achieves Top-$1$ accuracy of $77\%$. \input{TabsNFigs/Classification_Results.tex} Table~\ref{tab:classification_20bits} compares the accuracy of \ensuremath{{\rm LLC}}\xspace (with $20$-bit codebook) against baseline codebooks mentioned above. Note that MHD with \ensuremath{{\rm LLC}}\xspace codebook is $74.5\%$ accurate, i.e., despite using only $20$-dimensional {\em binary} representation it is only about $2.5\%$ less accurate than standard ResNet50 that uses 2048 dimensional real-valued representation. Furthermore, we observe that compared to standard codebooks like SVD, our jointly learnt codebook is 5\% more accurate. Interestingly, Exact Decoding (ED) -- which is $O(1)$ inference scheme -- with \ensuremath{{\rm LLC}}\xspace codebook is nearly as accurate as the SVD codebook with MHD scheme and is about 12\% more accurate than the CCA codebook with ED scheme. Naturally, codebook length/dimensionality plays a critical role in classification accuracy; see Section~\ref{sec:ablations} for a detailed ablative study on this aspect. Finally, the gains in efficiency should be even more compelling for problems with millions of classes~\citep{varma2019extreme}. \subsection{Efficient Retrieval} \label{sec:retrieval_expts} The goal in retrieval is to find instances from a database that are most similar to a given {\em query}. Traditional retrieval approaches, use a {\em fixed metric} to retrieve "similar points", with data structures like LSH for efficient retrieval. Recent progress in Deep Supervised Hashing (DSH)~\citep{liu2016deep} offer significantly more compelling solutions by learning the hashing function itself. That is, DSH aims to learn binary codes for each instance s.t. a pair of instances are embedded closely iff they belong to the same class, and then learns the hashing function end-to-end using a small train set. As \ensuremath{{\rm LLC}}\xspace also learns instance codes to reflect class membership, we can directly use our learnt encoder as a hashing function for given instances. For each query, the most relevant samples from the database are retrieved based on the minimum Hamming distance. Similar to the decoding schemes in classification, the retrieval can be optimized using approximate nearest neighbor search. Finally, the efficiency gains provided by using bits instead of real numbers should enable deployment of \ensuremath{{\rm LLC}}\xspace based retrieval for efficient high recall portions of retrieval pipelines. \subsubsection{Empirical Evaluation} Following DSH literature, we evaluate hashing-based image retrieval on ImageNet-100, a benchmark dataset created by~\citet{cao2017hashnet}. ImageNet-100 has 100 classes randomly sampled from ImageNet-1K. All the validation images of these classes are used as query images, all the training images ($\sim$ 1300 per class) of these 100 classes are used as database images. Finally, 130 samples per class from the database are used as the training set for learning binary codes or hashing functions. We compare against HashNet~\citep{cao2017hashnet} and Greedy Hash~\citep{su2018greedy} for image retrieval using learnt instance codes. HashNet learns the bit representations of instances using a pairwise optimization with positive and negative instance pairs. HashNet is a representative baseline for an alternative way of learning binary instance codes compared to \ensuremath{{\rm LLC}}\xspace. On the other hand, Greedy Hash learns only the instance codes using straight-through-estimator via the classification task. Note that \ensuremath{{\rm LLC}}\xspace learns both class codes as well as instance codes differentiating it from Greedy Hash style methods. Learnt instance codes are a byproduct of efficient classification as opposed to baselines that optimize for them. We use the Mean Average Precision (MAP@1000) metric for evaluation. The MAP@1000 calculation code of HashNet~\citep{cao2017hashnet} is erroneous and has propagated to several papers in the literature. We use the corrected version, hence the accuracy numbers are different from the original paper. Please see Appendix~\ref{sec:metric} for the corrected version, the changes required along with an example and a brief discussion. We used the publicly available pre-trained HashNet models~\citep{hashnetcode} and Greedy Hash~\citep{su2018greedy} code to recompute the MAP@1000. Following HashNet~\citep{cao2017hashnet}, we use AlexNet~\citep{krizhevsky2012imagenet} as the backbone and warm-start it with a pre-trained model on ImageNet-1K. We add a projection layer to the backbone and learn the instance and class codes. We also report retrieval numbers with ResNet50~\citep{he2016deep} and compare \ensuremath{{\rm LLC}}\xspace based retrieval numbers to learnt real-valued representations. Please see Appendix~\ref{sec:hparams} for the training details and hyperparameters of efficient retrieval pipelines. \input{TabsNFigs/Hashing_Results.tex} Table~\ref{tab:hashing_alex} shows the performance (evaluated using MAP@1000) for HashNet, Greedy Hash, and \ensuremath{{\rm LLC}}\xspace across various code lengths. \ensuremath{{\rm LLC}}\xspace outperforms HashNet across all code lengths (16 -- 64) by at least 4.79\% on MAP@1000. \ensuremath{{\rm LLC}}\xspace is also better than Greedy Hash across all the bit lengths. \ensuremath{{\rm LLC}}\xspace also outperforms $16$-bit HashNet by $2\%$ \& $15\%$ using only $10$ \& $16$ bits respectively. Finally, $32$-bit \ensuremath{{\rm LLC}}\xspace comfortably outperforms both $48$ \& $64$-bit HashNet showcasing the effectiveness of our learnt tight bit codes. Note that \ensuremath{{\rm LLC}}\xspace, learning both instance and class codes, is effective in retrieval even though it was designed for classification. We repeat the retrieval experiments with ResNet50. Table~\ref{tab:hashing_resnet} shows the MAP@1000 for \ensuremath{{\rm LLC}}\xspace with $10$ and $64$ bits along with the same dimensional real-valued representations. The $10$-bit \ensuremath{{\rm LLC}}\xspace is only 2\% lower than $10$ dimensional real-valued representation even though theoretically, the cost associated with 10-bit \ensuremath{{\rm LLC}}\xspace based retrieval is about $256\times$ less than $10$ dimensional real representations. The $64$ bit and $10$ bit \ensuremath{{\rm LLC}}\xspace outperforms $10$ and $8$ dimensional real-valued representations respectively at a much cheaper retrieval cost, at least by an order of magnitude. More discussion about the use of binary codes for retrieval at a large scale can be found in Section~\ref{sec:disc}. Finally, $10$-bit \ensuremath{{\rm LLC}}\xspace with ResNet50 outperforms the best performing AlexNet based models for the same task, suggesting ResNet50 is a more appropriate architecture for benchmarking DSH literature. \subsection{Out-of-Distribution (OOD) Detection} \label{sec:ood_expts} For a multi-class classifier, detecting an OOD sample is very important for robustness~\citep{hendrycks2016baseline} and sequential learning~\citep{wallingford2020overfitting}. Multi-class classifiers are augmented with OOD detection capability by setting a threshold on heuristics like maximum logit which is tuned using a validation set. We focus on the scenario where the ratio of in-distribution to out-of-distribution samples in the validation set is not representative of the deployment. This throws off the methods that try to maximize metrics, F1, using a validation set. Our learnt class codebook from \ensuremath{{\rm LLC}}\xspace comes with over-provisioning (for ease of optimization) resulting in unassigned codes. These unassigned codes can be treated as OOD out-of-the-box with no tuning whatsoever. That is, we classify an instance as OOD if its instance code does not match {\em exactly} with the code of a class in our learnt codebook. Appendix~\ref{sec:ood_expts_app} discusses the OOD detection experiments on ImageNet-750~\citep{wallingford2020overfitting} \& MIT Places~\citep{zhou2014learning}. At a high level, \ensuremath{{\rm LLC}}\xspace based out-of-the-box OOD detection (with a learnt 20-bit codebook on ImageNet-1K) achieves nearly the same OOD detection accuracy as a baseline~\citep{hendrycks2016baseline} that tries to maximize F1 using a validation set. We would like to stress that while such a method needs $\approx 3000$ points in the validation set, our method requires {\em no} samples, which is critical in several practical settings. \subsection{Ablation Studies} \label{sec:ablations} \paragraph{Classification Accuracy vs Number of Bits.} Table~\ref{tab:classification_variousbits} shows the trade-off in classification accuracy with the variation in the length of the learnt codebook for ImageNet-1K. \ensuremath{{\rm LLC}}\xspace learns a $15$-bit codebook with only 990 unique codes leading to a loss of accuracy due to code collapse in both ED and MHD schemes ($1.62\%$ \& $3.54\%$ compared to 20-bit codebook respectively). An interesting observation is that the ED accuracy gradually goes down after 20-bits while the MHD accuracy keeps on increasing. The phenomenon of increasing accuracy with MHD is probably due to the increase in the capacity of both instance and class codes. However, the decrease in ED accuracy after 20-bits can be explained through the hardness in exactly predicting every bit in the instance code to match the ground truth class code. Our classification model with 20-bits on average gets $19.2$ bits correct but the model with 30-bits only gets $28.5$ bits right. This increase in uncertainty coupled with the stringent ED scheme leads to a slight dip in accuracy as the code length increases. However, this also provides us with a path for more accurate decoding schemes while being efficient as discussed in Section~\ref{sec:disc}. \paragraph{Classification Accuracy vs Faster Codebook Learning.} Codebook learning phase of \ensuremath{{\rm LLC}}\xspace is expensive, this motivated us to speed up codebook learning at a minimal loss in accuracy. One way is to warm-start the codebook using the ones built with SVD/CCA (see Section~\ref{sec:classification_expts}). While these codebooks suffer from code collapse, with further training, they start to learn 1000 unique codes quickly. Using these final codebooks gets to a comparable ($1\%$ drop) accuracy as the $20$-bit learnt \ensuremath{{\rm LLC}}\xspace codebook but at a relatively cheaper training. Another option is to use only a portion of the data and a much smaller network to learn the codebook. We sampled 50K training images and use a MobileNetV1~\citep{howard2017mobilenets} (which has about $6\times$ less parameters and compute than ResNet50) to learn a 20-bit codebook which gets to ED and MHD accuracy of $66.62\%$ \& $72.55\%$ which is only $2\%$ lower than the end-to-end learnt codebook but at a fraction of the training cost (3 hrs vs 2 days). \paragraph{Linear vs Hamming Separability.} Fitting a deep neural network to the learnt codebook for classification results in warping of the feature space considerably. The final classification space is a hypercube with the vertices being apart by Hamming distance of 1. To verify linear separability, we take the learnt, frozen ResNet50 trained for the 20-bit classification problem and fit a linear classifier on top of the 2048 dimensional features. Linear classifier quickly reaches a top-$1$ accuracy of $75.51\%$. The opposite does not seem to be true. We extract and freeze the backbone of a pre-trained ResNet50 and train a projection layer to fit the $20$-bit learnt codebook. This gets to top-$1$ accuracy of only about $21\%$ with the ED scheme. However, we also observed that unfreezing and finetuning the last 3 layers of the backbone recovers the top-$1$ ED accuracy to roughly $68\%$. These experiments show 1) Hamming separability inherently enables linear separability, 2) Linear separability does not imply Hamming separability \& 3) with enough overparameterization, linearly separable space can be warped to support Hamming separability. Hamming separability automatically provides linear separability with increased accuracy of $\sim 1\%$ over the MHD scheme which allows for an option for using a more powerful yet simple classifier, in case of accuracy requirements. \paragraph{Independent vs Nested Codebook Learning.} Consider a scenario with varied computational budgets for classification. We could either train independent $k$-bit models (eg., $k=20,25,30$) and use them according to the budget, or we could learn a single nested codebook-based model that can be readily adapted to any of these settings. While training a codebook of larger bit length like $k=30$, we can ensure that the first $m$-bits, $m<k$, also form a codebook at minimal additional cost. We were able to stably train a $30$-bit codebook and also extract $20$, $25$-bit codebooks from it all of which are as accurate as independently trained codebooks. These nested codebooks have the potential to be used based on the computational resource availability for efficient classification without having to retrain. \section*{Checklist} \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{sec:disc}.} \item Did you discuss any potential negative societal impacts of your work? \answerNA{As with all the efficient machine learning work, this work has both pros and cons. We believe that making ML models affordably available will help in a better feedback loop overall.} \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? \answerNA{} \item Did you include complete proofs of all theoretical results? \answerNA{} \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)? \answerYes{See supplemental material. All the code and models will be open sourced.} \item Did you specify all the training details (e.g., data splits, hyperparameters, how they were chosen)? \answerYes{See Section~\ref{sec:apps+exps} and Appendix~\ref{sec:hparams}.} \item Did you report error bars (e.g., with respect to the random seed after running experiments multiple times)? \answerNo{We evaluated our method on ImageNet which is computationally expensive to run (3 days per experiment).} \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)? \answerYes{See Section~\ref{sec:apps+exps}.} \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? \answerYes{} \item Did you mention the license of the assets? \answerNo{All the datasets and code used are public and are under MIT, BSD or CC licenses.} \item Did you include any new assets either in the supplemental material or as a URL? \answerNo{} \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} \label{sec:conc} \section{Discussion and Conclusions} \label{sec:disc} We designed \ensuremath{{\rm LLC}}\xspace to learn low-dimensional binary codes for instances as well as classes, and utilized them in applications like efficient classification, retrieval, OOD detection. A key finding is that combining class code learning with ECOC framework to learn instance code leads to a stable training system that can accurately capture the semantics of the class data despite just $20$-dimensional code. Traditionally, methods like HashNet, KLSH~\cite{kulis2009kernelized} attempt to learn hashing function using pairwise loss functions by embedding instances such that points from the same class are embedded closely and points from different classes are far. But such formulations are hard to optimize, due to the risk of embedding collapse. We observe that \ensuremath{{\rm LLC}}\xspace by using instance-wise formulation can train stably with significantly higher performance. Another fascinating observation is that while architectures like ResNet50 have large intermediate ($2048$ dimensional real) representations, they can be compressed to just $20$ bits without significant loss in accuracy! Even though quantization~\cite{rastegari2016xnor} literature demonstrates strong compression of representations, we believe such stark compression has been elusive so far and is worth further exploration from the efficient inference viewpoint. \paragraph{Limitations.} Our visualization (see Figure~\ref{fig:bit-splits} in Appendix~\ref{sec:quant_hier}) indicates that each bit does not correspond to some easily interpretable attributes, unlike DBC~\citep{rastegari2012attribute}. We believe incorporating priors with weak supervision as well as cross-modal learning could help \ensuremath{{\rm LLC}}\xspace get past this limitation. ED and MHD schemes are on two ends of the computation vs accuracy spectrum and do not transition smoothly. Designing decoding schemes that can compromise between these two extreme decoding schemes might be able to address this limitation. Strong encoders are needed to warp the feature space to ensure Hamming separability. For example, using a $20$-bit learnt codebook with ED scheme, ResNet50 gets to $68.8\%$ top-$1$ accuracy whereas MobileNetV1 can only reach $53.23\%$. This also ties into the argument that classification is a trade-off between encoder and decoder costs. Making decoders efficient and cheap, puts the burden on encoding the information in the right way and higher expressivity often helps in that cause. \paragraph{Future Work.} There are several exciting directions that we would like to explore. In principle, \ensuremath{{\rm LLC}}\xspace can easily incorporate side-information when needed with simple additional losses during training. The additional regularization losses can also help in incorporating natural constraints on the codebook~\citep{crammer2001algorithmic,allwein2000reducing} or can enable attribute-based class codes for interpretablity~\citep{farhadi2009describing,ferrari2007learning,lampert2013attribute} making them exciting directions to explore. \ensuremath{{\rm LLC}}\xspace algorithm can also be used to encode instances of multiple modalities like audio, visual, language to the same learnt low-dimensional binary space. This might help in effective cross-modal supervision along with retrieval among various other applications. \paragraph{Potential in Large-Scale Applications.} While our focus was on designing low-dimensional accurate binary codes, several studies~\citep{rastegari2016xnor,hubara2016binarized} have shown that efficiency afforded by bit-wise computation over floating-point computation can lead to almost an order of magnitude speed-up. Furthermore, as the number of classes increases, the learning of class codebooks helps in training representations in sublinear costs~\citep{cisse2013robust} along with sublinear inference (in $L$). We expect \ensuremath{{\rm LLC}}\xspace algorithm to have its efficiency benefits outweigh the accuracy drop for large multi-class/multi-label problems, like objection recognition using ImageNet-22K~\citep{deng2009imagenet}, document tagging~\citep{varma2019extreme,prabhu2020extreme} and instance classification~\citep{weyand2020google}. The efficiency aspect of the binary codes has not been fully explored in this paper as the main computational bottleneck for ImageNet-1K classification is the deep neural network featurizer. Lastly, \ensuremath{{\rm LLC}}\xspace based efficient retrieval can be used for the initial high-recall shortlisting of a search pipeline, which is followed by high precision models operating on more expressive yet expensive embeddings. We leave practical demonstration of such a system at web-scale for future work. \section{Introduction} \label{sec:intro} Embedding data in low-dimensional binary space is a long-standing machine learning problem~\cite{wang2015learning}. The problem has received a lot of interest in the computer vision (CV) domain, where the goal is to find binary codes that capture the key semantics of the image, like, objects present in the image or interpretable attributes. Section~\ref{sec:rw} covers the literature on learning binary codes and their applications. In addition to learning semantically meaningful representations of the instances, low-dimensional binary codes allow efficiency in a variety of large-scale machine learning (ML) applications. Low-dimensional codes are crucial in extreme classification with millions of classes~\citep{bhatia2015sparse, jain2019slice, dahiya2021deepxml} and also critical in efficient large-scale retrieval settings~\citep{liu2016deep,datar2004locality,weyand2020google}. Compressing information into binary codes is challenging due to its highly non-smooth nature while requiring the preservation of relevant information in an instance/class. This might explain the lack of good classification accuracy for existing classification-based embedding techniques~\cite{hsu2009multi,cisse2013robust}. To address that, traditional methods often relied on side-information like attributes to construct class codes and then use that to learn the instance codes~\citep{deng2011hierarchical,akata2015label}. Learning binary embeddings can be posed in a variety of formulations like pairwise optimization~\cite{kulis2009fast} or unsupervised learning~\citep{carreira2015hashing,salakhutdinov2007learning}, in this work we focus on learning binary codes using a given labeled multi-class dataset, e.g., ImageNet-1K. This allows us to couple the representation (code) learning of both {\em instances} and {\em classes} thus enabling us to capture the underlying semantic structure efficiently to assist in downstream tasks like classification, retrieval etc. We propose \ensuremath{{\rm LLC}}\xspace, a method to learn {\em both} class and instance codes via the standard classification task and its setup {\em without any side-information}. Our Learning Low-dimensional binary Codes (\ensuremath{{\rm LLC}}\xspace) technique, formulates the embedding (code) learning problem as that of learning a low-dimensional binary embedding of a standard deep neural ``backbone''. Instead of directly training for the low-dimensional binary instance codes, we propose a two-phase approach. In the first phase, \ensuremath{{\rm LLC}}\xspace learns low-dimensional ($k$-bit) binary codes for classes that capture semantic information through a surrogate classification task. Then in the second phase, \ensuremath{{\rm LLC}}\xspace uses these learnt class codes as an efficient alternative to learning instance codes in sub-linear cost (in the number of classes, $L$) using the Error-Correcting Output Codes (ECOC) approach~\citep{dietterich1994solving}. This two-phase pipeline helps in the effective distillation of required semantic similarity between instances through the learnt class codes. For example, on ImageNet-1K with ResNet50, \ensuremath{{\rm LLC}}\xspace is able to learn tight $20$-bit codes that can be used for {\em efficient classification} and achieve $74.5\%$ accuracy compared to the standard baseline $77\%$ on ImageNet-1K (Section~\ref{sec:classification_expts}). Furthermore, we observe that the learnt $20$-bit class codes capture intuitive taxonomy over classes (Figure~\ref{fig:heir}) while the instance codes retain the distilled class similarity information useful in efficient retrieval and OOD detection. {\bf Retrieval.} To further study, the effectiveness of our learnt binary codes, we apply them to hashing-based efficient retrieval, where the goal is to retrieve a large number of similar instances with the same class label in top retrieved samples. Deep supervised hashing is a widely studied problem with several recent results~\cite{cao2017hashnet,su2018greedy} which are designed {\em specifically} for the learnt hashing-based retrieval. Interestingly, our learnt instance codes through the \ensuremath{{\rm LLC}}\xspace routine provide strikingly better performance while not being learnt explicitly for hashing. For eg., using AlexNet, with just $32$-bit codes we are can provide $5.4\%$ more accurate retrieval than HashNet's $64$-bit codes on ImageNet-100 (Section~\ref{sec:retrieval_expts}). {\bf OOD Detection.} We similarly apply \ensuremath{{\rm LLC}}\xspace based learnt binary codes to detect OOD instances~\citep{hendrycks2016baseline}. We adopt a simple approach based on our binary codes: if an instance is not within a Hamming distance of $1$ to any class codes, we classify it as OOD. That is, we do not fine-tune our OOD detector for the new domain, which is critical in practical settings. In contrast, baseline techniques for OOD detection require a few samples (eg., $\approx3000$ for ImageNet-750) from the OOD domain to fine-tune thresholds, while we require {\em no} samples yet reaching similar OOD detection (Section~\ref{sec:ood_expts}). In this work, we make the following key contributions: \begin{itemize}[leftmargin=*]\vspace{-1mm} \itemsep 0pt \topsep 0pt \parskip 2pt \item \ensuremath{{\rm LLC}}\xspace method to learn semantically-rich low-dimensional binary codes for both classes \& instances. \item Show that the learnt codes enable accurate \& efficient classification: ImageNet-1K with $20$-bits. \item Apply \ensuremath{{\rm LLC}}\xspace to image retrieval task, and demonstrate that it comfortably outperforms the instance code learning methods for hashing-based retrieval on ImageNet-100. \item Finally, use codes from \ensuremath{{\rm LLC}}\xspace for strong \& sample efficient OOD detection in practical settings. \end{itemize} \section{Learning Low-dimensional Binary Codes} \label{sec:llc} The goal is to learn a binary embedding (code) function $g\colon{\mathcal{X}} \to \{-1,1\}^k$ where $\mathcal{X}$ is the input domain and $k$ is the dimensionality of the code. We focus on learning embeddings using a labelled multi-class data~\citep{hsu2009multi}. That is, suppose we are given a labelled dataset $\mathcal{D}=\{(x_1, y_1), \ldots, (x_n,y_n)\}$ where $x_i\in \mathcal{X}$ is an input point and $y_i \in [L]$ is the label of $x_i$ for all $i\in[n]$. Then, the goal is to learn an instance embedding function $g\colon {\cal X}\to \{+1,-1\}^k$ {\em and} class embeddings $h_q\in\{+1,-1\}^k$ for all $q\in[L]$ such that $g(x_i) = h_{y_i}$ and $g(x_i) = g(x_j)$ if and only if $y_i=y_j$. Intuitively, for large-scale datasets, $g(x)$ and $h_q$ should capture key semantic information to provide accurate classification, thus allowing their use in application domains like retrieval or OOD detection. Note that while we present our technique for learning embeddings using multi-class datasets, it applies more generally to multi-labeled datasets as well. \paragraph{Instance and Class Code Parameterization.} For learning such embedding function, we assume access to a deep neural architecture $F(\, \cdot\, ;\theta_F)\colon \mathcal{X} \rightarrow \mathbb{R}^d$ that maps the input $x\in {\cal X}$ to a $d$-dimensional real-valued representation. $\theta_F$ is a learnable parameterization of the network; we drop $\theta_F$ from $F$ wherever the meaning is clear from the context. For example, ResNet50 is one such network that encodes $224\times 224$ RGB images into $d=2048$ dimensions. Now, given a network $F$ and $x\in {\cal X}$, we formulate embedding function of $x$ and the corresponding multiclass prediction scores $\hat{y}\in \mathbb{Z}^L$ as: \begin{equation} \label{eq:embedx} g(x) \coloneqq B\left(\mathbf{P}\cdot F(x; \theta_F)\right), \quad \hat{y} \coloneqq B(\mathbf{C}) \cdot g(x)\ , \end{equation} where $\mathbf{P}\in \mathbb{R}^{k\times d}$ maps $F(x)$ into $k$-dimensions and $B(a)=\mathrm{sign}(a)\in\{+1, -1\}$ is the standard binarization/sign operator applied elementwise (with the assumption $\mathrm{sign}(0)=+1$). Finally, $\mathbf{C} \in \mathbb{R}^{L\times k}$, and $\hat{y} = B({\mathbf{C}})\cdot g(x)$ represents the scores of each class for an input $x$. Note that for a class $\ell\in[L]$, $B(\mathbf{C}_\ell)$ (where $\mathbf{C}_\ell$ represents the $\ell$-th row of $\mathbf{C}$) is the learnt binary class embedding (code) of class $\ell\in [L]$, and $g(x)=B(\mathbf{P}\cdot F(x; \theta_F))$ is the learnt instance embedding (code) of instance $x$. Note that~\eqref{eq:embedx} is a general purpose formulation for the problem of learning class and instance codes. \subsection{The \ensuremath{{\rm LLC}}\xspace Method} \paragraph{Phase 1: \em{Codebook Learning} -- $B(\mathbf{C})$.} Given labelled examples ${\cal D}$, we use standard empirical risk minimization to learn a multi-class classifier, i.e., we solve \begin{equation} \label{eq:phase1} \min_{\mathbf{C}, \mathbf{P}, \theta_F} \sum_{(x_i,y_i)\in {\cal D}} {\cal L}\left(B(\mathbf{C}) \cdot (\mathbf{P}\cdot F(x_i; \theta_F))\ ;\ y_i\right) \ , \end{equation} where ${\cal L}\colon \mathbb{R}^L\times [L] \to \mathbb{R}_+$ is the standard multi-class softmax cross-entropy loss function. This is a standard optimization problem that can be solved using standard gradient descent methods or other sub-gradient based optimizers. However, one challenge is that $B(\mathbf{C})$ is a binary matrix and $B$ is a binary function, so the gradients are $0$ almost everywhere. Instead, we use the Straight-Through Estimator (STE)~\citep{bengio2013estimating} technique popular in binary neural networks domain~\citep{rastegari2016xnor}, to optimize for $\mathbf{C}$ through the binarization. Intuitively, STE uses binarization/sign function in the forward pass, but in the backpropagation phase, it allows the gradients to flow straight-through as if it were real-valued. The codebook, $B(\mathbf{C})$ refers to the collection of $k$-bit class codes learnt in this process. For ImageNet-1K, we learnt unique binary codes, $B(\mathbf{C}_\ell)$, for every class $\ell\in[L]$ of the 1000 classes using only $20$-bits, only twice the information-theoretic limit. As with the class representations from a linear classifier, these class codes do capture intrinsically important features that help in discovering intuitive taxonomy over classes (Section~\ref{sec:hierarchy}) among various applications (Section~\ref{sec:apps+exps}). \paragraph{Phase 2: \em{Instance Code Learning} -- $B(\mathbf{P}\cdot F(x; \theta_F))$.} Several existing techniques model $\mathbf{C}$ and $\mathbf{P}$ in different ways to learn an embedding function similar to~\eqref{eq:embedx}. However, these methods often try to only learn instance codes and have challenges in maintaining high accuracy~\citep{cao2017hashnet,carreira2015hashing} in a variety of applications because optimization problem (\ref{eq:phase1}) is challenging and might lead to significantly sub-optimal classification error. For example, for ImageNet-1K classification with ResNet50, the accuracy for our trained model (20-bits) at this stage is $72.5\%$ compared to the standard $77\%$. To remedy this, we further optimize our embeddings using the ECOC framework~\citep{dietterich1994solving} for multi-class classification, which essentially transforms the multi-class problem into a multi-label problem, which in turn is $k$ independent binary classification problems. That is, we use the $k$-bit codes learnt for each class as the supervision to further train $F(\, \cdot\, ; \theta_F)$ and $\mathbf{P}$: \begin{equation}\label{eq:phase2} \min_{\theta_F, P} \sum_{(x_i,y_i)\in{\cal D}} \sum_{j=1}^k \textrm{BCE}\left(\sigma(\mathbf{P}_j\cdot F(x_i; \theta_F))\ ;\ \left(B(\mathbf{C}_{y_i,j})+1\right)/2\right), \end{equation} where $\sigma$ is the sigmoid/logistic function, $\textrm{BCE}$ is the binary cross-entropy loss between the $j$-th bit of instance $x_i$'s embedding, and the $j$-th bit extracted from the class embedding of it's label $y_i$ (the function $z\mapsto (z+1)/2$ is used to map $\{+1,-1\}$ to $\{1,0\}$ to make it a simple binary classification problem per each bit). We use gradient based optimization to learn $\theta_F$ and $\mathbf{P}$. As mentioned earlier, ECOC framework allows us to correct errors in classification. For example, with just $20$ bits on ImageNet-1K dataset, the method now achieves $74.5\%$ accuracy with ResNet50 backbone. The advantage of this two-phase pipeline where we start with a codebook learning for classes is that the cost of learning instances codes reduces to a bottleneck of $k$-dims ($\ll L$) instead of the usual $L$ . Furthermore, these learnt low-dimensional binary codes for both classes and instances help in large-scale applications via efficient classification and retrieval (see Section~\ref{sec:apps+exps}). Note that, unlike attribute-based methods~\citep{lampert2013attribute}, we do {\em not} require additional meta-data, but learn binary codes by only using the standard classification task. This also circumvents the potential instabilities of pairwise optimization in instance binary code learning which often leads to poor class codes due to codebook collapse. At the end of \ensuremath{{\rm LLC}}\xspace routine, we have learnt the instance codes, $B(\mathbf{P}\cdot F(x; \theta_F))$, and class codes, $B(\mathbf{C})$ to be used for downstream applications. Algorithm~\ref{alg:llc} presents \ensuremath{{\rm LLC}}\xspace in full. \input{TabsNFigs/llc_alg.tex} Overall, we present a simple yet scalable method to learn low-dimensional (exact) binary codes for both classes and instances which in turn could power multi-class classification with sub-linear costs (in terms of $L$) and efficient retrieval for large-scale applications. Using our method, we can consistently learn unique low-dimensional binary codes for all 1000 classes in ImageNet-1K using only $20$-bits (which is twice the information-theoretic limit of $\lceil\log_2 (1000)\rceil$). Next, we discuss the learnt codebook's intrinsic information about the classes and their structure. \subsection{Discovered Taxonomy and Visualizations} \label{sec:hierarchy} \input{TabsNFigs/hierarchy_learnt.tex} After learning the $20$-bit binary codebook for 1000 classes of ImageNet-1K, we used the class representation from $B(\mathbf{C})$ of the first 50 classes to discover an intuitive taxonomy through agglomerative clustering~\citep{murtagh2012algorithms}. Figure~\ref{fig:heir} shows the discovered hierarchy. This hierarchy effectively separates birds from amphibians; frogs and chickens are on extremes of the taxonomy and brings species with shared similarities closer (lizards \& crocodiles; marine life). While the taxonomy is not perfect, the $20$-bits do capture enough important information that can be used downstream. Figure~\ref{fig:heat} shows the pair-wise inner-product heat maps for all the 1000 classes using $20$-bits and $2048$-dimensional real representation; the comparison reveals that $20$-bits indeed highlights the same substructures as the higher dimensional real-valued embeddings. Appendix~\ref{sec:quant_hier} has a more detailed discussion about quantitatively evaluating the discovered hierarchy and more visualizations. \input{TabsNFigs/heatmap.tex} \section{Related Work} \label{sec:rw} Binary class codes were originally aimed at sub-linear training and prediction for multi-class classification. The Error-Correcting Output Codes (ECOC) framework~\citep{dietterich1994solving,allwein2000reducing,escalera2010error} reformulated multi-class classification as multi-label classification using $k$-bit codes per class (codebook). The learning of optimal codebook is NP-complete~\citep{crammer2001algorithmic} which lead to use of random codebooks~\citep{hsu2009multi,cisse2013robust} in traditional ML. However, there were a few codebook learning~\citep{bengio2010label,zhang2011multi,weston2011wsabie,bautista2016learning} and construction schemes using side-information from other modalities~\citep{akata2015label}. The lack of a strong learnable feature extractor often deterred the gains these codebooks provide for the classification and effective learning of instance codes. Attribute annotations can also help in constructing class codes~\citep{akata2015evaluation}. These binary codes are either explicitly annotated~\citep{farhadi2009describing} or discovered~\citep{rastegari2012attribute,ferrari2007learning}. Attributed-based learning also ties into leveraging the class codes for zero/few-shot learning~\citep{lampert2009learning,lampert2013attribute,akata2015label,norouzi2013zero} expecting some form of interpretability. Most methods that use class codes as supervision can produce instance codes~\citep{dietterich1994solving}. However, the standalone literature of instance codes comes from requirements in large-scale application like retrieval (hashing). In the past, most hashing techniques that created instance codes were based on random projections~\citep{datar2004locality,cisse2013robust,choromanska2016binary}, semantics~\citep{salakhutdinov2009semantic,deng2011hierarchical} or learnt through metric learning~\citep{kulis2009fast,kulis2009kernelized,norouzi2012hamming,kulis2009learning}, clustering~\citep{weiss2008spectral,salakhutdinov2007learning} and quantization~\citep{gong2012iterative}. Deep learning further helped in learning more accurate hashing functions to generate instance codes either in an unsupervised~\citep{carreira2015hashing,shen2018unsupervised} or supervised~\citep{liu2016deep,cao2017hashnet,su2018greedy,yuan2018relaxation} fashion. We refer to~\citep{luo2020survey,zhang2020survey,wang2015learning} for a more thorough review on deep hashing methods. Finally, embedding-based classification~\citep{cisse2013robust,yu2014large,bhatia2015sparse,Guo2019BreakingTG} enables joint low-dimensional representation learning for both classes and instances with an eye on sub-linear training and prediction costs. After distilling the key ideas from the literature, we aim to a) learn semantically rich low-dimensional representations for both classes and instances together, b) have these representations in the binary space, and c) do this with minimal dependence on side-information or metadata. \ensuremath{{\rm LLC}}\xspace, to the best of our knowledge - for the first time, jointly learns low-dimensional binary codes for both classes and instances using a surrogate classification task, without any side-information (Section~\ref{sec:llc}). The learnt class codes capture intrinsic information at the semantic level that helps in discovering an intuitive taxonomy over classes (Figure~\ref{fig:heir}). The learnt class codes then anchor the instance code learning which results in tight and accurate low-dimensional instance codes further used in retrieval (Section~\ref{sec:retrieval_expts}). Finally, both the learnt class and instance codes power extremely efficient yet accurate classification (Section~\ref{sec:classification_expts}) and out-of-distribution detection (Section~\ref{sec:ood_expts}).
{'timestamp': '2021-10-08T02:06:59', 'yymm': '2106', 'arxiv_id': '2106.01487', 'language': 'en', 'url': 'https://arxiv.org/abs/2106.01487'}
arxiv
\section{Introduction} In the clinical domain, the ability to conduct natural language inference (NLI) on unstructured, domain-specific texts such as patient notes, pathology reports, and scientific papers, plays a critical role in the development of predictive models and clinical decision support (CDS) systems. Considerable progress in domain-agnostic NLI has been facilitated by the development of large-scale, crowdworker-constructed datasets, including the Stanford Natural Language Inference corpus (SNLI), and the Multi-Genre Natural Language Inference (MultiNLI) corpus~\citep{bowman2015large, williams2017broadcoverage}. MedNLI is a similarly-motivated, healthcare-specific dataset created by a small team of physician-annotators in lieu of crowdworkers, due to the extensive domain expertise required~\citep{romanov2018lessons}. \citet{poliak-etal-2018-hypothesis}, \citet{gururangan2018annotation}, \citet{tsuchiya-2018-performance}, and \citet{mccoy2019right} empirically demonstrate that SNLI and MultiNLI contain lexical and syntactic annotation artifacts that are disproportionately associated with specific classes, allowing a hypothesis-only classifier to significantly outperform a majority-class baseline model. The presence of such artifacts is hypothesized to be partially attributable to the priming effect of the example hypotheses provided to crowdworkers at annotation-time. \citet{romanov2018lessons} note that a hypothesis-only baseline is able to outperform a majority class baseline in MedNLI, but they do not identify specific artifacts. We confirm the presence of annotation artifacts in MedNLI and proceed to identify their lexical and semantic characteristics. We then conduct adversarial filtering to partition MedNLI into \emph{easy} and \emph{difficult} subsets~\citep{sakaguchi2020winogrande}. We find that performance of off-the-shelf \texttt{fastText}-based hypothesis-only and hypothesis-plus-premise classifiers is lower on the \emph{difficult} subset than on the \emph{full} and \emph{easy} subsets~\citep{joulin2016bag}. We provide partition information for downstream use, and conclude by advocating alternative dataset construction strategies for knowledge-intensive domains.\footnote{See {https://github.com/crherlihy/clinical\_nli\_artifacts} for code and partition ids.} \section{The MedNLI Dataset} MedNLI is domain-specific evaluation dataset inspired by general-purpose NLI datasets, including SNLI and MultiNLI~\citep{romanov2018lessons, bowman2015large, williams2017broadcoverage}. Much like its predecessors, MedNLI consists of premise-hypothesis pairs, in which the premises are drawn from the \texttt{Past Medical History} sections of a randomly selected subset of de-identified clinical notes contained in MIMIC-III~\citep{johnson2016mimicIII, goldberger2000physiobank}. MIMIC-III was created from the records of adult and neonatal intensive care unit (ICU) patients. As such, complex and clinically severe cases are disproportionately represented, relative to their frequency of occurrence in the general population. Physician-annotators were asked to write a \textit{definitely true}, \textit{maybe true}, and \textit{definitely false} set of hypotheses for each premise, corresponding to \textit{entailment}, \textit{neutral} and \textit{contradiction} labels, respectively. The resulting dataset has cardinality: $n_{\text{train}} = 11232; \ n_{\text{dev}} = 1395; \ n_{\text{test}} = 1422$. \section{MedNLI Contains Artifacts} \label{sec:mednliContainsArtifacts} To determine whether MedNLI contains annotation artifacts that may artificially inflate the performance of models trained on this dataset, we train a simple, premise-unaware, \texttt{fastText} classifier to predict the label of each premise-hypothesis pair, and compare the performance of this classifier to a majority-class baseline, in which all training examples are mapped to the most commonly occurring class label~\citep{joulin2016bag, poliak-etal-2018-hypothesis, gururangan2018annotation}. Note that since annotators were asked to create an entailed, contradictory, and neutral hypothesis for each premise, MedNLI is class-balanced. Thus, in this setting, a majority class baseline is equivalent to choosing a label uniformly at random for each training example. The micro F1-score achieved by the \texttt{fastText} classifier significantly exceeds that of the majority class baseline, confirming the findings of \citet{romanov2018lessons}, who report a micro-F1 score of 61.9 but do not identify or analyze artifacts: \begin{table}[!bth] \centering \small \begin{tabular}{lcc} \hline {} & \textbf{dev} & \textbf{test} \\ \hline majority class & 33.3 & 33.3 \\ \texttt{fastText} & \textbf{64.8} & \textbf{62.6} \\ \hline \end{tabular} \caption{Performance (micro F1-score) of the \texttt{fastText} hypothesis-only classifier.} \label{tab:fastTextF1} \end{table} As the confusion matrix for the test set shown in \hyperref[tab:confusionMatrix]{Table 2} indicates, the \texttt{fastText} model is most likely to misclassify entailment as neutral, and neutral and contradiction as entailment. Per-class precision and recall on the test set are highest for contradiction (73.2; 72.8) and lowest for entailment (56.7; 53.8). \begin{table}[!htb] \resizebox{\columnwidth}{!}{% \centering \begin{tabular}{lccc} \hline {} & entailment & neutral & contradiction \\ \hline entailment & \textbf{255} & 151 & 68 \\ neutral & 126 & \textbf{290} & 58 \\ contradiction & 69 & 60 & \textbf{345} \\ \hline \end{tabular}% } \caption{Confusion matrix for \texttt{fastText} classifier.} \label{tab:confusionMatrix} \end{table} \section{Characteristics of Clinical Artifacts} In this section, we conduct class-specific lexical analysis to identify the clinical and domain-agnostic characteristics of annotation artifacts associated with each set of hypotheses in MedNLI. \subsection{Preprocessing} We cast each hypothesis string in the MedNLI training dataset to lowercase. We then use a \texttt{scispaCy} model pre-trained on the \texttt{en\_core\_sci\_lg} corpus for tokenization and clinical named entity recognition (CNER)~\citep{neumann2019scispacy}. One challenge associated with clinical text, and scientific text more generally, is that semantically meaningful entities often consist of spans rather than single tokens. To mitigate this issue during lexical analysis, we map each multi-token entity to a single-token representation, where sub-tokens are separated by underscores. \subsection{Lexical Artifacts} \label{sec:lexicalArtifacts} Following \citet{gururangan2018annotation}, to identify tokens that occur disproportionately in hypotheses associated with a specific class, we compute token-class pointwise mutual information (PMI) with add-50 smoothing applied to raw counts, and a filter to exclude tokens appearing less than five times in the overall training dataset. Table \hyperref[tab:wordChoice]{3} reports the top 15 tokens for each class. \begin{equation} \noindent \nonumber \texttt{PMI}(\text{token, class}) = log_2 \frac{p(\text{token, class})}{p(\text{token}, \cdot ) p(\cdot, \text{class})} \end{equation} \begin{table*}[!htb] \small \centering \begin{tabular}{lclclc} \toprule entailment & \% & neutral & \% & contradiction & \% \\ \midrule just & 0.25\% & cardiogenic\_shock & 0.33\% & no\_history\_of\_cancer & 0.27\% \\ high\_risk & 0.26\% & pelvic\_pain & 0.30\% & no\_treatment & 0.27\% \\ pressors & 0.25\% & joint\_pain & 0.30\% & normal\_breathing & 0.27\% \\ possible & 0.26\% & brain\_injury & 0.32\% & no\_history\_of\_falls & 0.27\% \\ elevated\_blood\_pressure & 0.26\% & delerium & 0.30\% & normal\_heart\_rhythm & 0.28\% \\ responsive & 0.25\% & intracranial\_pressure & 0.30\% & health & 0.26\% \\ comorbidities & 0.26\% & smoking & 0.42\% & normal\_head\_ct & 0.26\% \\ spectrum & 0.27\% & obesity & 0.41\% & normal\_vision & 0.26\% \\ steroid\_medication & 0.25\% & tia & 0.32\% & normal\_aortic\_valve & 0.27\% \\ longer & 0.26\% & acquired & 0.31\% & bradycardic & 0.26\% \\ history\_of\_cancer & 0.26\% & head\_injury & 0.31\% & normal\_blood\_sugars & 0.27\% \\ broad & 0.26\% & twins & 0.30\% & normal\_creatinine & 0.28\% \\ frequent & 0.25\% & fertility & 0.30\% & cancer\_history & 0.26\% \\ failed & 0.26\% & statin & 0.30\% & cardiac & 0.33\% \\ medical & 0.29\% & acute\_stroke & 0.30\% & normal\_chest & 0.28\% \\ \bottomrule \end{tabular} \caption{Top 15 tokens by \texttt{PMI}(token, class); \% of \emph{class} training examples that contain the token.} \label{tab:wordChoice} \end{table*} \paragraph{Entailment} Entailment hypotheses are characterized by tokens about: (1) patient status and response to treatment (e.g., \emph{responsive}; \emph{failed}; \emph{longer} as in \emph{no longer intubated}); (2) medications and procedures which are common among ICU patients (e.g., \emph{broad\_spectrum}; \emph{antibiotics}; \emph{pressors}; \emph{steroid\_medication}; \emph{underwent}; \emph{removal}); (3) generalized versions of specific words in the premise (e.g., \emph{comorbidities}; \emph{multiple\_medical\_problems}), which \citet{gururangan2018annotation} also observe in SNLI; and (4) modifiers related to duration, frequency, or probability (e.g., \emph{frequent}, \emph{possible}, \emph{high\_risk}). \paragraph{Neutral} Neutral hypotheses feature tokens related to: (1) chronic and acute clinical conditions (e.g., \emph{obesity}; \emph{joint\_pain}; \emph{brain\_injury}); (2) clinically relevant behaviors (e.g., \emph{smoking}; \emph{alcoholic}; \emph{drug\_overdose}); and (3) gender and reproductive status (e.g., \emph{fertility}; \emph{pre\_menopausal}). Notably, the most discriminative conditions tend to be commonly occurring within the general population and generically stated, rather than rare and specific. This presumably contributes to the relative difficulty that the hypothesis-only \texttt{fastText} model has distinguishing between the entailment and neutral classes. \paragraph{Contradiction} Contradiction hypotheses are characterized by tokens that convey normalcy and good health. Lexically, such sentiment manifests as: (1) explicit negation of clinical severity, medical history, or in-patient status (e.g., \emph{denies\_pain}; \emph{no\_treatment}; \emph{discharged\_home}), or (2) affirmation of clinically unremarkable findings (e.g., \emph{normal\_heart\_rhythm}; \emph{normal\_blood\_sugars}), which would generally be rare among ICU patients. This suggests a heuristic of inserting negation token(s) to contradict the premise, which \citet{gururangan2018annotation} also observe in SNLI. \subsection{Syntactic Artifacts} \paragraph{Hypothesis Length} In contrast to \citet{gururangan2018annotation}'s finding that entailed hypotheses in SNLI tend to be shorter while neutral hypotheses tend to be longer, hypothesis sentence length does not appear to play a discriminatory role in MedNLI, regardless of whether we consider merged- or separated-token representations of multi-word entities, as illustrated by Table \hyperref[fig:hypLenTable]{4}: \begin{table}[!htb] \label{fig:hypLenTable} \resizebox{\columnwidth}{!}{% \begin{tabular}{l|c|c|c|c|c|c|} \cline{2-7} & \multicolumn{2}{c|}{\textbf{entailment}} & \multicolumn{2}{c|}{\textbf{neutral}} & \multicolumn{2}{c|}{\textbf{contradiction}} \\ \cline{2-7} & mean & median & mean & median & mean & median \\ \hline \multicolumn{1}{|c|}{\textbf{separate}} & 5.6 & 5.0 & 5.2 & 5.0 & 5.6 & 5.0 \\ \hline \multicolumn{1}{|c|}{\textbf{merged}} & 5.3 & 5.0 & 4.9 & 5.0 & 5.3 & 5.0 \\ \hline \end{tabular}% } \caption{Average and median hypothesis length by class and entity representation.} \end{table} \section{Physician-Annotator Heuristics} \label{sec:annotatorHeuristics} In this section, we re-introduce premises to our analysis to evaluate a set of hypotheses regarding latent, class-specific annotator heuristics. If annotators \emph{do} employ class-specific heuristics, we should expect the semantic contents, $\upvarphi$, of a given hypothesis, $h \in \mathcal{H}$, to be influenced not only by the semantic contents of its associated premise, $p \in \mathcal{P}$, but also by the target class, $c \in \mathcal{C}$. To investigate, we identify a set of heuristics parameterized by $\upvarphi(p)$ and $c$, and characterized by the presence of a set of heuristic-specific Medical Subject Headings (MeSH) linked entities in the premise and hypothesis of each heuristic-satisfying example. These heuristics are described below; specific MeSH features are detailed in the \hyperref[sec:appendix]{Appendix}. \paragraph{Hypernym Heuristic} This heuristic applies when the premise contains clinical condition(s), medication(s), finding(s), procedure(s) or event(s), the target class is \emph{entailment}, and the generated hypothesis contains term(s) that can be interpreted as super-types for a subset of elements in the premise (e.g., clindamycin \texttt{<:} antibiotic). \paragraph{Probable Cause Heuristic} This heuristic applies when the premise contains clinical condition(s), the target class is \emph{neutral}, and the generated hypothesis provides a plausible, often subjective or behavioral, causal explanation for the condition, finding, or event described in the premise (e.g., associating altered mental status with drug overdose). \paragraph{Everything Is Fine Heuristic} This heuristic applies when the premise contains condition(s) or finding(s), the target class is \emph{contradiction}, and the generated hypothesis negates the premise or asserts unremarkable finding(s). This can take two forms: repetition of premise content plus negation, or inclusion of modifiers that convey good health. \paragraph{Analysis} We conduct a $\chi^2$ test for each heuristic to determine whether we are able to reject the null hypothesis that pattern-satisfying premise-hypothesis pairs are uniformly distributed over classes. \begin{table}[!htb] \footnotesize \centering \begin{tabular}{lcll} \toprule \textbf{heuristic} & $\chi^2$ & \textbf{p-value} & \textbf{top class} \\ \midrule hypernym & 59.15 & \num{1.4e-13}$\ddagger$ & entail (45.2\%) \\ probable cause & 111.05 & \num{7.7e-25}$\ddagger$ & neutral (57.8\%) \\ everything fine & 874.71 & \num{1.1e-190}$\ddagger$ & contradict (83.8\%) \\ \bottomrule \end{tabular}% \caption{Results of $\chi^2$ test statistic by heuristic, computed using the combined MedNLI dataset \footnotesize{($\ddagger$ $p<0.001$, $\dagger$ $p<0.01$, * $p<0.5$).} Top class presented with \% of heuristic-satisfying pairs.} \label{tab:chisquare} \end{table} The results support our hypotheses regarding each of the three heuristics. Notably, the percentage of heuristic-satisfying pairs accounted for by the top class is lowest for the \textsc{hypernym} hypothesis, which we attribute to the high degree of semantic overlap between entailed and neutral hypotheses. \section{Adversarial Filtering} To mitigate the effect of clinical annotation artifacts, we employ \texttt{AFLite}, an adversarial filtering algorithm introduced by \citet{sakaguchi2020winogrande} and analyzed by \citet{bras2020adversarial}, to create \emph{easy} and \emph{difficult} partitions of MedNLI. \texttt{AFLite} requires distributed representations of the full dataset as input, and proceeds in an iterative fashion. At each iteration, an ensemble of $n$ linear classifiers are trained and evaluated on different random subsets of the data. A score is then computed for each premise-hypothesis instance, reflecting the number of times the instance is correctly labeled by a classifier, divided by the number of times the instance appears in any classifier's evaluation set. The top-$k$ instances with scores above a threshold, $\tau$, are filtered out and added to the \emph{easy} partition; the remaining instances are retained. This process continues until the size of the filtered subset is $< k$, or the number of retained instances is $< m$; retained instances constitute the \emph{difficult} partition. To represent the full dataset, we use $\texttt{fastText}_{\text{MIMIC-III}}$ embeddings, which have been pretrained on deidentified patient notes from MIMIC-III~\citep{romanov2018lessons, johnson2016mimicIII}. We represent each example as the average of its component token vectors. We proportionally adjust a subset of the hyperparameters used by \citet{sakaguchi2020winogrande} to account for the fact that MedNLI contains far fewer examples than \textsc{Winogrande}\footnote{MedNLI's training dataset contains $14049$ examples when the training, dev, and test sets are combined, while \textsc{Winogrande} contains $47$K after excluding the $6$K used for fine-tuning.}: specifically, we set the training size for each ensemble, $m$, to $5620$, which represents $\approx \frac{2}{5}$ of the MedNLI combined dataset. The remaining hyperparameters are unchanged: the ensemble consists of $n = 64$ logistic regression models, the filtering cutoff, $k$ = 500, and the filtering threshold $\tau =0.75$. We apply \texttt{AFLite} to two different versions of MedNLI: (1) $\mathcal{X}_{h,m}$: hypothesis-only, multi-token entities merged, and (2) $\mathcal{X}_{ph,m}$: premise and hypothesis concatenated, multi-token entities merged. \texttt{AFLIte} maps each version to an \emph{easy} and \emph{difficult} partition, which can in turn be split into training, dev, and test subsets. We report results for the \texttt{fastText} classifier trained on the original, hypothesis-only (hypothesis + premise) MedNLI training set, and evaluated on the \emph{full}, \emph{easy} and \emph{difficult} dev and test subsets of $\mathcal{X}_{h,m}$ ($\mathcal{X}_{ph,m}$), and observe that performance decreases on the \emph{difficult} partition: \begin{table}[!htb] \resizebox{\columnwidth}{!}{% \centering \begin{tabular}{lccccc} \toprule {} & \textbf{model} & \textbf{eval dataset} & \textbf{full} & \textbf{easy} ($\Delta$) & \textbf{difficult} ($\Delta$) \\ \midrule \textbf{no premise} & majority class & dev & 0.33 & 0.34 (+0.01) & 0.35 (+0.02) \\ \textbf{no premise} & majority class & test & 0.33 & 0.35 (+0.02) & 0.37 (+0.04) \\ \hline \textbf{no premise} & \texttt{fastText} & dev & 0.65 & 0.67 (+0.02) & 0.46 (-0.19) \\ \textbf{no premise} & \texttt{fastText} & test & 0.63 & 0.65 (+0.02) & 0.4 (-0.23) \\ \hline \textbf{with premise} & majority class & dev & 0.33 & 0.45 (+0.12) & 0.36 (+0.03) \\ \textbf{with premise} & majority class & test & 0.33 & 0.48 (+0.15) & 0.37 (+0.04) \\ \hline \textbf{with premise} & \texttt{fastText} & dev & 0.53 & 0.6 (+0.07) & 0.43 (-0.1) \\ \textbf{with premise} & \texttt{fastText} & test & 0.51 & 0.55 (+0.04) & 0.4 (-0.11) \\ \bottomrule \end{tabular} % } \caption{Performance (micro F1-score) for the majority class baseline and \texttt{fastText} classifiers, with and without premise, by partition (e.g., \emph{full, easy, difficult}).} \label{tab:afliteRes} \end{table} \section{Discussion} \subsection{MedNLI is Not Immune from Artifacts} In this paper, we demonstrate that MedNLI suffers from the same challenge associated with annotation artifacts that its domain-agnostic predecessors have encountered: namely, NLI models trained on $\{$Med, S, Multi$\}$NLI can perform well even without access to the training examples' premises, indicating that they often exploit shallow heuristics, with negative implications for out-of-sample generalization. Interestingly, many of the high-level lexical characteristics identified in MedNLI can be considered domain-specific variants of the more generic, class-specific patterns identified in SNLI. This observation suggests that a set of abstract design patterns for inference example generation exists across domains, and may be reinforced by the prompts provided to annotators. Creative or randomized priming, such as \citet{sakaguchi2020winogrande}~'s use of anchor words from WikiHow articles, may help to decrease reliance on such design patterns, but it appears unlikely that they can be systematically sidestepped without introducing new, ``corrective'' artifacts. \subsection{A Prescription for Dataset Construction} To mitigate the risk of performance overestimation associated with annotation artifacts, \citet{zellers2019hellaswag} advocate adversarial dataset construction, such that benchmarks will co-evolve with language models. This may be difficult to scale in knowledge-intensive domains, as expert validation of adversarially generated benchmarks is typically required. Additionally, in high-stakes domains such as medicine, information-rich inferences should be preferred over correct but trivial inferences that time-constrained expert annotators may be rationally incentivized to produce, because entropy-reducing inferences are more useful for downstream tasks. We advocate the adoption of a mechanism design perspective, so as to develop modified annotation tasks that reduce the cognitive load placed on expert annotators while incentivizing the production of domain-specific NLI datasets with high downstream utility~\citep{ho2015incentivizing, liu2017machine}. An additional option is to narrow the generative scope by defining a set of inferences deemed to be useful for a specific task. Annotators can then map (premise, relation) tuples to relation-satisfying, potentially fuzzy subsets of this pool of useful inferences, or return partial functions when more information is needed. \section{Ethical Considerations} When working with clinical data, two key ethical objectives include: (1) the preservation of patient privacy, and (2) the development of language and predictive models that benefit patients and providers to the extent possible, without causing undue harm. With respect to the former, MedNLI's premises are sampled from de-identified clinical notes contained in MIMIC-III~\cite{goldberger2000physiobank, johnson2016mimicIII}, and the hypotheses generated by annotators do not refer to specific patients, providers, or locations by name. MedNLI requires users to complete Health Insurance Portability and Accountability Act (HIPAA) training and sign a data use agreement prior to being granted access, which we have complied with. Per MedNLI's data use agreement requirements, we do not attempt to identify any patient, provider, or institution mentioned in the de-identified corpus. Additionally, while we provide AFLite \emph{easy} and \emph{difficult} partition information for community use in the form of split-example ids and a checksum, we do not share the premise or hypothesis text associated with any example. Interested readers are encouraged to complete the necessary training and obtain credentials so that they can access the complete dataset~\cite{romanov2018lessons, goldberger2000physiobank}. With respect to benefiting patients, the discussion of natural language artifacts we have presented is intended to encourage clinical researchers who rely on (or construct) expert-annotated clinical corpora to train domain-specific language models, or consume such models to perform downstream tasks, to be aware of the presence of annotation artifacts, and adjust their assessments of model performance accordingly. It is our hope that these findings can be used to inform error analysis and improve predictive models that inform patient care. \section*{Acknowledgments} We thank the four anonymous reviewers whose feedback and suggestions helped improve this manuscript. The first author was supported by the National Institute of Standards and Technology's (NIST) Professional Research Experience Program (PREP). This research was also supported by the DARPA KAIROS program. The views and conclusions contained in this publication are those of the authors and should not be interpreted as representing official policies or endorsements of NIST, DARPA, or the U.S. Government. \bibliographystyle{acl2021}
{'timestamp': '2021-06-04T02:06:13', 'yymm': '2106', 'arxiv_id': '2106.01491', 'language': 'en', 'url': 'https://arxiv.org/abs/2106.01491'}
arxiv
\section{Introduction} Recent years have seen great improvements in ``abstractive'' summarization models -- models that not only concatenate text from the source document, but can additionally paraphrase to generate summary text. Once limited to sentence compression \cite{rush-etal-2015-neural}, abstractive models now generate multi-sentence summaries \cite{see-etal-2017-get}, even for relatively long documents \cite{cohan-etal-2018-discourse}. However, extractive models and mixed models with significant extractive components continue to show strong performance, and the extent and manner in which abstraction is used by summarization models is not well understood. Previous work has raised concerns about whether models are able to paraphrase in ways that lead to better summaries. Abstractive models often generate summaries that are either ungrammatical or unfaithful to the source document \cite{maynez-etal-2020-faithfulness, durmus2020feqa, kryscinski-etal-2020-evaluating} and are prone to repetition in their outputs \cite{see-etal-2019-massively, holtzman2020curious}. These issues raise questions about \emph{how} neural summarizers generate novel text. Abstractive summarization is differentiated from extractive summarization by the model's ability to paraphrase, but paraphrasing ability is not directly measured by popular metrics, leading to a lack of understanding of the generative process. Some previous research has aimed to alleviate these issues in evaluation: \citet{zhang2018abstractiveness} propose evaluating summaries with human evaluations of informativeness and coherence, and \citet{Ganesan2018ROUGE2U} implements a metric to reward models that paraphrase via simple synonym substitutions according to WordNet. However, synonym substitution is just one form of paraphrasing, and truly abstractive models should be capable of more complex paraphrasing strategies. To understand how abstraction manifests in neural summarization models, we study a model that has an explicit abstraction/extraction switch, the pointer-generator model of \citet{see-etal-2017-get}. The training objective of this model causes it to choose the best summarization strategy (abstractive vs extractive) in different contexts, permitting us to determine the environments where abstractive summarization is an effective summarization strategy. First, we show how the switch varies across a full summary and is influenced by the decoder's copy and generation distributions. Next, we present a behavioral probe of the abstraction/extraction switch, to observe how the switch reacts to lexical, structural, and distributional information as it decodes a summary. Finally, we modify the switch value, forcing more frequent paraphrase generation during decoding, revealing the limits of the model's paraphrasing capabilities. Ultimately, we find across both the CNN/DailyMail and XSum datasets that the model's abstractive capabilities are limited; the model understands how to identify and combine constituents from the source text in a grammatical fashion, but lacks the semantic understanding required to produce grammatical, faithful and meaningful paraphrases. \section{Model} \subsection{The Pointer-Generator Model} We study the pointer-generator model released by \citet{see-etal-2017-get}, which uses an explicit switch, $p_{\text{gen}}$, that blends abstractive and extractive summarization strategies. We briefly review the pointer-generator model here; for more details, see the original paper of \citet{see-etal-2017-get}. The final output distribution for a particular word in the summary $P(w)$ is a weighted sum of the generation distribution and the copy distribution, weighted by $p_{\text{gen}}$ and $1 - p_{\text{gen}}$, respectively. This is described by Equation 9 in \citet{see-etal-2017-get}, modified for clarity here: \begin{equation} P(w) = p_{\text{gen}} P_{\text{vocab}}(w) + (1-p_{\text{gen}}) P_{\text{copy}}(w) \end{equation} $P_{\text{vocab}}(w)$ is the generation distribution over the model's vocabulary, and $P_{\text{copy}}(w)$ is the copy distribution over the tokens in the source document. The $p_{\text{gen}}$ switch explicitly weights the influence of the generation and copy mechanisms on $P(w)$. For each time step $t$, $p_{\text{gen}}$ is a function of the context vector $h_t^*$, the decoder state $s_t$ and the decoder input $x_t$, \begin{equation} p_{\text{gen}} = \sigma(\delta_{h_t^*}^T h_t^* + \delta_s^T s_t + \delta_x^T x_t + \beta_{\text{ptr}}) \end{equation} where $\sigma$ is the sigmoid function and $\delta_{h_t^*}$, $\delta_s$, $\delta_x$ and $\beta_{\text{ptr}}$ are learned parameters. \citet{see-etal-2017-get} also use a coverage mechanism aimed at reducing repetition, defining the coverage vector $c^t$ as \begin{equation} c^t = \sum_{t'=0}^{t-1} P_{\text{copy}(w_t)} \end{equation} which is passed as another input to the attention mechanism. \subsection{Data} We analyze pointer-generator behavior when trained on an extractive-biased dataset, CNN/DailyMail, and on an abstractive-biased dataset, XSum. The CNN/DailyMail dataset is made up of multi-sentence summaries of news articles from CNN and Daily Mail. XSum \citep{narayan2018don} is a summarization dataset that uses the first sentence of a news article as a summary of the article. The dataset treats the remainder of the article as the source document. As a result, the summaries are both shorter and more difficult to copy from the source document, compared to the CNN/DailyMail dataset. \subsection{Training} Our experiments on CNN/DailyMail use the trained model released by \citet{see-etal-2017-get}, which includes the coverage mechanism described above. We decode summaries on the test set of at most 120 tokens using beam search with beam width 4, as in the original paper. For XSum, we trained our own model on the XSum training partition, using the code released by \citet{see-etal-2017-get}.\footnote{Code and full replication details are available at \href{https://github.com/mwilbz/pointer-generator-analysis}{https://github.com/mwilbz/pointer-generator-analysis}.} Like \citet{narayan2018don}, we do not include the coverage mechanism for the XSum model. When coverage is used for the XSum model, ROUGE scores \citep{lin-2004-rouge} slightly decrease, and the produced summaries contain more severe hallucinations. However, adding coverage does ``fix'' some degenerate summaries that produce the same sequence of tokens repeatedly -- see Appendix B for an example. For both datasets, in addition to the output summaries, we record the value of the $p_{\text{gen}}$ switch for each emitted token, as well as the generation distribution and the copy distribution at each time step. \section{Experiments}\label{section:experiments} \begin{figure*}[h!] \centering \begin{subfigure}[b]{\textwidth} \centering \includegraphics[width=\linewidth]{img/0.png} \caption{CNN/DailyMail} \end{subfigure} \begin{subfigure}[b]{\textwidth} \centering \includegraphics[width=\linewidth]{img/xsum_2.png} \caption{XSum} \end{subfigure} \caption{(Top) Correlation contributions $\CC(p_{\text{gen}}, H_{\text{gen}})$ (green) and $\CC(p_{\text{gen}}, H_{\text{copy}})$ (purple) for a randomly-sampled summary. (Bottom) Bar plot of per-token $p_{\text{gen}}$ (orange), and entropy of the generation distribution (green) and copy distribution (purple) for the same summary.} \label{fig:corr_contrib_0} \end{figure*} In Section~\ref{section:experiment_token_level} we qualitatively analyze the evolution of the per-token $p_{\text{gen}}$ and uncertainty in the extractive/abstractive components over the course of randomly selected summaries. Section~\ref{section:probing_pgen} provides quantitative evidence of our observations across the full test sets, by modeling the lexical, structural, and distributional ($P_{\text{vocab}}$ and $P_{\text{copy}}$) environments that drive the variability of the ${p_{\text{gen}}}$ switch. Finally, in Section~\ref{section:modifying_pgen} we manipulate $p_{\text{gen}}$ of the CNN/DailyMail model to generate summaries that are more abstractive than those of the base model, in order to disentangle any abstractive \emph{behavior} from abstractive \emph{capabilities}, finding that the model's abstractive capabilities are largely limited to lexical paraphrases, and that forcing the model to generate more novel text yields unfaithful summaries. \subsection{Token-level Analysis} \label{section:experiment_token_level} \subsubsection{Model} The $p_{\text{gen}}$ switch explicitly tells us how much weight is assigned to the generation and copy distributions. \citet{see-etal-2017-get} make qualitative claims about the environments where ${p_{\text{gen}}}$ is highest: “We find that ${p_{\text{gen}}}$ is highest at times of uncertainty such as the beginning of sentences, the join between stitched-together fragments, and when producing periods that truncate a copied sentence.” In this section, we evaluative these observations on randomly selected summaries generated with each model. We quantify the notion of ``uncertainty'' from \citet{see-etal-2017-get} using information-theoretic entropy \cite{shannon48} of the distribution that predicts the next word ${w_i}$ of a generated summary: \begin{equation} H_\theta(w_i) = \mathbb{E}_{P_\theta} \left[ -\log P_\theta(w_{i}) \right]. \end{equation} where $P_\theta$ is the predictive distribution over the model vocabulary $V_\theta$ at a given time step. In our experiments, we use \emph{normalized} entropy, which divides the equation above by $\log_2 |V_\theta|$, to limit the domain to $[0,1]$ regardless of the vocabulary size. We calculate model-internal entropies $H_{\text{gen}}$ and $H_{\text{copy}}$ by setting $P_\theta$ equal to $P_{\text{vocab}}$ and $P_{\text{copy}}$, respectively. Given the entropy of the copy and generation distributions at each decoder time step, we investigate the relationship between $p_{\text{gen}}$, $H_{\text{gen}}$, and $H_{\text{copy}}$ by calculating per-token \emph{correlation contributions}. Intuitively, correlation contribution measures how much an individual token contributes to either positive or negative correlation between $p_{\text{gen}}$ and the model entropies. The Pearson correlation coefficient between two sequences $\mathbf{x} = [x_1, \ldots, x_n]$ and $\mathbf{y} = [y_1, \ldots, y_n]$ can be written as \begin{equation} r = \frac{\sum_{i=1}^n (x_i - \bar{x}) (y_i - \bar{y})}{\sqrt{\sum_{i=1}^n (x_i-\bar{x})^2 \sum_{i=1}^n (y_i-\bar{y})^2}} \end{equation} We calculate the correlation contribution of the pair $(x_i, y_i)$ at index $i$ to be \begin{equation} \CC_i = \frac{n (x_i - \bar{x}) (y_i - \bar{y})}{\sqrt{\sum_{i=1}^n (x_i-\bar{x})^2 \sum_{i=1}^n (y_i-\bar{y})^2}} \end{equation} Note that the correlation between $\mathbf{x}$ and $\mathbf{y}$ is equal to the average of $\CC_1, \CC_2, \ldots, \CC_n$, but unlike $r$, the correlation coefficient, each component $\CC_i$ is not bounded by $[-1, 1]$. \subsubsection{Results} Across the test splits, the Pearson correlation betwen $p_{\text{gen}}$ and $H_{\text{gen}}$ is $-0.47$ for CNN/DailyMail and $-0.55$ for XSum. The correlation between $p_{\text{gen}}$ and $H_{\text{copy}}$ is $0.12$ for CNN/DailyMail and $0.54$ for XSum. This suggests that the higher-certainty (lower $H$) distribution is weighted more heavily when combining the generation and copy distributions, since $p_{\text{gen}}$ is high when $H_{\text{gen}}$ is low, and low when $H_{\text{copy}}$ is low. Visualizing the correlation contributions across a sentence helps us understand how individual tokens are decoded as a function of uncertainty in the abstractive and extractive components of the model. We randomly sample articles from each dataset's test split, and visualize the correlation contributions for the generated summaries in Figure \ref{fig:corr_contrib_0}. Additional examples may be found in Appendix A. \textbf{CNN/DailyMail}: The tokens that correlate high $p_{\text{gen}}$ with low $H_{\text{gen}}$ (high certainty in the abstractive component) are frequently punctuation, and periods in particular. This punctuation appears to be used to truncate sentences at a syntactic boundary, a behavior we quantify in Section \ref{section:probing_pgen}. The correlation of high $p_{\text{gen}}$ and high $H_{\text{copy}}$ (low certainty in the extractive component) comes from tokens including ``has'', ``managed'', ``.'', and ``sterling''; all tokens that appear multiple times in the source document. This suggests a possible role played by generation to tie break when the copy distribution has low certainty about which continuation to copy next. \textbf{XSum}: The XSum model uses the copy mechanism very infrequently; $p_{\text{gen}}$ is frequently large. When $p_{\text{gen}}$ is small, we tend to observe uncertainty in the generative component and certainty in the copy component, according to entropy measures. In Figure \ref{fig:corr_contrib_0}, we see this happens when the proper noun ``smiler'', a rollercoaster name, is generated. It also happens at the beginning of a quotation, indicating that the model has learned that quotations should be copied from the source document, rather than generated. Overall, we see a strong contrast in $p_{\text{gen}}$ values between the two models. On the extractive-biased CNN/DailyMail dataset, the model learns to copy frequently, generating where necessary to truncate sentences. On the generative-biased XSum dataset, the model acts nearly like a simple seq2seq model, only infrequently using the copy mechanism for the sake of proper nouns and quotations.\footnote{This can also be seen in the contrasting gaps between the seq2seq and pointer-generator ROGUE scores reported by \citet{see-etal-2017-get} and \citet{narayan2018don}. The former sees a 9-point gap in ROUGE-1, while the latter reports a 1-point gap.} \subsection{Probing $p_{\text{gen}}$} \label{section:probing_pgen} In the previous section, we made qualitative observations about the relationship between $p_{\text{gen}}$ and model entropies, as well as the linguistic environments where $p_{\text{gen}}$ is highest. In this section, we quantify these relationships by predicting $p_{\text{gen}}$ with a linear model of lexical, syntactic and distributional factors. \subsubsection{Model Features} In this section, we describe the four feature sets we use to model ${p_{\text{gen}}}$. These include model-internal entropy measures from the \citet{see-etal-2017-get} summarizer, model-external entropy measures derived from pretrained language models, structural features derived from syntactic parses of summaries, and part-of-speech tags. \textbf{Summarization model entropies:} We use $H_{\text{gen}}$ and $H_{\text{copy}}$ as features, hypothesizing, like \citet{see-etal-2017-get}, that the uncertainty in the copy and generation distributions will have a significant effect on $p_{\text{gen}}$. \textbf{Language model entropies:} We also use entropy from three types of language models with varying degrees of lexical and structural expressiveness: a trigram model,\footnote{A Kneser-Ney trigram model trained on 5.4m tokens of the articles from the training partition of the summarization dataset.} a top-down incremental constituency parser \cite{roark-2001-probabilistic,roark-etal-2009-deriving}, and a unidirectional recurrent neural language model \cite{van-schijndel-etal-2019-quantity}. These models allow us to directly measure how much ${p_{\text{gen}}}$ may be influenced by lexical, syntactic, and distributional uncertainty in the generated summary independent of the summarization objective. \textbf{Structural Features:} The summarization model may also condition its decision to copy or generate on the current syntactic environment. While pointer-generator models do not explicitly model syntax, they may exhibit some implicit syntactic knowledge, such as the ability to identify and copy whole constituents. As mentioned above, \citet{see-etal-2017-get} claim that $p_{\text{gen}}$ is high at the “the join between stitched-together fragments.” Structural features allow us to quantify this, seeing whether the model has learned to prefer copying or generation in particular syntactic environments. We incorporate two structural measures into our model: the root distance of word $w_i$, denoted as ${\Droot(w_i)}$ and the edge distance between word $w_{i-1}$ and $w_i$, denoted as ${\Dedge(w_{i-1}, w_i)}$. These measures are calculated on parse trees of generated summaries.\footnote{Parses and part of speech tags are generated by the top-down constituency parser.} Root distance is the distance in the parse tree from the current word to the root node, and corresponds to the depth of the word in the parse tree. This measure will tell us if there is an association between depth in the tree and the decision to copy or generate. Edge distance is the number of intervening edges between the current and previous word in the summary. Edge distance will be smaller within a constituent than across two constituents. This measure allows us to test whether the decision to copy or generate is associated with the size of the syntactic boundary between words. \textbf{Part of Speech:} In addition to structure, the summarization model may condition its decision to copy or generate on the syntactic category of the most recently generated word. For example, in our preliminary qualitative observations of the CNN/DailyMail model, we found that ${p_{\text{gen}}}$ was higher when decoding punctuation, main verbs and conjunctions. To test the association between part-of-speech and ${p_{\text{gen}}}$ formally, we include the part-of-speech label of the current word in our model. \subsubsection{CNN/DailyMail Results} We predicted $p_{\text{gen}}$ using four single feature-set linear models, and a single linear model including all features. We conducted ANOVA tests on all combinations of nested models, and found that each set of features significantly improves the $p_{\text{gen}}$ model (all $p < 0.00001$; see Table~\ref{tab:pgen_model}). \textbf{Entropies:} The coefficients for the model-internal entropy measures $H_{\text{gen}}$ and $H_{\text{copy}}$ intuitively indicate that as uncertainty in the generation distribution increases, the model is less likely to generate, and as uncertainty in the copy distribution increases, the model is less likely to copy; these relationships were previously explored in Section \ref{section:experiment_token_level}. The three language model entropy estimates are significantly associated with ${p_{\text{gen}}}$. However, the coefficients are all very small and this feature set individually does the poorest job of explaining ${p_{\text{gen}}}$\!'s variance of all the sets we analyzed. This could be due to the fact that, with the exception of the $n$-gram\ model, the language model entropy estimates come from different training data than the summarization model. Regardless, while language model entropies significantly improved $p_{\text{gen}}$ prediction, the other feature sets showed a much stronger relationship with ${p_{\text{gen}}}$. Therefore we do not focus on language model entropies in subsequent sections. \begin{table}[!t] \centering \small \begin{tabular}{ c c c } \hline Feature Set & Feature & $\beta$ \\ \hline\hline Summ. Model Entropies & ${H_{\text{gen}}}$ & -0.052 \\ ($R^2$ = 0.274) & ${H_{\text{copy}}}$ & 0.035 \\ \hline LM Entropies & ${H_{\text{LSTM}}}$ & 0.009 \\ ($R^2$ = 0.140) & ${H_{\text{parser}}}$ & 0.003 \\ & ${H_{\text{ngram}}}$ & 0.009 \\ \hline Structural Features & ${\Dedge(w_{i-1}, w_i)}$ & 0.018 \\ ($R^2$ = 0.204) & ${\Droot(w_i)}$ & -0.031 \\ \hline & \$ & -0.130 \\ & UH & -0.118 \\ & \# & -0.116 \\ Part of Speech & NNP & -0.111 \\ ($R^2$ = 0.593) & WRB & 0.156 \\ & : & 0.254 \\ & , & 0.269 \\ & . & 0.636 \\ \hline\hline Full Model $R^2$: 0.648 \\ \hline \end{tabular} \caption{Table of slope coefficients ${\beta}$ in the full linear model of ${p_{\text{gen}}}$ in the CNN/DailyMail model. Reported below the name of the feature set is the adjusted ${R^2}$ of a model fit only to that feature set. The eight part of speech tags with the largest magnitude ${\beta}$ are reported. All reported ${\beta}$ are significant via t-test (all ${p < 0.00001}$).} \label{tab:pgen_model} \end{table} \textbf{Structural Features:} Both structural features are significantly associated with ${p_{\text{gen}}}$. A model fit using only $\Dedge$ and $\Droot$ explains 20\% of ${p_{\text{gen}}}$'s variance ($R^2 = 0.204$). Edge-distance is positively associated with ${p_{\text{gen}}}$, meaning the larger the syntactic boundary between the previous and current word, the more likely the summarization model is to generate. This provides evidence that the model has some knowledge of syntactic boundaries, and uses the generation component as a means of joining together clauses, in line with the observations of \citet{see-etal-2017-get}. We also find that distance to the root node of the parse is negatively associated with ${p_{\text{gen}}}$. This means that words which are higher in the parse tree are more likely to be generated than copied. Conversely, this means that generated components are unlikely to be associated with complex, deeply nested phrasing, suggesting \textbf{the generation component only produces simple shallow substitutions} rather than structurally complex paraphrases or even simple substitutions that modify structurally complex copied elements. \textbf{Part-of-Speech:} The part of speech tags with the highest negative association with ${p_{\text{gen}}}$ (i.e.\ those most likely to be copied) are \$ (currency symbols), UH (interjection), \# (pound symbol), followed by NNP (singular proper nouns). These results are perhaps unsurprising, as interjections and proper nouns are difficult to paraphrase and are often out-of-vocabulary in the generation component of the summarization model. \$ and \# serve as prefixes to numerical values which cannot be faithfully paraphrased and therefore should be copied directly from the source text. The tag for a cardinal number (CD) also has a relatively strong negative correlation with ${p_{\text{gen}}}$ (${\beta}$ = -0.088). The part-of-speech tags with the highest positive association with ${p_{\text{gen}}}$ (i.e.\ those most likely to be generated) are “.” (sentence-final punctuation), “,” (comma), “:” (colon), and WRB (wh-adverbs, such as "where" or "when”). All of these categories can link two clauses or complete sentences, consistent with the ``stitching'' hypothesis of \citet{see-etal-2017-get}. \begin{figure} \centering \includegraphics[width=\linewidth]{img/3.png} \caption{Distribution of ${p_{\text{gen}}}$ across all tokens in the test split of the CNN/DailyMail corpus. Sentence-final punctuation makes up 5\% of tokens in the dataset, which accounts for 22\% of ${p_{\text{gen}}}$'s mass} \label{fig:pgen_dist} \end{figure} The mean ${p_{\text{gen}}}$ value of all tokens in the test dataset was 0.204, while the mean ${p_{\text{gen}}}$ value for sentence-final tokens was 0.915. Further inspection of the ${p_{\text{gen}}}$ distribution reveals a cluster of outliers at ${p_{\text{gen}}}$ = 1.0. Figure \ref{fig:pgen_dist} shows the distribution of ${p_{\text{gen}}}$ values. We find that, of all tokens with ${p_{\text{gen}}} > 0.95$, 92.1\% are sentence-final punctuation. Despite making up 5\% of all tokens, periods account for 22.1\% of the total mass of ${p_{\text{gen}}}$ in the dataset. This suggests that sentence final punctuation is entirely controlled by the generation distribution. Additionally, we find that of all 5-grams in generated-summaries ending with sentence-final punctuation, 52\% are also present in the article text, compared to 12\% in the reference summaries. Despite the large ${p_{\text{gen}}}$ values exhibited by sentence-final punctuation, the model only generates punctuation in novel contexts less than half of the time, suggesting that \textbf{even when the model heavily utilizes its generative component, it essentially generates a copy of the source text}. Our explanatory model of ${p_{\text{gen}}}$ shows that model entropy, syntactic depth, syntactic boundary size, and part-of-speech are associated with ${p_{\text{gen}}}$. The strongest predictor of ${p_{\text{gen}}}$ is the part-of-speech of the current word, with copying most strongly associated with numbers, number prefixes and proper nouns, and generation most strongly associated with punctuation. We find that sentence-final punctuation is handled almost entirely by the generative component of the model, despite the fact that sentence-final punctuation occurs in novel contexts less than half of the time. \subsubsection{XSum Results} \label{sec:pgen_probe_xsum} Overall, we find that the variance of $p_{\text{gen}}$ in the XSum model is well explained by model-internal entropy, and relatively poorly explained by linguistic features. We believe this is driven by the categorically different behaviors of each model.% \footnote{The full table of model coefficients can be found in Table \protect\ref{tab:pgen_model_xsum} of Appendix~C.} While the CNN/DailyMail model only uses the generative component to join together copied constituents, the generative component dominates the XSum model's behavior. The mean $p_{\text{gen}}$ value across all tokens in the XSum dataset was 0.828, compared to 0.204 in the CNN/DailyMail dataset. While the structural features ${\Dedge(w_{i-1}, w_i)}$ and ${\Droot(w_i)}$ explained 20.4\% of the variance of $p_{\text{gen}}$ in the CNN/DailyMail model, these features only explain 4.9\% of the variance in the XSum model. Part of speech also does a poorer job of explaining the variance in XSum's $p_{\text{gen}}$. While part of speech explains 59.3\% of the variance of $p_{\text{gen}}$ in the CNN/DailyMail model, part of speech tags only explain 23.0\% in the XSum model. While the CNN/DailyMail model assigned an abnormally high $p_{\text{gen}}$ value to punctuation, we do not observe this behavior in the XSum model. The CNN/DailyMail model appeared to make use of the “.”, “:” and “,” tokens to join together copied sentences, but none of these tokens are a significant predictor of $p_{\text{gen}}$ in the XSum model. This suggests that the XSum model does not use the generation distribution to connect copied clauses. While the XSum model appears not to use the copy and generation distributions in the same way as the CNN/DailyMail model, we still observe some clear and intuitive associations between part of speech tags and $p_{\text{gen}}$. In particular, the XSum model appears to use the copy distribution to handle words which are likely to be out-of-vocabulary for the generation distribution. For example, singular and plural proper nouns, interjections and foreign words (NNP, NNPS, UH, and FW respectively) are associated with low values of $p_{\text{gen}}$ (copying), while all types of verbs are associated with large values of $p_{\text{gen}}$ (generation). We conclude that the CNN/DailyMail model primarily makes use of lexical and syntactic information such as clause boundaries and punctuation to modulate between copying and generation. By contrast, the XSum model primarily relies on the generation distribution, and backs off to the copy distribution at times of high generation uncertainty or high copy certainty, such as when copying a quote or a proper name. \subsection{Modifying $p_{\text{gen}}$} \label{section:modifying_pgen} \begin{table*}[!t] \centering \small \begin{tabular}{{| m{.95\textwidth} |}} \hline \textbf{Article Text}: raheem sterling has admitted he is not ready to sign a new contract at liverpool deal despite being offered a \# 100,000-a-week deal to stay with the merseyside club . the 20-year-old wideman edged closer towards an anfield exit after revealing in an interview with the bbc on wednesday that he would have signed for a lot less a year ago . however , despite being one of liverpool 's star men , sterling has struggled to repeat the impressive form he showed for the reds last season . the england international has managed just six goals this season - one less than stoke frontman jon walters - while his conversion rate and minutes per goal ratio have worsened as the graphic below shows . raheem sterling has managed just six goals this season - one less than stoke forward jon walters -lrb- left -rrb- . \\ \hline \textbf{Reference}: raheem sterling has revealed he is not ready to sign a new liverpool deal . the reds wideman has struggled to repeat last season's impressive form . the 20-year-old liverpool star has managed just six goals this season . read: sterling insists he is not a 'money-grabbing 20-year-old' sterling: what he said about contract talks... and what he meant . click here for the latest liverpool news . \\ \hline $\mathbf{p_{\text{min}}=0}$: raheem sterling has admitted he is not ready to sign a new contract . the england international has managed just six goals this season . sterling has managed just six goals this season - one less than stoke forward jon walters . \\ \hline $\mathbf{p_{\text{min}}=0.25}$: raheem sterling has admitted he is not ready to sign a new contract . the england international has managed just six goals this season . {\color{Cerulean} the england international} has managed just six goals this season . \\ \hline $\mathbf{p_{\text{min}}=0.50}$: raheem sterling has admitted he is not ready to sign a new contract . the england international has managed just six goals this season . {\color{Cerulean} the england international} has managed just six goals this season . \\ \hline $\mathbf{p_{\text{min}}=0.75}$: raheem sterling has admitted he is not ready to sign a new {\color{Cerulean} deal} . the {\color{Cerulean} 20-year-old} has {\color{Cerulean} scored} just six {\color{Cerulean} premier league} goals this season . {\color{Cerulean} the 20-year-old} has {\color{Cerulean} scored} just {\color{WildStrawberry} three} goals this season . \\ \hline $\mathbf{p_{\text{min}}=1}$: {\color{Cerulean} man utd face manchester city in the premier league on saturday . the} {\color{WildStrawberry} striker} has {\color{Cerulean} scored} just {\color{WildStrawberry} four} premier league goals this season . the {\color{WildStrawberry} 19-year-old} has scored just {\color{WildStrawberry} three} goals this season . {\color{Cerulean} click here for all the latest premier league news .} \\ \hline \end{tabular} \caption{Summaries generated for the same randomly selected article with varying values of $p_{\text{min}}$. Differences from the base model summary are highlighted in {\color{Cerulean} blue}, while non-faithful text is highlighted in {\color{WildStrawberry} red}.} \label{tab:min_pgen} \end{table*} \subsubsection{Model} Taking advantage of the smooth interpolation between the generation and copy distribution, we experiment with forcing the CNN/DailyMail model to be more abstractive. This, we expect, will allow us to differentiate between the abstractive \emph{behavior} we observe in the model summaries and the abstractive \emph{capabilities} that the model may have but which it only uses infrequently in practice. We do so by artificially modifying $p_{\text{gen}}$ during decoding. If $p_{\text{min}} \in [0,1]$ is a parameter that represents the minimum value of $p_{\text{gen}}$ we allow, we then modify $p_{\text{gen}}$ as follows: \begin{equation} p_{\text{gen}}^* = p_{\text{min}} + (1 - p_{\text{min}}) p_{\text{gen}} \end{equation} This may be viewed as a linear interpolation from the range $[0,1]$ to $[p_{\text{min}},1]$. As $p_{\text{min}}$ grows, the model is forced to rely more heavily on the generation distribution rather than the copy distribution.% \footnote{We do not run this experiment on the XSum model because it already usually has a large $p_{\text{gen}}$.} \subsubsection{Results} We use the same randomly sampled articles used in Section \ref{section:experiment_token_level}.% \footnote{We see similar patterns in other randomly-sampled summaries, shared in Appendix B.} Generated summaries for $p_{\text{min}}$ values in $[0, 0.25, 0.50, 0.75, 1.0]$ can be found in Table \ref{tab:min_pgen}. Consistent with previous studies, we find that the model is effective at producing grammatical output. At small values of $p_{\text{gen}}$, the model mostly copies sentences verbatim, but shows the ability to cut a sentence short in a grammatical manner. For example, ``raheem sterling has admitted he is not ready to sign a new contract at liverpool deal...'' is shortened to ``raheem sterling has admitted he is not ready to sign a new contract.'' At greater values of $p_{\text{gen}}$, the model continues sentences in a consistent fashion despite substituting nouns or verbs at the beginning or middle of the sentences. For example, ``sterling has managed just six goals...'' at $p_{\text{min}}=0$ becomes ``the 20-year-old has scored just six premier league goals'' at $p_{\text{min}}=.75$. However, we do not observe significant paraphrasing beyond these simple substitutions, and at high values of $p_{\text{min}}$, where the model is forced to rely heavily on the generation distribution, we begin to observe hallucinations where the model inserts inaccurate information about the player's age and the number of goals scored. When $p_{\text{min}}=1$, the model generates a completely hallucinated sentence, ``man utd face manchester city in the premier league on saturday'' and a non-informative advertisement ``click here for all the latest premier league news.'' \section{Discussion} Understanding the limitations preventing abstractive summarization models from paraphrasing effectively is our ultimate aim, but answering that question requires an understanding of current models' abstraction capabilities. In this paper, we analyze the abstractions of which the pointer-generator model \cite{see-etal-2017-get} is capable. When trained on CNN/DailyMail, we find that sentence truncation is the most common form of paraphrasing. Punctuation tokens are associated with high generation rates and low entropy in the generation distribution. Additionally, high $p_{\text{gen}}$ often results in generating the token that comes next in a phrase already being copied verbatim, suggesting that high $p_{\text{gen}}$ merely gives the model the \emph{option} to generate novel text, but that the model rarely makes use of it. Artificially increasing $p_{\text{gen}}$ does not significantly change this behavior, introducing increased rates of synonym substitution as well as increased rates of non-faithful hallucination. When trained on XSum, the model makes much less use of the copy mechanism, largely generating novel text with a few exceptions, including the copying of proper nouns and parts of quotations. The model generally produces topical summaries, but ones that aren't necessarily grammatical or faithful to the original article. For example, the randomly selected summary used in Figure \ref{fig:corr_contrib_0} repeats itself and wanders, ``... on the smiler rollercoaster on the smiler rollercoaster in the south west 200 years ago as `phenomenal'''. This comes after a hallucination, ``firefighters are continuing to search for a man'' even though the article describes the rescue from the rollercoaster crash in the past tense. We hypothesize that the phrase ``firefighters are continuing to search'' is a relatively common phrase in news articles that the model learned from the training data. Such frequency biases likely contribute to the faithfulness issues in abstractive summarizers reported in previous literature. Our results give context to previous observations that summarization model unfaithfulness increases with abstraction \cite{maynez-etal-2020-faithfulness, durmus2020feqa, kryscinski-etal-2020-evaluating} and that abstractive models are prone to output repetition \cite{see-etal-2019-massively, holtzman2020curious}. To faithfully paraphrase, a model must understand both the syntax and the semantics of the original text. The models we studied were able to recognize syntactic boundaries, proper nouns, and noun phrases that could be substituted with synonyms. However, the models didn't appear to comprehend the meaning of the text well enough to generate faithful complex paraphrases. This is unacceptable in high-risk domains such as healthcare; \citet{zhang-etal-2018-learning-summarize} train a model to summarize radiology findings, but only 67\% of their summaries are judged at least as good as human summaries, in a domain where errors can have a major impact on human lives. In our work, the explicit switch between abstractive and extractive modes enabled us to directly observe the conditions under which abstractive summarization was chosen as a strategy, and to force an abstractive summarization strategy to disentangle paraphrasing behavior from capabilities. We found that the \citet{see-etal-2017-get} model trained on CNN/DailyMail did learn simple forms of paraphrasing, despite the extractive bias of the dataset. We conclude that pointer-generator models are \emph{capable} of simple paraphrasing regardless of training data, even though they \emph{behave} in ways that rely on the frequency biases of the training dataset. However, they also appear \emph{incapable} of producing significant paraphrases that are grammatical, non-repetitive, and faithful to the source document. This suggests that using an abstractive-biased dataset alone is not enough for a model to learn robust and faithful paraphrasing strategies. Rather, when trained on XSum, the pointer-generator model seems to simply learn that it should not copy from the source text. Future work should investigate how either datasets or models can improve the training signal that allows the model to understand the underlying semantics of the source document. Related to our work, \citet{xu-etal-2020-understanding} studied the summarization strategies of state-of-the-art transformer summarization models. Since their models did not contain an explicit copy/generation switch, they used $n$-gram\ overlap between source documents and summaries as a proxy to measure a summary's ``extractiveness.'' They found a similar result to ours, that high $n$-gram\ overlap (``copying'') corresponded to low entropy in the decoder's output distribution when the model was trained on CNN/DailyMail.% \footnote{Their findings are more difficult to interpret when trained on XSum, partially due to the lack of an explicit extractive/abstractive summarization switch in their models.} Their findings suggest that our results likely generalize to a much broader class of summarization models than the pointer-generator models studied here. Finally, \citet{liu2010exploring} found that ROUGE metrics poorly correlate with human evaluations, leading to recent models being evaluated with human judgements, but these evaluations often disagree on what they are measuring, whether it is faithfulness, informativity, or the unqualified ``quality'' of a summary \cite{zhang2018abstractiveness, zhang2020pegasus, dou2020gsum}. Developing best practices on how abstractive summarizers should be evaluated for their paraphrasing ability is another problem we leave for future work. \section{Conclusion} In this paper, we presented three experiments that evaluate the abstraction capabilities of the pointer-generator neural summarization model. Our results conclude that on extractive training data, the model uses only simple paraphrasing strategies that truncate sentences at syntactic boundaries, allowing the model to stay grammatically accurate as well as faithful to the source document. We explore two ways to make the model use abstractive summarization strategies: modifying the model so that it relies more heavily on its abstractive component, and training a new model on an abstractive-biased dataset. In both cases, the model shows simple paraphrasing capabilities but frequently generates unfaithful paraphrases. These results highlight current limitations of abstractive summarization, where in lieu of semantic understanding, models must rely on extractive heuristics in order to stay faithful. \section*{Acknowledgements} We thank our reviewers for their helpful suggestions. We also thank Esin Durmus, Ryan Benmalek, and Claire Cardie for helpful discussions about abstractive summarization. Finally, we thank Shashi Narayan and Shay Cohen for helping us reproduce their pointer-generator model trained on XSum. \bibliographystyle{acl_natbib}
{'timestamp': '2021-06-04T02:10:10', 'yymm': '2106', 'arxiv_id': '2106.01581', 'language': 'en', 'url': 'https://arxiv.org/abs/2106.01581'}
arxiv
\section{Context Enrichment} \label{sec:applications} In this section, we define context enrichment, and provide example workloads that can be framed as a form of context enrichment. \subsection{Problem Statement} \label{subsec:problem} Structured data, or data that adheres to a fixed schema formatted in rows and columns, suffers from context fragmentation. We broadly define structured data to include semi-structured and textual data sources that may be stored and keyed in data management systems, such as content from Wikipedia articles or web search results. Unlike unstructured data, structured data follows a scattered format that is efficient to store, query, and manipulate for specific business needs. This may be in the form of an e-commerce company storing datasets cataloging products and user reviews as in Figure~\ref{fig:example}. To use this fragmented data for ML tasks, practitioners implicitly or explicitly join these dataset to construct discriminative features. We refer to this joining process as \emph{context enrichment}, which we define as follows: Given a base dataset in tabular form, $D_0$, context enrichment aligns $D_0$ with context derived from auxiliary data sources, $D = \{D_1, ... , D_M\}$, to solve a task $T$. We focus on a text-based, two-dataset case ($|D| = 1$), but propose means for multi-dataset extension Sections~\ref{sec:preprocessing}-\ref{sec:joining}, and defer their evaluation to future work. We explore context enrichment in regimes with abundant and limited labeled relevant pairs $Y$ to learn source alignment. We represent each dataset $D_i$ as an $\mathbf{n_i}\times\mathbf{d_i}$ matrix of $\mathbf{n_i}$ data points (or records) and $\mathbf{d_i}$ columns. We denote $C_{ir}$ as the $r^{th}$ column in dataset $i$. We denote $d_{ij}$ as the $j^{th}$ row in dataset $i$. Columns are numeric or textual, and we refer to the domain of $d_{ij}$ as $\mathbf{D_i}$. \eat{Each dataset $D_i$ consists of $\mathbf{d_i}$ columns, each of which we denote as $C_{ir}$, where $r \in \{1, ...,\mathbf{d_i}\}$. Columns are either numeric or textual, meaning $C_{ir} \in X^{{n_i}}$, where $X \in \{\mathbb{R} \cup \mathbb{N}\}$ and $n_i$ is the number of records in dataset $D_i$. Data points in each dataset are represented as $d_{ij}$ for the $j^{th}$ row in dataset $i$, where $j \in \{1, ...,n_i\}$ and $d_{ij} \in X^{\mathbf{d_i}}$. We describe how to extend beyond these formats in Section~\ref{sec:representation}. } Our goal is to \emph{enrich}, or identify all context for, each $d_{0j}$ in $D_0$: auxiliary records $d_{lm}$ ($l \neq 0$) that are related to $d_{0j}$, as per task $T$. \subsection{Motivating Applications} \label{subsec:target} Context enrichment is a key component for applications across a broad array of domains. Thus, a context enrichment system would reduce the developer time and effort needed to construct domain-specific pipelines. We now describe a subset of these domains, which we evaluate in Section~\ref{sec:eval}. Additional applicable domains include entity linkage or disambiguation~\citep{link2,link1}, nearest neighbor machine translation~\citep{knnmt}, and nearest neighbor language modeling~\citep{knnlm}. \minihead{Entity Matching and Deduplication} Entity matching identifies data points that refer to the same real-world entity across two different collections of entity mentions~\citep{matchsurvey}. An entity denotes any distinct real-world object such as a person or organization, while its entity mention is a reference to this entity in a structured dataset or a text span. Entity deduplication identifies entities that are found multiple times in a single data source, thus is a special case of entity matching where both collections of entity mentions are the same. \vspace{4pt} \noindent We frame entity matching as a context enrichment problem where $D_0$ and $D_1$ represent the two collections of entity mentions. Context enrichment aligns entities $d_{1m}$ in the auxiliary dataset $D_1$ with each entity $d_{0j}$ in the base dataset $D_0$. In entity deduplication, $D_0 = D_1$. The downstream task $T$ is a binary classifier over the retrieved relevant records, as the aim is to identify matching entities. \eat{ \minihead{Entity Linking or Disambiguation} Entity linking, or named entity disambiguation, joins entity mentions (as defined above) in the form of a text span to a canonical entity in a database or knowledge graph~\citep{link1,link2}. Entity linkage differs from entity matching in that it has access to relationship information across entities. \vspace{3pt} \noindent We frame entity linkage as a context enrichment problem where $D_0$ and $D_1$ represent the collection of entity mentions and a database or linearized representation of the knowledge graph, respectively. Context enrichment aligns entities $d_{1m}$ in the auxiliary dataset $D_1$ that map to each entity $d_{0j}$ in the base dataset $D_0$. The downstream task $T$ is a binary classifier over the retrieved relevant records, as the aim is to identify matching entities. \\ } \minihead{Fuzzy Joining} A fuzzy join identifies data point pairs that are similar to one another across two database tables, where similar records may be identified with respect to a similarity function (e.g., cosine similarity, Jaccard similarity, edit distance) and threshold~\citep{fj1,surajit} defined over a subset of key columns. Though related to entity matching, fuzzy joins can be viewed as a primitive used to efficiently mine and block pairs that are similar across the two data sources. \vspace{4pt} \noindent We frame fuzzy joining as a context enrichment problem where $D_0$ and $D_1$ represent the two database tables. We let $C_0$ and $C_1$ denote the set of key columns used for joining. Records $d_{0j}$ and $d_{1m}$ are joined if their values in columns $C_0$ and $C_1$ are similar, to some threshold quantity. This is equivalent to a generic context enrichment task with a limited number of features used. The downstream task $T$ is a top-k query, as the aim is to identify similar entities. \minihead{Recommendation} A recommender system predicts the rating that a user would give an item, typically for use in content recommendation or filtering~\citep{recsys}. We also consider the broader problem of uncovering the global rating for an item, as in the e-commerce example in Figure~\ref{fig:example}, as being a form of recommendation problem---namely, the global score may be predicted by aggregating the predicted per-user results obtained via classic recommender systems. \vspace{4pt} \noindent We frame such recommendation workloads as a context enrichment problem where $D_0$ represents all information regarding the entity to be ranked (e.g., a base product table, or new candidate products), and $D_1$ represents the information of the rankers, or other auxiliary data (e.g., catalogs of previously ranked products). Context enrichment aligns rankers $d_{1m}$ in the auxiliary dataset $D_1$ with those that are related to each entity to be ranked $d_{0j}$ in the base dataset $D_0$. The downstream task $T$ is to return the top-1 query, or to perform aggregation or train an ML model over the returned top-k entries. \minihead{Search} An enterprise search engine returns information relevant to a user query issued over internal databases, documentation, files, or web pages~\citep{enterprise1, enterprise2}. A general web retrieval system displays information relevant to a given search query~\citep{search1,search2}. Both rely on information retrieval techniques and relevance-based ranking over an underlying document corpus as building blocks to develop complex, personalized pipelines, or for retrospective analyses~\citep{marco}. \vspace{4pt} \noindent We frame retrieval and ranking in search as a context enrichment problem where $D_0$ represents the set of user queries, and $D_1$ represents the underlying document corpus. Context enrichment aligns documents $d_{1m}$ in the auxiliary dataset $D_1$ that map to each query $d_{0j}$ in the base dataset $D_0$. The downstream task $T$ is to return the top-k documents for each query, sorted by their query relatedness. \minihead{Question Answering} Question answering systems answer natural language questions given a corresponding passage (e.g., in reading comprehension tasks) or existing knowledge source (e.g., in open domain question answering)~\citep{squad,qa}. Multi-hop question answering generalizes this setting, where the system must traverse a series of passages to uncover the answer~\citep{multihop}. For instance, the question "what color is the ocean?" may be provided the statements "the sky is blue" and "the ocean is the same color as the sky." \vspace{4pt} \noindent We frame the retriever component~\citep{retriever} of a classic retriever-reader model in open domain question answering as a context enrichment problem. Our task is to identify the candidate text spans in the provided passages that contain the question's answer (the retriever component), and a downstream reader task can formulate the answer to the question. We let dataset $D_0$ represent the set of questions, and $D_1$ represent the provided passages or knowledge source, split into spans (e.g., based on sentences, or fixed word windows). Context enrichment aligns spans $d_{1m}$ in the auxiliary dataset $D_1$ that contain the answer to each question $d_{0j}$ in the base dataset $D_0$. Multi-hop question answering requires an extra round of context enrichment for each hop required. Each round selects a different passage's spans as the base table $D_0$; to identify context relevant to the question, the user can traverse the related spans extracted from each passage. The downstream task $T$ is to learn a reader model to answer questions using the enriched data sources. \eat{ \minihead{Machine Translation} \red{Do the nearest neighbor MT or LM warrant adding?} } \section{Conclusion} \label{sec:conclusion} We demonstrate how seemingly unrelated tasks spanning data integration, search, and recommendation can all be viewed as instantiations of context enrichment. We propose keyless joins as a unifying abstraction that can power a system for general context enrichment, which allows us to view context enrichment as a data management problem. Consequently, we developed and applied \textsc{Ember}\xspace, a first-of-its kind system that performs no-code context enrichment via keyless joins. We evaluate how developing a keyless join enrichment layer empowers a single system to generalize to five downstream applications, with no ML code written by the user. \section{Introduction} Machine learning (ML) systems that extract structural and semantic context from unstructured datasets have revolutionzed domains such as computer vision~\citep{alexnet} and natural language processing~\citep{bert,gpt2}. Unfortunately, applying these sytems to structured and semi-structured data repositories that consist of datasets with pre-defined schemas is challenging as their context is often \textit{fragmented}: they frequently scatter information regarding a data record across domain-specific datasets with unique schemas. For instance, in Figure~\ref{fig:example}B, information regarding \textsc{Asics} shoes is scattered across three catalogs with unique schemas. These datasets adhere to fixed schemas that are optimized for task-specific querying, and often lack explicit linking keys, such as primary key-foreign key (KFK) relationships. This constrains users to a single view of an entity that is specialized for a specific business need. \begin{figure} \includegraphics[width=\columnwidth]{figures/tables.pdf} \caption{An end-to-end task requiring context enrichment. Predicting the rating of and recommending a new product (\texttt{A82}), requires relating the Asics products (highlighted in dark gray) via a keyless join (top). This process is manual due to data heterogeneity---we aim to automate it (bottom).} \label{fig:example} \vspace{-1em} \end{figure} Associating these fragmented data contexts is critical in enabling ML-powered applications over such datasets---a process we denote as \emph{context enrichment}---yet is a heavily manual endeavor due to task and dataset heterogeneity. Engineers develop solutions for context enrichment tailored to their task, such as similarity-based blocking in data integration~\citep{blocking}, retriever models in question answering~\citep{retriever}, or retrieval functions in search~\citep{bm25} (see Section~\ref{sec:applications}). Constructing these independent solutions is repetitive, time-consuming, and results in a complicated landscape of overlapping, domain-specific methods. For instance, consider the scenario depicted in Figure~\ref{fig:example}: \vspace{-7pt} \emph{\\An e-commerce company has a proprietary product catalog, and aggregates product information from several external vendors to perform market analysis. Each vendor uses a unique product catalog, each with unique product representations (i.e., schema) ranging from free-form text to tabular product descriptions; products may overlap and evolve (Figure~\ref{fig:example}B). Given normalized tables containing user and rating data, an engineer wishes to estimate the rating for a candidate new product (\texttt{A82}) and identify users to recommend the product to (Figure~\ref{fig:example}A). } \vspace{5pt} The engineer must first perform context enrichment by joining information across tables to extract features that capture similarities between the new (\texttt{A82}) and existing (\texttt{A80}, \texttt{P8}) products. They can then estimate the product rating, and recommend the new product to users based on how they rated related products. The classic data management approach is to denormalize datasets using KFK joins. This fails to solve the problem due to two reasons. First, not all tables can be joined when relying on only KFK relationships (e.g., there is no KFK relationship between Catalog B and Catalogs A or C). Second, even when KFK relationships exist, as between Catalogs A and C (\textsc{\texttt{ITEM}}), relying on only KFK semantics fails to capture the similarity between \texttt{A82} and \texttt{A80}. Alternatively, the engineer can rely on similarity-based join techniques, as in data blocking~\citep{blocking}, built to avoid exhaustive, pairwise comparison of potentially joinable records. However, as we show in Section~\ref{subsec:general}, the optimal choice of join operator to maximize recall of relevant records is task-dependent, and may not scale at query time when new records arrive. The engineer must first note that the \texttt{Description} column in Catalog A relates to the \texttt{Brand} and \texttt{Model} columns in Catalog B and the \texttt{Size}, \texttt{Make}, and \texttt{Color} columns in Catalog C. They can then select a custom join based on table properties: for matching primarily short, structured data records, they may want to join based on Jaccard similarity, whereas BM25 may be better suited for purely textual records (see Table~\ref{tab:baselines}). As database semantics do not natively support these \emph{keyless joins} that require similarity-based indexing, joining arbitrary catalogs remains heavily manual---even large companies rely on vendors to categorize listings, which results in duplicate listings.\footnote{https://sell.amazon.com/sell.html} To counter this manual process, we draw inspiration from recent no-code ML systems such as Ludwig~\citep{ludwig}, H20.ai~\citep{h20}, and Data Robot~\citep{robot} that are rapidly shifting practitioners towards higher-level configuration-based abstractions for developing ML applications. Despite their success, these systems leave context enrichment as a user-performed data preparation step.\footnote{https://cloud.google.com/automl-tables/docs/prepare} In this paper, we evaluate how to bring no-code semantics to context enrichment. No out-of-the-box query interface surfaces the relatedness between \texttt{A80}, \texttt{A82}, and \texttt{P8} (all \texttt{Asics}, two \texttt{GT-1000}, and two \texttt{blue}), and links these records to the Ratings table with minimal intervention. The challenge in developing a no-code context enrichment system to enable this is to construct an architecture that is simultaneously: \begin{enumerate} \item \textbf{General}: Applicable to a wide variety of tasks and domains. \item \textbf{Extensibile}: Customizable for domain or downstream needs. \item \textbf{Low Effort}: Usable with minimal configuration. \end{enumerate} Our key insight to enable such a system is to simplify context enrichment by abstracting an interface for a new class of join: a \textit{learned keyless join} that operates over record-level similarity. Just as traditional database joins provide an abstraction layer for combining structured data sources given KFK relationships, we formalize keyless joins as an abstraction layer for context enrichment. We then propose \textsc{Ember}\xspace: a no-code context enrichment framework that implements a keyless join abstraction layer. \textsc{Ember}\xspace creates an index populated with task-specific embeddings that can be quickly retrieved at query time, and can operate over arbitrary semi-structured datasets with unique but fixed schema. To provide generality, \textsc{Ember}\xspace relies on Transformers~\citep{transformers} as building blocks for embedding generation, as they have demonstrated success across textual, semi-structured, and structured workloads~\citep{picket,tabert,bert,gpt2,neuraldb}. To provide extensibility, \textsc{Ember}\xspace is composed of a modular, three step architecture with configurable operators. To provide ease of use, \textsc{Ember}\xspace can be configured using a simple json-based configuration file, and provides a default configuration that works well across five tasks with a single line change per task. As input, users provide \textsc{Ember}\xspace with: \textbf{(1)} a base data source, \textbf{(2)} an auxiliary data source, \textbf{(3)} a set of examples of related records across the sources. For each record in the base data source, \textsc{Ember}\xspace returns related records from the auxiliary data source as characterized by the examples, which can be post-processed for downstream tasks (e.g., concatenated or averaged). We present \textsc{Ember}\xspace's three-step modular architecture that enables index construction via Transformer-based embeddings to facilitate related record retrieval: preprocessing, representation learning, and joining (Figure~\ref{fig:overview}). \eat{ \begin{enumerate} \item A base data source \item An auxiliary data source \item A set of examples of related records across the sources \end{enumerate} } \minihead{Preprocessing} \textsc{Ember}\xspace transforms records from different data sources to a common representation, which allows us to apply the same methods across tasks. By default, \textsc{Ember}\xspace uses operators that convert each record to a natural language sentence for input to a Transformer-based encoder, which we optionally pretrain using self-supervision. We demonstrate that depending on the data vocabulary, encoder pretraining to bootstrap the pipeline with domain knowledge can increase recall of relevant records by up to \red{20.5\%}. \begin{figure} \includegraphics[width=\columnwidth]{figures/overview.pdf} \caption{\textsc{Ember}\xspace's interface for context enrichment. \textsc{Ember}\xspace retrieves related auxiliary records for each base record.} \label{fig:overview} \vspace{-1em} \end{figure} \minihead{Representation Learning} \textsc{Ember}\xspace tunes the preprocessed representations to identify contextually similar records as defined by supervised examples. Learning this representation is task-dependent: we show that a natural approach of using pretrained Transformer-based embeddings with no fine-tuning performs up to three orders of magnitude worse than a fine-tuned approach, often returning less than \red{10\%} of relevant records. Pretraining in the first step can increase recall by over \red{30\%}, but this is still insufficient. Thus, \textsc{Ember}\xspace relies on operators that use supervised examples of related records and a contrastive triplet loss~\citep{tripletloss} to learn a representation that encourages similar records to be close while pushing away dissimilar records in the induced embedding space. We evaluate how many labeled examples \textsc{Ember}\xspace needs to match the performance of using all provided examples, and find that at times, \red{1\%} of the labels is sufficient, and that operators for hard negative sampling improve performance by up to \red{30\%} recall, further improving ease of use. \minihead{Joining} \textsc{Ember}\xspace quickly retrieves related records using the tuned representations to perform the keyless join. \textsc{Ember}\xspace populates an index with the embeddings learned to capture record similarity, and uses optimized maximum inner product search (MIPS) to identify the nearest neighbors of a given record. This procedure allows \textsc{Ember}\xspace to capture one-to-one and one-to-many join semantics across a variety of downstream applications with low query-time overhead. We demonstrate that \textsc{Ember}\xspace meets or exceeds the performance of eight similarity-based join baselines including BM25~\citep{bm25}, Jaccard-similarity-based joins, Levenshtein distance-based joins, and AutoFuzzyJoin~\citep{autofj} with respect to recall and query runtime. Although conventional wisdom in data management often says to rely on domain-specific pipelines for context enrichment, we introduce no-code ML semantics to context enrichment and empirically show how a single system can generalize to heterogeneous downstream tasks. We report on our experiences in deploying \textsc{Ember}\xspace across five tasks: fuzzy joining, entity matching, question answering, search, and recommendation. We demonstrate that \textsc{Ember}\xspace generalizes to each, requires as little as a single line configuration change, and extends to downstream similarity-based analyses for search, entity matching, and recommendation as in Figure~\ref{fig:example}. In summary, we present the following contributions in this paper: \begin{itemize} \setlength\itemsep{.75em} \item We propose keyless joins with a join specification to serve as an abstraction layer for context enrichment. To our knowledge, this is the first work to generalize similarity-based tasks across data integration, natural language processing, search, and recommendation as a data management problem. \item We design and develop \textsc{Ember}\xspace, the first no-code framework for context enrichment that implements keyless joins, and provides an API for extending and optimizing keyless joins. \item We empirically demonstrate that \textsc{Ember}\xspace generalizes to five workloads by meeting or exceeding the recall of baselines while using \red{6} or fewer configuration line changes, and evaluate the modular design of \textsc{Ember}\xspace's default architecture. \end{itemize} \section{Learned Keyless Joins for Context Enrichment} Although the applications in Section~\ref{sec:applications} implicitly or explicitly perform the \emph{same} context enrichment, many state-of-the-art systems for these tasks re-implement and rediscover primitives across domains spanning machine learning, databases, information retrieval, and natural language processing~\citep{colbert,ditto,knnlm,rpt}. We propose learned \textit{keyless joins} as an abstraction to unify context enrichment across these tasks and provide a vehicle to develop a no-code system with out-of-the-box recall exceeding na\"ive baselines. In this section, we define keyless joins, provide a keyless join API specification, and introduce Transformer models that enable general keyless joins. \subsection{Keyless Joins: Definition and Objective} \label{subsec:keyless} Context enrichment requires a similarity-based join that operates at the record-, not schema-, level to retrieve related records without primary key-foreign key (KFK) relationships. We propose learned \emph{keyless joins} as an abstraction to enable this functionality. The goal of a keyless join is to quantify the relatedness of records across different datasets to identify records referring to similar entities. A keyless join must learn a common embedding space $\mathbf{X}$ for all records $d_{ij}$ across datasets $D_0 \cup D$ that reflects entity similarity. For each $\mathbf{D_i}$, a keyless join learns a function $F_i: \mathbf{D_i} \rightarrow \mathbf{X}$ that maps elements of $D_i$ to the space $\mathbf{X}$. We denote each transformed data point $F_i(d_{ij})$ as $x_{ij}$. This mapping must be optimized such that related values map to similar feature vectors in $\mathbf{X}$ and unrelated values map to distant feature vectors in $\mathbf{X}$: $sim(x_{ij}, x_{kl}) > sim(x_{ij}, x_{mn})$ implies that the $j^{th}$ entity in the $i^{th}$ dataset is more closely related to the $l^{th}$ entity in the $k^{th}$ dataset than the $n^{th}$ entity in the $m^{th}$ dataset. For instance, if we define similarity with respect to an $\ell_p$-norm, the above condition is equal to optimizing for $\|x_{ij} - x_{kl}\|_p < \|x_{ij} - x_{mn}\|_p$. \begin{figure*} \includegraphics[width=\linewidth]{figures/full_pipeline.pdf} \caption{\textsc{Ember}\xspace system architecture.} \label{fig:pipeline} \end{figure*} \subsection{Join Specification for Context Enrichment} \label{subsec:keyless_spec} We propose a minimal join specification for our applications using keyless joins as a building block (Listing~\ref{listing:spec}). Given a pair of data sources to join (\texttt{base\_table\_ref}, \texttt{aux\_table\_ref}), and examples of similar records across them (\texttt{supervision}), users first specify the \texttt{join type}: an inner join to only return enriched records, or outer join (left, right, full) to return enriched and unenriched records. Users then specify the \texttt{join size}: how many records from one data source joins to a single record in the other data source to indicate one-to-one, one-to-many, or many-to-many semantics. As output, joined tuples (matches) between the two tables are the most similar records across them as learned using the keyless join objective. Results are ranked in order of greatest entity similarity, and the top k results are returned based on \texttt{join size}. \eat{ \begin{listing}[t] \small \begin{minted}{python} base_table_ref [join_type] "KEYLESS JOIN" aux_table_ref "LEFT SIZE" integer "RIGHT SIZE" integer "USING" supervision; join_type = "INNER" | "LEFT" | "RIGHT" | "FULL"; \end{minted} \caption{Keyless join specification and syntax, which defaults to an inner join.} \label{listing:spec} \end{listing} } \begin{lstlisting}[frame=single,caption={Keyless join specification (inner join default).},captionpos=b,float=t,label={listing:spec}, language=Python,commentstyle=\textcolor{teal},stringstyle=\dred,showstringspaces=false,belowskip=-2pt] base_table_ref [join_type] "KEYLESS JOIN" aux_table_ref "LEFT SIZE" integer "RIGHT SIZE" integer "USING" supervision; join_type = "INNER" | "LEFT" | "RIGHT" | "FULL"; \end{lstlisting} For instance, an entity matching application is written as follows to retrieve a single matching record between each data source: \vsepfbox{% \parbox{.975\linewidth}{% \small{\texttt{% entity\_mentions\_A \dred{INNER KEYLESS JOIN} entity\_mentions\_B \\ \dred{LEFT SIZE} 1 \dred{RIGHT SIZE} 1 \dred{USING} matching\_mentions; }} }% } \eat{\texttt{ \dred{entity\_mentions\_A} INNER KEYLESS JOIN \dred{entity\_mentions\_B} LEFT SIZE \dred{1} RIGHT SIZE \dred{1} }} A search application is written as follows to retrieve 10 documents for each search query, else return the unenriched query: \\ \vsepfbox{% \parbox{.975\linewidth}{% \small{\texttt{% query\_corpus \dred{LEFT KEYLESS JOIN} document\_corpus \\ \dred{LEFT SIZE} 1 \dred{RIGHT SIZE} 10 \dred{USING} relevant\_docs\_for\_query; }} }% } A recommendation application is written as follows to retrieve 10 items for each user, and 20 users who like each item: \\ \vsepfbox{% \parbox{.975\linewidth}{% \small{\texttt{% user\_database \dred{INNER KEYLESS JOIN} product\_database \\ \dred{LEFT SIZE} 20 \dred{RIGHT SIZE} 10 \dred{USING} relevant\_docs\_for\_query; }} }% } In the remainder of paper, we describe our prototype system that implements this keyless join abstraction layer for enrichment. \subsection{Background: Transformer-Based Encoders} \label{subsec:transformer} Our main tools for creating a representation optimized for the objective in Section~\ref{subsec:keyless} are Transformers~\citep{transformers}, as they have demonstrated success across a range of structured, semi-structured, and unstructured domains~\citep{tabert,bert,gpt2,neuraldb,picket}. They consist of an encoder-decoder architecture, where the Transformer first encodes the input to an intermediate representation, and then decodes this representation to produce the end output. Stacking encoder (e.g., BERT~\citep{bert}) or decoder (e.g., GPT-2~\citep{gpt2}) modules allows us to learn high-quality word embeddings that can either be used for a wide array of downstream applications. We focus on BERT-based embeddings. BERT embeddings used for a downstream task are trained in a two-step procedure. The first step is self-supervised pretraining using a masked language model (MLM) objective: a random subset of tokens are masked, and the model must predict each masked token given the surrounding text as context. Pretraining is performed with general purpose corpora such as Wikipedia. The second step is task-specific fine-tuning. Additional layers are appended to the final layer of the pretrained model based on the downstream task, and all model parameters are updated given small amounts of downstream supervision. Rather than relying solely on fine-tuning, an additional MLM pretraining step can be performed prior to fine-tuning to introduce additional domain knowledge. \section{Evaluation} \label{sec:eval} In this section, we demonstrate that \textsc{Ember}\xspace and its operators are: \begin{enumerate} \item \textbf{General}: \textsc{Ember}\xspace enables context enrichment across five domains while meeting or exceeding similarity-join baseline recall and query runtime performance (Section~\ref{subsec:general}). \item \textbf{Extensible}: \textsc{Ember}\xspace provides a modular architecture, where each component affects performance (Section~\ref{subsec:micros}). \textsc{Ember}\xspace enables task-specific pipelines for various similarity-based queries, and provides task performance that can be fine-tuned by state-of-the-art systems (Section~\ref{subsec:extensibility}). \item \textbf{Low Effort}: \textsc{Ember}\xspace requires no more than five configuration changes (Table~\ref{table:datasets}) from its default, and does not always require large amounts of hand-labeled examples (Section~\ref{subsec:easy}). \end{enumerate} \input{tables/datasets} \subsection{Evaluation Metric and Applications} \minihead{Context Enrichment Evaluation Metric} Context enrichment identifies related records across a base and auxiliary dataset. We can view related records between the two datasets as forming edges in a bipartite graph: each record in each dataset represents a vertex in the graph. Under this framing, a context enrichment system must retrieve all of the outgoing edges (i.e., related records) for each record in the base dataset. This is equivalent to maximizing record-level recall, or the fraction of records for which we recover \emph{all} related records. We choose to define recall at the record-level, rather than the edge-level, as we view context enrichment systems as being repeatedly queried for new incoming data once instantiated. A na\"ive means to optimize for recall is to return \textit{all} auxiliary records as being related to each record in the base dataset. A precision metric greatly drops when we retrieve multiple records. Thus, our evaluation metric is \textbf{recall@k}, for small k (i.e., \texttt{join size}). \minihead{Applications} We evaluate \textsc{Ember}\xspace against workloads from five application domains: fuzzy joining, entity matching, search, question answering, and recommendation (summarized in in Table~\ref{table:datasets}). We make all our datasets publicly available post-\textsc{Ember}\xspace processing. \subsubsection{Fuzzy Join (FJ)} We build two workloads using a dataset and generation procedure from a 2019 scalable fuzzy join VLDB paper~\citep{surajit}. The first dataset consists of the Title, Year, and Genre columns from IMDb~\citep{imdb}. The second dataset is generated by perturbing each row in the first by applying a combination of token insertion, token deletion, and token replacement. The task $T$, is to join each perturbed row with the row that generated it. We generate two dataset versions: 5 perturbations per row (IMDb) and 15 perturbations per row (IMDb-hard), up to 25\% of the record length. As we focus on generalizablity more than scalability, to form a dataset, we randomly sample 10,000 movies and generate 5 perturbed rows for each. We hold out 20\% of records as the test set; no records from the same unperturbed record are in both the train and test sets. \subsubsection{Entity Matching (EM)} We use all 13 benchmark datasets~\citep{dmdata} released with DeepMatcher~\citep{deepmatcher}, spanning structured (EM-S), textual (EM-T), and dirty (EM-D) entity matching. The base and auxiliary datasets always share the same schema. In EM-T, all data records are raw text entries or descriptions. In EM-S, each data record is drawn from a table following a pre-defined schema, where text-based column values are restricted in length. In EM-D, records are similar to EM-S, but some column values are injected into the incorrect column. The task $T$ is to label a record pair (one from each dataset) as representing the same entity or not. Train, validation, and test supervision are lists of unrelated, and related pairs---we only use the related pairs for training \textsc{Ember}\xspace, as we identified mislabeled entries (false negatives) when using \textsc{Ember}\xspace to explore results. \subsubsection{Search (S)} We use the MS MARCO passage retrieval benchmark~\citep{marco}. MS MARCO consists of a collection of passages from web pages that were gathered by sampling and anonymizing Bing logs from real queries~\citep{marco}. The task $T$ is to rank the passage(s) that are relevant to a given query as highly as possible. Supervision is a set of 397M triples, with 1 relevant and up to 999 irrelevant passages for most queries. Irrelevant passages are retrieved via BM25. We report results over the publicly available labeled development set. \subsubsection{Question Answering (QA)} We modify the Stanford Question Answering Dataset (SQuAD)~\citep{squad}. SQuAD consists of Wikipedia passages and questions corresponding to each passage. The task $T$ is to identify the beginning of the text span containing the answer to each question. As described in Section~\ref{sec:applications}, a retriever module, used in retriever-reader models for QA~\citep{retriever}, performs context enrichment. We modify SQuAD by splitting each each passage at the sentence-level, and combining these sentences to form a new dataset. The modified task is to recover the sentence containing the answer \subsubsection{Recommendation (R)} We construct a workload using IMDb and Wikipedia to mimic the e-commerce example from Figure~\ref{fig:example}. For the first dataset, we denormalize four IMDb tables using KFK joins: movie information (title.basics), principal cast/crew for each movie (title.principals) and their information (name.basics), and movie ratings (title.ratings)~\citep{imdb}. For the second dataset, we extract the summary paragraphs of the Wikipedia entry for each IMDb movie by querying latest Wikipedia snapshot; we extract 47813 overlapping records~\citep{wiki}. We remove the IMDb ID that provides a KFK relationship to induce a need for keyless joins. We construct this workload to enable two applications. In Application A, we show that \textsc{Ember}\xspace can join datasets with dramatically different schema. In Application B, we show how to estimate the rating for movies in the test set given ratings for the train set by performing similarity-based analyses enabled by \textsc{Ember}\xspace. Supervision is provided as exact matches and movie ratings with an 80-20 train-test set split. \input{tables/baselines} \eat{\minihead{Evaluation Metrics} We evaluate all EM workloads with respect to F1 score, as is standard in existing work~\citep{deepmatcher,ditto}. For the remainder of the workloads, we report MRR@k and Retrieval@k for k = 1, 10. MRR@k refers to the average of the multiplicative inverse of the rank of the first relevant item in the top k ranked items, and is an information retrieval standard~\citep{marco}. We define Retrieval@k to be the percentage of the test set whose true match is present in the top-k returned nearest neighbors by the \texttt{retriever}\xspace. We report Retrieval@k as a modification of Recall@k, to reflect that we are only looking for a single match in these join scenarios. MRR@1 is equivalent to Retrieval@1.} \subsection{Experimental Setup} \label{sec:setup} \minihead{Baselines} We first evaluate all workloads compared to seven similarity-based joins with respect to recall@1 and recall@10. Our baselines are joins using Levenshtein distance, four variations of Jaccard Similarity, BM25, Auto-FuzzyJoin~\citep{autofj}, and a pretrained embedding-based approach. We evaluate downstream EM and search workloads with respect to previously reported state-of-the-art and benchmark solutions~\citep{deepmatcher,deeper,ditto,marcohomepage,bertmarco}. The remainder of our workloads were constructed to isolate context enrichment from the downstream task, and do not have standard baselines. \minihead{\textsc{Ember}\xspace Default Configuration} Tasks use a \texttt{sentence}\xspace \texttt{preparer}\xspace, and perform 20 epochs of self-supervised pretraining. \textsc{Ember}\xspace uses a single DistilBERT$_{\text{base}}$ \texttt{encoder}\xspace trained with a triplet \texttt{loss}\xspace and \red{stratified} hard negative \texttt{sampler}\xspace. Self-supervision and the \texttt{sampler}\xspace use BM25 to identify similar \texttt{sentence}s\xspace to concatenate from each data source, and to mark as hard negatives, respectively. The output \texttt{embedding}\xspace size is 200, and models are trained with a batch size of 8 using an ADAM optimizer~\citep{adam} with initial learning rate of $1\mathrm{e}{-5}$. The default \texttt{join sizes} are 1 and 10. Results are five-trial averages. \minihead{Implementation} We use a server with two Intel Xeon Gold 6132 CPUs (56 threads) with 504GB of RAM, and four Titan V GPUs with 12GB of memory. We implement \textsc{Ember}\xspace in Python and PyTorch~\citep{pytorch}, with pretrained models and tokenizers from HuggingFace Transformers~\citep{hf}. We use Faiss for MIPS~\citep{faiss}, Magellan for similarity join baselines~\citep{magellan}, rank-BM25 for BM25~\citep{bm25_code}, and AutoFuzzyJoin~\citep{autofj}. \subsection{Generalizability} \label{subsec:general} We show that \textsc{Ember}\xspace's recall and runtime meets or outperforms that of the following similarity-join baselines in nearly all tasks: \minihead{Levenshtein-Distance (LD)} LD is the number of character edits needed to convert one string to another. This join returns the closest records with respect to single-character edits over provided key columns. We filter and only return results under a 30 edit threshold. \minihead{Jaccard-Similarity, Specified Key (JK-WS, JK-2G)} The Jaccard similarity between sets $A$ and $B$ is $J(A, B) = \frac{|A\cap B|}{|A \cup B|}$. Defining a Jaccard-similarity based join over textual inputs requires tokenizer selection. We consider a whitespace tokenizer (WS) and a 2-gram tokenizer (2G) to capture different granularities. JK-WS and JK-2G return the closest records with respect to Jaccard similarity over provided key columns using a WS or 2G tokenizer. We set a filtering threshold to return results with at least 0.3 Jaccard similarity. \minihead{Jaccard-Similarity, Unspecified Key (J-WS, J-2G)} J-WS and J-2G return the closest records with respect to Jaccard similarity using a WS or 2G tokenizer, after a \texttt{sentence}\xspace \texttt{preparer}\xspace. We set a filtering threshold to return results with over 0.3 Jaccard similarity. \minihead{BM25 (BM25)} BM25 is a bag-of-words ranking function used in retrieval~\citep{bm25}. This join returns the closest records with respect to the Okapi BM25 score using default parameters k1=1.5 and b=0.75. \minihead{Pretrained-Embedding (BERT)} BERT generates embeddings for each prepared \texttt{sentence}\xspace via a pretrained DistilBERT$_{\text{base}}$ model, and returns the closest records based on the $\ell_2$-norm between them. \red{\minihead{Auto-FuzzyJoin (AutoFJ)} AutoFJ automatically identifies join functions for unsupervised similarity joins~\citep{autofj} by assuming one input is a "reference table" with few or no duplicates, which does not always hold in context enrichment. If duplicates are present, or records in the reference table are not sufficiently spread, precision estimation may break down (\textsc{Ember}\xspace trivially accounts for these scenarios). AutoFJ optimizes for a precision target, and does not expose any \texttt{join size} semantics. We find a single result is typically returned per record, so we only consider recall@1 at a low precision target of 0.5. We comment on workloads that completed in 1.5 days on our machines using all cores. As AutoFJ exhaustively computes record similarities for each considered join configuration, this means we omit results for MS MARCO, EM-T Company, EM-S BeerAdvo-RateBeer, and several others consisting of large text spans, or where blocking may not be as effective. Users must manually align \emph{matching} columns, which do not always exist thus ignore information in our tasks (e.g., IMDb-wiki): as input, we pass the output of a \texttt{sentence}\xspace \texttt{preparer}\xspace if column names are not identical. } \\ \noindent For multi-column datasets, we provide a plausible key column if the method requires. In FJ, EM, and R, this is a title or name column. \subsubsection{Retrieval Quality} We show that \textsc{Ember}\xspace is competitive with or exceeds the best performing alternatives with respect to Recall@1 and Recall@10 (Table~\ref{tab:baselines}). In both tables, we highlight the methods that are within 1\% of the top performing method. No method dominates the others across the different workloads, while BERT underperformed all alternatives. Broadly, character-based joins (LD, JK-2G, J-2G) tend to perform well in scenarios where a join key exists but may be perturbed (FJ, EM-S, EM-D); word-based joins (J-WS, BM25) tend to perform well in scenarios with word-level join keys (EM-S), or where a join key does not exist but common phrases still link the two datasets (R, EM-D). Neither performs well otherwise (S, EM-T). \textsc{Ember}\xspace most consistently outperforms or is comparable with alternatives across the tasks: a learned approach is necessary for generalization. The exception is with the synthetic FJ workload that is, by construction, suited for character-based joins. \red{We do not report AutoFJ in Table~\ref{tab:baselines} due to incompleteness. AutoFJ is tailored for the EM and FJ: many-to-one joins with identical schema. Of those completed, \textsc{Ember}\xspace is sometimes outperformed by up to 8\% recall@1 (Amazon-Google), but is otherwise comparable or far exceeds AutoFJ when considering recall@10. AutoFJ's recall is 37.9\% for QA, and 38.5\% for R. As AutoFJ over the Wikipedia summary (task R) did not terminate, we only use the title column. } \subsubsection{Query Runtime} Using optimized MIPS routines improved query runtime performance by up to two orders of magnitude. We note that this reflects \textsc{Ember}\xspace joining time, not pretraining and representation learning, which may require several hours. As the two FJ datasets are synthetic and follow identical generation methods, we consider just IMDb-hard. For our largest dataset, MS MARCO (S) with 8.8M auxiliary records, \textsc{Ember}\xspace indexes and retrieves results from the entire corpus, but each baseline only considers each of the up to 1000 relevant records provided by the MS MARCO dataset for each base record. Even when using CPU-only Faiss~\citep{faiss}, \textsc{Ember}\xspace takes \red{7.24} seconds on average for the MIPS-based joining step. Embedding the query table takes \red{24.52} seconds on average. The most expensive dataset with respect to MIPS runtime is MS MARCO (S), which required \red{1.97} minutes when indexing all 8.8M records; excluding it reduces the average to \red{0.31} seconds. For embedding time, this was EM-T Company, requiring \red{3.96} minutes, whose exclusion reduces the average to \red{11.19} seconds. In contrast, the fastest baseline method (JK-WS), took \red{5.02} minutes on average; excluding MS MARCO (\red{79.73} minutes) reduces the average to \red{21.18} seconds. The slowest method (LD), took \red{23.64} minutes on average, with the most expensive dataset, EM-T Company, requiring \red{321.98} minutes. \subsection{Extensibility: Architecture Lesion} \label{subsec:micros} We demonstrate modularity and justify our architectural defaults by evaluating \textsc{Ember}\xspace's performance when modifying components as follows, each of which requires a single line configuration change (all reported percentages are relative unless explicitly specified): \begin{enumerate} \item Replacing MLM pretraining and representation learning (RL) with a pretrained \texttt{encoder}\xspace. \item Removing RL, leaving only MLM pretraining. \item Replacing the fine-tuned Transformer model with a frozen pretrained embedding and a learned dense layer. \item Removing MLM pretraining. \item Random negatives compared to hard negative sampling \item Using an \texttt{encoder}\xspace for each dataset versus a single \texttt{encoder}\xspace. \item Removing the joining index-query optimization. \end{enumerate} \subsubsection{Pretrained \texttt{encoder}\xspace (\textsc{-mlm, rl})} We remove MLM pretraining and RL, and use a pretrained DistilBERT$_{\text{base}}$ encoder---i.e., the same as BERT in Table~\ref{tab:baselines}. We report our results in Figure~\ref{fig:lesion} normalized by \textsc{Ember}\xspace's default. \textsc{Ember}\xspace's performance dramatically declines, sometimes by three orders of magnitude (e.g., recall dropped to 0.04 in R). It is only feasible when the contents of the datasets to be joined are similar, as in certain EM-S and EM-D tasks, and FJ-IMDb. \subsubsection{Removing Representation Learning (\textsc{-rl})} We remove representation learning (RL) and only pretrain an \texttt{encoder}\xspace using the BM25-based MLM procedure from Section~\ref{sec:preprocessing}. We report our results in Figure~\ref{fig:lesion}. \textsc{Ember}\xspace's performance declines by up to an order of magnitude, though it improves performance compared to \textsc{-mlm, rl} on tasks whose datasets do not match the original natural text Wikipedia corpus (e.g., EM-S, FJ). Primarily textual datasets do not see as large an improvement over \textsc{-mlm, rl}, and for QA, where the corpus is derived from Wikipedia, \textsc{-rl} performs slightly worse. \subsubsection{Remove Transformer fine-tuning (\textsc{-ft})} We replace RL with fixed MLM pretrained embeddings followed by a learned fully-connected layer (i.e., we do not fine tune the entire BERT-based \texttt{encoder}\xspace, just the final output layer). We report our results in Figure~\ref{fig:lesion}. Without end-to-end Transformer fine-tuning, \textsc{Ember}\xspace slightly outperforms using just a pretrained encoder (\textsc{-rl}) at times. We primarily observe benefits in text-heavy workloads, where the pretrained encoder provides meaningful representations (QA, S, R, EM-T) without relying on positional information from Transformers. While we do not perform an exhaustive comparison of pretrained embeddings or non-Transformer-based architectures, this shows that \textsc{Ember}\xspace's architecture is a strong out-of-the-box baseline. \subsubsection{Remove MLM Pretraining (\textsc{-mlm})} We eliminate MLM pretraining from the pipeline, and report our results in Figure~\ref{fig:lesion} as \textsc{-mlm}. \textsc{Ember}\xspace meets or exceeds this setting in all but QA, though by a smaller margin than the previous experiments (up to 20.5\% in IMDb-hard). MLM pretraining is not effective for QA as the corpus is drawn from Wikipedia---one of the two corpora BERT was trained with---and both base and auxiliary datasets consist of the same, primarily textual vocabulary. In such cases, users may wish to disable MLM pretraining, although performance is not significantly impacted. In contrast, of the non-EM tasks, MLM pretraining is most helpful for FJ IMDb-hard, where random perturbations result in many records with words that are not in the original vocabulary. \subsubsection{No Negative Sampling (\textsc{-NS})} We replace hard negative sampling with random sampling of unrelated records, and report our results in Figure~\ref{fig:lesion}. Hard negative sampling tends to improve performance by a similar margin as MLM pretraining, and only negatively impacted the EM-T Company dataset (by up to 8.72\% absolute recall). We find larger improvements when the join condition is more ambiguous than recovering a potentially obfuscated join key, as in tasks S (30\% R@1), QA (15\% R@1), and EM-D (15\% R@1). We use BM25-based sampling for all but FJ and QA, where we have prior knowledge, and develop custom samplers based on Jaccard similarity, and sentence origin, respectively. This improved performance over the BM25-based sampler by 1\% absolute recall for FJ, and 8.7\% and 5.6\% absolute recall@1 and recall@10, respectively, for QA. \begin{figure*} \includegraphics[width=\textwidth]{figures/lesion_s.pdf} \caption{Architecture lesion displaying recall@k normalized to the default seen in Table~\ref{tab:baselines} (All) for: a pretrained DistilBERT$_{\text{base}}$ model with no representation learning (\textsc{-mlm,rl}), MLM pretraining with no RL (\textsc{-rl}), RL with no Transformer fine tuning (\textsc{-ft}), RL with no MLM pretraining (\textsc{-mlm}), no hard negative sampling (\textsc{-ns}), and one encoder per dataset (\textsc{te}).} \label{fig:lesion} \end{figure*} \subsubsection{\texttt{encoder}\xspace Configuration (\textsc{te})} We use two \texttt{encoder}s\xspace, one for each dataset, instead of our default single \texttt{encoder}\xspace configuration, and report our results in Figure~\ref{fig:lesion}. We find that using two \texttt{encoder}s\xspace performs up to two orders of magnitude worse than using a single encoder, especially for strictly structured datasets. We observe that through the course of the \texttt{encoder}\xspace training procedure, the performance of using two identically initialized \texttt{encoder}s\xspace often \emph{degrades}---inspecting the resulting embeddings even when running \textsc{Ember}\xspace over two identical tables shows that the exact same terms diverge from one another in the training process. However, we still provide the option to use a distinct encoder for each data source for future extension to non text-based data, such as audio or image. \subsubsection{Index Optimization} For \texttt{INNER} and \texttt{FULL OUTER JOIN}s, we optimize for join execution time by indexing the larger dataset, which reduces the number of queries made by the system. Due to \texttt{encoder}\xspace training, this reflects a small fraction of the end-to-end pipeline execution time at our data sizes, but can be a substantial cost at scale. We evaluate this optimization by running the joining step while indexing the larger dataset, and then the smaller dataset for \emph{all} tasks. On average, this optimization reduces join time by \red{1.76}$\times$, and up to \red{2.81}$\times$. However, this improvement is only meaningful in the MS MARCO workload, saving \red{2.7} minutes. \subsection{Extensibility: End-to-End Workloads} \label{subsec:extensibility} We show how to extend and use \textsc{Ember}\xspace in an end-to-end context. \minihead{Entity Matching} Recent deep-learning-based EM systems focus on the matching phase of that two-part (i.e., blocking and matching) end-to-end EM pipeline~\citep{deeper,deepmatcher,ditto}: given a pair of candidate records, these systems must identify if the pair correspond to the same entity. For end-to-end EM, \textsc{Ember}\xspace must generate candidate blocks with a low rate of false negatives such that it can be efficiently followed by downstream matchers; we verify this in Table~\ref{table:dm_all} (R@10). Perhaps surprisingly, we find that treating \textsc{Ember}\xspace results from a top-1 query as binary classifier achieves performance that is comparable to or better than previous, custom-built state-of-the-art with respect to F1 score. We believe incorporating general operators for data augmentation and domain knowledge integration to enable the custom advances presented in the current state-of-the-art EM system, Ditto, may allow \textsc{Ember}\xspace to entirely bridge this gap~\citep{ditto}. \input{tables/dm} \minihead{Search} In MS MARCO passage ranking, results are ranked in relevance order, and rankings are evaluated via mean reciprocal rank (MRR) of the top 10 results. We rank \textsc{Ember}\xspace results based on their query distance, and compare MRR@10 with existing MS MARCO baselines. We obtain \red{MRR@10 of $0.266$} on the dev set after just 2.5M training examples, outperforming the official Anserini BM25 baseline solution of $0.167$. Our results exceed K-NRM, a kernel based neural model, with a dev set MRR@10 of 0.218~\citep{knrm}, and is slightly below the state-of-the-art from the time, IRNet, with 0.278 MRR@10~\citep{marcohomepage}. For comparison, the first state-of-the-art BERT-based model uses BERT$_\text{large}$ to achieve MRR@10 of 0.365 after training with 12.8M examples~\citep{bertmarco}, and current state-of-the-art is 0.439~\citep{rocketqa}. By developing an additional joining operator, \textsc{Ember}\xspace can implement ColBERT~\citep{colbert}, a previous state-of-the-art method that achieves 0.384 MRR@10 in MS MARCO document ranking that operates on larger input passages: we must remove the pooling step from \textsc{Ember}\xspace's \texttt{encoder}\xspace (1 line config change), and develop a \texttt{retriever}\xspace that indexes and retrieves bags of embeddings for each record. \minihead{Recommendation} In Application B of task R, we estimate the IMDb ratings of movies in the test set given a training dataset and Wikipedia corpus. We report the mean squared error (MSE) between the rating estimates and the true rating. The task is easy: predicting the average training rating returns 1.19 MSE, and a gradient-boosted decision tree (GBDT) over the joined data returns 0.82 MSE. We aim to show extensibility while meeting GBDT performance. There are two approaches to enable this analysis with \textsc{Ember}\xspace by reusing the representation learned for the IMDb-wiki task: similarity defined in a single hop in terms of the labeled training data, or by first going through the Wikipedia data in two hops. In the first method, users configure \textsc{Ember}\xspace to index labeled IMDb training data (with ratings) and retrieve records related to the test data (without ratings) via an \texttt{INNER JOIN}. Users then post-process the output by averaging the labels of the returned \texttt{record}s\xspace. In the second method, users require two \texttt{LEFT JOIN}s that index the Wikipedia training data against the IMDb test dataset, and the IMDb train dataset against the Wikipedia training data. Following a two-hop methodology, users first retrieve the closest Wikipedia summary to each test IMDb record, and then retrieve the closest labeled IMDb instances to each previously retrieved Wikipedia summary, which is post-processed via averaging. Both approaches reuse the pretrained encoder from the IMDb-wiki task, and require at most \red{6} configuration changes and a 7-line post-processing module. We report results when aggregating with a \texttt{join size} of 1, 10, 20, and 30; both approaches improve performance as the number of neighbors increase, until a plateau is reached. The two-hop approach attains MSE of 1.69, 0.92, 0.89, and 0.89 for \texttt{join size} 1, 10, 20, and 30, respectively, while the one-hop approach performs better with 1.59, 0.89, 0.86, and 0.85. \subsection{Low Development Effort} \label{subsec:easy} We describe \textsc{Ember}\xspace's configuration to show the low number of config changes we made, and comment on the supervision required. \subsubsection{Configuration} Perhaps surprisingly, we found that exposing only join specification parameters (Listing~\ref{listing:config}) is a strong out-of-the-box baseline. We require input datasets and supervision to follow a fixed naming convention, under which obtaining the results in Table~\ref{tab:baselines} relies on a default set of configurations options, where only the data directory must be changed. In Table~\ref{table:datasets}, we list how many config changes are required for the best results from Figure~\ref{fig:lesion}. \eat{ \begin{lstlisting}[frame=single,caption={Core configuration lines annotated with options.},captionpos=b,float=t,label={listing:config}] \begin{Verbatim}[commandchars=\\\{\}] \small \dred{"data_dir"}: \dred{"IMDb-wiki"}, \dred{"join_type"}: \dred{"INNER"}, \textcolor{teal}{# or "LEFT", "RIGHT", "FULL"} \dred{"left_size"}: 1, \dred{"right_size"}: 1, \end{Verbatim} \end{lstlisting} } \begin{lstlisting}[frame=single,caption={Core configuration lines annotated with options.},captionpos=b,float=t,label={listing:config}, language=Python,basicstyle=\small,commentstyle=\textcolor{teal},stringstyle=\dred] "data_dir": "IMDb-wiki", "join_type": "INNER", # or "LEFT", "RIGHT", "FULL" "left_size": 1, "right_size": 1, \end{lstlisting} We generate each result in Figure~\ref{fig:lesion} by altering the following unsurfaced options: number of encoders, encoder intialization, encoder finetuning (boolean), fraction of supervision, negative sampler. Users can additionally specify lower-level hyperparameters, which we fix across our experiments: epochs, batch size, embedding size, pooling type, tokenizer, learning rate, loss function parameters. \eat{ \subsubsection{FJ: 1 Line Changed} \label{case:FJ} As an FJ task is symmetric (i.e., there is no difference between which dataset is considered the base or auxiliary for the downstream task), \textsc{Ember}\xspace can rely on the default configuration and indexing optimization to index the smaller of the two tables. This requires a change in the input directory path in the config file. \subsubsection{EM: 1 or 2 Lines Changed} \label{case:EM} EM tasks are symmetric. Thus, we rely on the indexing optimization to index the smaller of the two tables. As the output task is based on pairwise labels, given a pair of records that refer to as the query and target, we define a positive match as one where the target record is in the set of retrieved neighbors when querying \textsc{Ember}\xspace's index with the query record. The default configuration retrieves a single neighbor, and requires a single config change. To retrieve multiple neighbors requires an additional line changed. First, we can simply treat the closest retrieved record as a predicted positive example, and all other records as negatives. Our result post-processing script consists of a 9-lines of python code to process the retrieved results and compute the necessary precision, recall, and F1 metrics. \subsubsection{S: 2 Lines Changed} \label{case:IR} We denote the dataset with the queries as the base dataset, and the passage collection as the auxiliary dataset as the goal is to retrieve passages relevant to each query. This is the configuration set by \textsc{Ember}\xspace's default indexing optimization, as the passage collection is the larger of the two. Thus, we preserve the default configuration, but modify the \texttt{retriever}\xspace to return the top 10 most related \texttt{record}s\xspace, and add a post-processing module that computes MRR. This requires 2 changes to the config file, and our post-processing module consists of 11 lines of code. \subsubsection{QA: 2 Lines Changed} \label{case:QA} For the QA task, we denote the question dataset as the base dataset, and the collection of sentences as the auxiliary dataset. The sentence corpus is smaller than the question corpus, thus, we override the indexing optimization. As the SQuAD corpus is based off Wikipedia, the dataset is of the same vocabulary as the pretraining corpus used by BERT. Thus, \textsc{Ember}\xspace does not perform MLM pretraining by default. Overriding the indexing optimization requires one configuration line edited. \subsubsection{R Application A: 1 Line Changed} \label{case:rec} As both datasets are the same size, the choice of base and auxiliary dataset is irrelevant. This is a standard context enrichment problem, thus we preserve the default configuration for the join task. \subsubsection{R Application B: 3 or 5 Lines Changed} One means of solving the second application is to identify movies in the test set that are similar to those in the train set (with ratings), and aggregate the rating of the similar movies as the predicted rating. \textsc{Ember}\xspace can perform this operation with similarity defined in a single hop, in terms of the labeled training data, or in two hops, by first going through the Wikipedia data. We report the performance of both. In either instance---as there are no labeled examples connecting the train and test data---users retain the default operator configuration up to the representation learning step. In the first method, users configure \textsc{Ember}\xspace to index labeled IMDb training data (with ratings), and retrieve records related to the test data (without ratings) with a \texttt{retriever}\xspace set to return multiple related (labeled) records. The user then post-processes the output by averaging the labels of the returned \texttt{record}s\xspace. This requires 3 lines of config changes, and a 7-line post-processing module. In the second method, users configure \textsc{Ember}\xspace to index both the train Wikipedia and IMDb dataset. Following a two-hop methodology, users then configure a standard \texttt{retriever}\xspace over the Wikipedia index that returns the closest Wikipedia summary to each test IMDb record. Users configure a second \texttt{retriever}\xspace over the IMDb train dataset that returns the closest labeled IMDb instances to each previously retrieved Wikipedia summary, which can then be post-processed via averaging. This requires 5 lines of config changes, and a 7-line post-processing module } \subsubsection{Dependence on Labeled Data} A key user input is labeled examples of relevant record pairs. With the exception of MS MARCO, we use all available labeled examples of \textit{relevant pairs} in Table~\ref{tab:baselines} and Figure~\ref{fig:lesion}. In MS MARCO, we use 2.5M of the 397M of the provided labeled \textit{triples}, which is just $0.63\%$ of the provided triples. For the remaining datasets, we evaluate how many labeled examples are required to match performance of our reported results. We found that 9 of the 17 datasets required all of the provided examples. The remaining datasets required $54.4\%$ of labeled relevant data on average to meet Recall@1 performance, and $44.5\%$ for Recall@10. In the best case, for EM-S DBLP-ACM, only $30\%$ and $1\%$ of the data is required to achieve the same Recall@1 and Recall@10, respectively. \section{Conclusion} \label{sec:conclusion} We demonstrate how seemingly unrelated tasks spanning data integration, search, and recommendation can all be viewed as instantiations of context enrichment. We propose keyless joins as a unifying abstraction that can power a system for general context enrichment, which allows us to view context enrichment as a data management problem. Consequently, we developed and applied \textsc{Ember}\xspace, a first-of-its kind system that performs no-code context enrichment via keyless joins. We evaluate how developing a keyless join enrichment layer empowers a single system to generalize to five downstream applications, with no ML code written by the user. \section{0pt}{1pt plus 2pt minus 1pt}{1pt plus 2pt minus 1pt} \begin{document} \title{\textsc{Ember}\xspace: No-Code Context Enrichment via \\ Similarity-Based Keyless Joins} \eat{\author{Ben Trovato} \affiliation{% \institution{Institute for Clarity in Documentation} \streetaddress{P.O. Box 1212} \city{Dublin} \state{Ireland} \postcode{43017-6221} } \email{[email protected]} } \author{Sahaana Suri, Ihab F. Ilyas$^\ast$, Christopher R\'e, Theodoros Rekatsinas$^\dagger$} \affiliation{% \institution{Stanford University, University of Waterloo$^\ast$, UW-Madison$^\dagger$} } \input{abstract} \maketitle \pagestyle{\vldbpagestyle} \begingroup\small\noindent\raggedright\textbf{PVLDB Reference Format:}\\ \vldbauthors. \vldbtitle. PVLDB, \vldbvolume(\vldbissue): \vldbpages, \vldbyear.\\ \href{https://doi.org/\vldbdoi}{doi:\vldbdoi} \endgroup \begingroup \renewcommand\thefootnote{}\footnote{\noindent This work is licensed under the Creative Commons BY-NC-ND 4.0 International License. Visit \url{https://creativecommons.org/licenses/by-nc-nd/4.0/} to view a copy of this license. For any use beyond those covered by this license, obtain permission by emailing \href{mailto:[email protected]}{[email protected]}. Copyright is held by the owner/author(s). Publication rights licensed to the VLDB Endowment. \\ \raggedright Proceedings of the VLDB Endowment, Vol. \vldbvolume, No. \vldbissue\ % ISSN 2150-8097. \\ \href{https://doi.org/\vldbdoi}{doi:\vldbdoi} \\ }\addtocounter{footnote}{-1}\endgroup \ifdefempty{\vldbavailabilityurl}{}{ \vspace{.3cm} \begingroup\small\noindent\raggedright\textbf{PVLDB Artifact Availability:}\\ The source code, data, and/or other artifacts have been made available at \url{\vldbavailabilityurl}. \endgroup } \input{intro} \input{application} \input{keyless} \input{ember} \input{preprocessing} \input{representation} \input{joining} \input{evaluation} \input{relwork} \input{conclusion} \eat{\begin{figure*} \includegraphics[width=\textwidth]{figures/lesion_s.pdf} \caption{alternative to lesion -- what do you think?} \label{fig:lesion} \vspace{-1em} \end{figure*}} \bibliographystyle{ACM-Reference-Format} \section{Context Enrichment} \label{sec:applications} In this section, we define context enrichment, and provide example workloads that can be framed as a form of context enrichment. \subsection{Problem Statement} \label{subsec:problem} Structured data, or data that adheres to a fixed schema formatted in rows and columns, suffers from context fragmentation. We broadly define structured data to include semi-structured and textual data sources that may be stored and keyed in data management systems, such as content from Wikipedia articles or web search results. Unlike unstructured data, structured data follows a scattered format that is efficient to store, query, and manipulate for specific business needs. This may be in the form of an e-commerce company storing datasets cataloging products and user reviews as in Figure~\ref{fig:example}. To use this fragmented data for ML tasks, practitioners implicitly or explicitly join these dataset to construct discriminative features. We refer to this joining process as \emph{context enrichment}, which we define as follows: Given a base dataset in tabular form, $D_0$, context enrichment aligns $D_0$ with context derived from auxiliary data sources, $D = \{D_1, ... , D_M\}$, to solve a task $T$. We focus on a text-based, two-dataset case ($|D| = 1$), but propose means for multi-dataset extension Sections~\ref{sec:preprocessing}-\ref{sec:joining}, and defer their evaluation to future work. We explore context enrichment in regimes with abundant and limited labeled relevant pairs $Y$ to learn source alignment. We represent each dataset $D_i$ as an $\mathbf{n_i}\times\mathbf{d_i}$ matrix of $\mathbf{n_i}$ data points (or records) and $\mathbf{d_i}$ columns. We denote $C_{ir}$ as the $r^{th}$ column in dataset $i$. We denote $d_{ij}$ as the $j^{th}$ row in dataset $i$. Columns are numeric or textual, and we refer to the domain of $d_{ij}$ as $\mathbf{D_i}$. \eat{Each dataset $D_i$ consists of $\mathbf{d_i}$ columns, each of which we denote as $C_{ir}$, where $r \in \{1, ...,\mathbf{d_i}\}$. Columns are either numeric or textual, meaning $C_{ir} \in X^{{n_i}}$, where $X \in \{\mathbb{R} \cup \mathbb{N}\}$ and $n_i$ is the number of records in dataset $D_i$. Data points in each dataset are represented as $d_{ij}$ for the $j^{th}$ row in dataset $i$, where $j \in \{1, ...,n_i\}$ and $d_{ij} \in X^{\mathbf{d_i}}$. We describe how to extend beyond these formats in Section~\ref{sec:representation}. } Our goal is to \emph{enrich}, or identify all context for, each $d_{0j}$ in $D_0$: auxiliary records $d_{lm}$ ($l \neq 0$) that are related to $d_{0j}$, as per task $T$. \subsection{Motivating Applications} \label{subsec:target} Context enrichment is a key component for applications across a broad array of domains. Thus, a context enrichment system would reduce the developer time and effort needed to construct domain-specific pipelines. We now describe a subset of these domains, which we evaluate in Section~\ref{sec:eval}. Additional applicable domains include entity linkage or disambiguation~\citep{link2,link1}, nearest neighbor machine translation~\citep{knnmt}, and nearest neighbor language modeling~\citep{knnlm}. \minihead{Entity Matching and Deduplication} Entity matching identifies data points that refer to the same real-world entity across two different collections of entity mentions~\citep{matchsurvey}. An entity denotes any distinct real-world object such as a person or organization, while its entity mention is a reference to this entity in a structured dataset or a text span. Entity deduplication identifies entities that are found multiple times in a single data source, thus is a special case of entity matching where both collections of entity mentions are the same. \vspace{4pt} \noindent We frame entity matching as a context enrichment problem where $D_0$ and $D_1$ represent the two collections of entity mentions. Context enrichment aligns entities $d_{1m}$ in the auxiliary dataset $D_1$ with each entity $d_{0j}$ in the base dataset $D_0$. In entity deduplication, $D_0 = D_1$. The downstream task $T$ is a binary classifier over the retrieved relevant records, as the aim is to identify matching entities. \eat{ \minihead{Entity Linking or Disambiguation} Entity linking, or named entity disambiguation, joins entity mentions (as defined above) in the form of a text span to a canonical entity in a database or knowledge graph~\citep{link1,link2}. Entity linkage differs from entity matching in that it has access to relationship information across entities. \vspace{3pt} \noindent We frame entity linkage as a context enrichment problem where $D_0$ and $D_1$ represent the collection of entity mentions and a database or linearized representation of the knowledge graph, respectively. Context enrichment aligns entities $d_{1m}$ in the auxiliary dataset $D_1$ that map to each entity $d_{0j}$ in the base dataset $D_0$. The downstream task $T$ is a binary classifier over the retrieved relevant records, as the aim is to identify matching entities. \\ } \minihead{Fuzzy Joining} A fuzzy join identifies data point pairs that are similar to one another across two database tables, where similar records may be identified with respect to a similarity function (e.g., cosine similarity, Jaccard similarity, edit distance) and threshold~\citep{fj1,surajit} defined over a subset of key columns. Though related to entity matching, fuzzy joins can be viewed as a primitive used to efficiently mine and block pairs that are similar across the two data sources. \vspace{4pt} \noindent We frame fuzzy joining as a context enrichment problem where $D_0$ and $D_1$ represent the two database tables. We let $C_0$ and $C_1$ denote the set of key columns used for joining. Records $d_{0j}$ and $d_{1m}$ are joined if their values in columns $C_0$ and $C_1$ are similar, to some threshold quantity. This is equivalent to a generic context enrichment task with a limited number of features used. The downstream task $T$ is a top-k query, as the aim is to identify similar entities. \minihead{Recommendation} A recommender system predicts the rating that a user would give an item, typically for use in content recommendation or filtering~\citep{recsys}. We also consider the broader problem of uncovering the global rating for an item, as in the e-commerce example in Figure~\ref{fig:example}, as being a form of recommendation problem---namely, the global score may be predicted by aggregating the predicted per-user results obtained via classic recommender systems. \vspace{4pt} \noindent We frame such recommendation workloads as a context enrichment problem where $D_0$ represents all information regarding the entity to be ranked (e.g., a base product table, or new candidate products), and $D_1$ represents the information of the rankers, or other auxiliary data (e.g., catalogs of previously ranked products). Context enrichment aligns rankers $d_{1m}$ in the auxiliary dataset $D_1$ with those that are related to each entity to be ranked $d_{0j}$ in the base dataset $D_0$. The downstream task $T$ is to return the top-1 query, or to perform aggregation or train an ML model over the returned top-k entries. \minihead{Search} An enterprise search engine returns information relevant to a user query issued over internal databases, documentation, files, or web pages~\citep{enterprise1, enterprise2}. A general web retrieval system displays information relevant to a given search query~\citep{search1,search2}. Both rely on information retrieval techniques and relevance-based ranking over an underlying document corpus as building blocks to develop complex, personalized pipelines, or for retrospective analyses~\citep{marco}. \vspace{4pt} \noindent We frame retrieval and ranking in search as a context enrichment problem where $D_0$ represents the set of user queries, and $D_1$ represents the underlying document corpus. Context enrichment aligns documents $d_{1m}$ in the auxiliary dataset $D_1$ that map to each query $d_{0j}$ in the base dataset $D_0$. The downstream task $T$ is to return the top-k documents for each query, sorted by their query relatedness. \minihead{Question Answering} Question answering systems answer natural language questions given a corresponding passage (e.g., in reading comprehension tasks) or existing knowledge source (e.g., in open domain question answering)~\citep{squad,qa}. Multi-hop question answering generalizes this setting, where the system must traverse a series of passages to uncover the answer~\citep{multihop}. For instance, the question "what color is the ocean?" may be provided the statements "the sky is blue" and "the ocean is the same color as the sky." \vspace{4pt} \noindent We frame the retriever component~\citep{retriever} of a classic retriever-reader model in open domain question answering as a context enrichment problem. Our task is to identify the candidate text spans in the provided passages that contain the question's answer (the retriever component), and a downstream reader task can formulate the answer to the question. We let dataset $D_0$ represent the set of questions, and $D_1$ represent the provided passages or knowledge source, split into spans (e.g., based on sentences, or fixed word windows). Context enrichment aligns spans $d_{1m}$ in the auxiliary dataset $D_1$ that contain the answer to each question $d_{0j}$ in the base dataset $D_0$. Multi-hop question answering requires an extra round of context enrichment for each hop required. Each round selects a different passage's spans as the base table $D_0$; to identify context relevant to the question, the user can traverse the related spans extracted from each passage. The downstream task $T$ is to learn a reader model to answer questions using the enriched data sources. \eat{ \minihead{Machine Translation} \red{Do the nearest neighbor MT or LM warrant adding?} } \section{Related Work} \label{sec:relwork} \minihead{Similarity Joins} Similarity-based, or fuzzy, joins often focus on the unsupervised setting~\citep{surajit,fj1,fj2}. State-of-the art systems such as AutoFJ~\citep{autofj} are tailored for the case where tables can be joined using exact keys or shared phrases that do not differ greatly in distribution (e.g., our EM tasks)---not complex context enrichment. \textsc{Ember}\xspace generalizes to arbitrary notions of similarity and join semantics at the expense of supervised pairs, and can also leverage unsupervised methods for negative sampling or MLM pretraining. \minihead{Automated Machine Learning} Automated Machine Learning (AML) systems aim to empower users to develop high-performance ML pipelines minimal intervention or manual tuning. They support various types of data preprocessing, feature engineering, model training and monitoring modules. Examples of AML tools include Ludwig~\citep{ludwig}, Overton~\citep{overton}, Google Cloud AutoML~\citep{gcloud}, and H20.ai~\citep{h20}. However, these platforms do not focus on context enrichment, leaving it as an exercise for users to perform prior to data ingestion. \minihead{Relational Data Augmentation} Relational data augmentation systems seek to find new features for a downstream predictive task by deciding whether or not to perform standard database joins across a base table and several auxiliary tables~\citep{hamlet, hamletpp, arda}. Similar to context enrichment, these systems aim to augment a base table for a downstream ML workload. However, they assume the existence of KFK relationships that simply must be uncovered. \minihead{Data Discovery} Data discovery systems find datasets that may be joinable with or related to a base dataset, and to uncover relationships between different datasets using dataset schema, samples, and metadata~\citep{dd1,dd2,dd3,dd4,dd5,dd6,dd7}. These systems typically surface KFK relationships, and do not tune for downstream ML workloads. \minihead{NLP and Data Management} A recurring aim in data management is to issue natural language commands to interface with structured data~\citep{nlidb,csc}. Recent work in Neural Databases~\citep{neuraldb} aims to replace standard databases with Transformer-powered schemaless data stores that are updated and queried with natural language commands. Related to this work are systems that leverage advances in NLP to provide domain-specific functionality, such as converting text to SQL~\citep{text2sql1,text2sql2}, correlating structured and unstructured data~\citep{tabert}, enabling interpretable ML over structured data~\citep{tabnet}, or automating data preparation~\citep{rpt}. We focus on the broader problem of context enrichment of entities for downstream tasks. To our knowledge, this has not been formally addressed in the literature, which often assumes entity information has been resolved~\citep{neuraldb}. \section{Joining} \label{sec:joining} In this section, we describe the last step of \textsc{Ember}\xspace's pipeline: joining. Given the \texttt{embedding}s\xspace output by the trained \texttt{encoder}s\xspace, \textsc{Ember}\xspace executes the keyless join by identifying related points across the input datasets, and processing them for downstream use. \textsc{Ember}\xspace indexes the learned \texttt{embedding}s\xspace and queries this index to find candidate related records. The \texttt{join sizes} determine the number of returned results per query, and we also allow users to configure a similarity threshold for each candidate match. We now detail the indexing and retrieval procedure, post-processing, and multi-dataset extension. \minihead{Indexing and Query Retrieval} Given two records, \textsc{Ember}\xspace computes the similarity between their \texttt{embedding}s\xspace to determine if the records are related. Many traditional solutions to our motivating applications perform such pairwise checks across all possible pairs either na\"ively or with blocking~\citep{deepmatcher, blocking, bertmarco} to identify related records. However, the choice of operator is both domain-specific, and scales quadratically at query time with the size of the input datasets and blocking mechanisms used (see Section~\ref{subsec:general}). We eliminate the need for pairwise checking by indexing our \texttt{embedding}s\xspace, which are optimized for clustering related records, and rely on efficient libraries for maximum inner product search (MIPS)~\citep{faiss}. For a \texttt{LEFT} or \texttt{RIGHT OUTER JOIN}, \textsc{Ember}\xspace constructs an index over the base ($D_0$) or auxiliary ($D_1$) datasets, respectively. \textsc{Ember}\xspace then queries the index with each \texttt{embedding}\xspace of the remaining dataset, and returns the \texttt{record}\xspace and \texttt{embedding}\xspace corresponding to the most similar records using a \texttt{retriever}\xspace operator. For a \texttt{FULL OUTER} or \texttt{INNER JOIN}, \textsc{Ember}\xspace may jointly index and query both datasets to identify related entries in either direction. By default, \textsc{Ember}\xspace only indexes the larger dataset to reduce runtime---an optimization we evaluate in Section~\ref{subsec:micros} that improves query runtime by up to \red{2.81}$\times$. \textsc{Ember}\xspace's default configuration is an \texttt{INNER JOIN}. \minihead{Post-Processing} The user-provided \texttt{join size} configures the \texttt{retriever}\xspace to return the top-$k$ records with the closest embeddings in the indexed dataset. \textsc{Ember}\xspace additionally supports threshold-based retrieval. The former is useful for applications such as search, where a downstream task may be to display the top-$k$ search results to a user in sorted order. The latter is useful for applications where there may not be related records for each record in the base dataset. \textsc{Ember}\xspace's default \texttt{retriever}\xspace is configured for a 1-to-10 join. If the task $T$ is not to simply return related records, users can construct pipelines on top of \textsc{Ember}\xspace's outputs, relying on keyless-join-based context enrichment as a key primitive. Examples of such workloads include the recommendation example from Figure~\ref{fig:example}, which we simulate as a case study in Section~\ref{subsec:extensibility}, open domain question answering, data augmentation, or applications that involve humans in the loop to verify matches or drive business needs. \minihead{Multi-Dataset Extension} The joining step may vary in the multi-dataset case in two ways. In a first scenario, each auxiliary data source $D_i$ is indexed, and the query retrieval phase will query each of these indexes and return candidate related data points for each pairwise interaction. If multiple data sources must be sequentially aligned and a DAG can be specified over this sequence, a user can chain context enrichment subroutines by querying the next index with the records retrieved by the previous subroutine; we provide a toy example of this scenario in Section~\ref{subsec:extensibility} under Recommendation. \section{Preprocessing} \label{sec:preprocessing} In this section, we describe the first step of \textsc{Ember}\xspace's pipeline: preprocessing. Users provide base and auxiliary datasets with examples of related records across the two. \textsc{Ember}\xspace first processes the input datasets so all records are represented in a comparable format. \textsc{Ember}\xspace then pretrains the \texttt{encoder}s\xspace for the representation learning step. We describe these phases, and then multi-dataset extension. \minihead{Data Preparing (Figure~\ref{fig:pipeline}A.1)} This phase converts each \texttt{record}\xspace $d_{ij}$ into a format that can be used for downstream Transformer-based \texttt{encoder}s\xspace regardless of schema. Motivated by recent work in representing structured data as sentences~\citep{tabert, neuraldb}, \textsc{Ember}\xspace's default pipeline uses a \texttt{sentence}\xspace \texttt{preparer}\xspace $P$ to convert input \texttt{record}s\xspace $d_{ij}$ into \texttt{sentence}s\xspace $P(d_{ij}) = s_{ij}$. Each key-value pair in $d_{ij}$ is converted to a string and separated by the \texttt{encoder}\xspace's separator token as \texttt{``key\_1 value\_1 [SEP] key\_2 value\_2 [SEP]..."} (Figure~\ref{fig:preprocess}). \minihead{Optional Pretraining (Figure~\ref{fig:pipeline}A.2)} Our default BERT-based \texttt{encoder}\xspace is trained over natural language corpora (Wikipedia and BookCorpus~\citep{wiki,bookcorpua}). Structured data is often domain-specific, and is of a different distribution than natural language. Thus, we find that bootstrapping the pipeline's \texttt{encoder}s\xspace via additional pretraining can improve performance by up to \red{2.08$\times$}. \textsc{Ember}\xspace provides a pretraining configuration option that is enabled by default. Users can pretrain the pipeline's \texttt{encoder}s\xspace via BM25-based self-supervision (out-of-the-box) or by developing weak supervision-based \texttt{labeler}s\xspace (custom-built). We add a standard Masked Language Modeling (MLM) head to each pipeline \texttt{encoder}\xspace, and pretrain it following the original BERT pretraining procedure that fits a reconstruction loss. To encourage the spread of contextual information across the two tables, we concatenate one \texttt{sentence}\xspace from each table to one other as pretraining input as \texttt{``$s_{ij}$ [SEP] $s_{kl}$"} (Figure~\ref{fig:preprocess}). We select \texttt{sentence}\xspace pairs that are likely to share information in an unsupervised manner via BM25, a bag-of-words relevance ranking function~\citep{bm25}, though any domain-specific unsupervised similarity join can be used, such as from Magellan~\citep{magellan} or AutoFJ~\citep{autofj}. We evaluate BM25-based MLM pretraining in Section~\ref{subsec:micros}. During development, we explored learning conditional representations of each table given the other by selectively masking one table's \texttt{sentence}s\xspace, but found no change in performance compared to uniform masking. \minihead{Multi-Dataset Extension} Depending on the encoder configuration used in the multi-dataset case, the BM25-based pretraining step will be applied to all \texttt{sentence}s\xspace across all datasets at once (anchored from the base table), or each dataset pairwise. \begin{figure} \includegraphics[width=\columnwidth]{figures/preprocessing.pdf} \caption{Examples of the data preparing and pretraining phases of the preprocessing architecture step.} \label{fig:preprocess} \vspace{-1em} \end{figure} \section{Representation Learning} \label{sec:representation} In this section, we describe the second step of \textsc{Ember}\xspace's pipeline: representation learning. Given the \texttt{sentence}s\xspace and optionally pretrained \texttt{encoder}s\xspace from the first step, \textsc{Ember}\xspace fine-tunes the \texttt{encoder}s\xspace such that \texttt{embedding}s\xspace from related records are close in embedding space. These \texttt{embedding}s\xspace are then passed to the final pipeline step. Users can choose how many \texttt{encoder}s\xspace to configure, the \texttt{encoder}\xspace architecture and output dimension, and how to train the \texttt{encoder}s\xspace, which we now detail prior to describing multi-dataset extension. \minihead{\texttt{Encoder} configuration} \textsc{Ember}\xspace provides a choice of training independent \texttt{encoder}s\xspace, $E_i$ for each data source, or using a single \texttt{encoder}\xspace $E_0$ common to all data sources. In all of our scenarios, using a single, common \texttt{encoder}\xspace performs best, sometimes by over an order of magnitude, and is set as \textsc{Ember}\xspace's default configuration. In our tasks, we found that using separate encoders perturbs the representations such that exact matches no longer share a representation---thus, the encoders must relearn correspondences, and often fail to. However, to extend \textsc{Ember}\xspace to non-textual data (e.g., images, video, text-image for image captioning or joint sentiment analysis, or text-audio tasks), users must leverage source-specific \texttt{encoder}s\xspace---thus, we provide them as a configurable option. \minihead{\texttt{Encoder} architecture} \textsc{Ember}\xspace lets users configure each \texttt{encoder}\xspace's base architecture and the size of the learned \texttt{embedding}s\xspace. Users can choose BERT$_{\text{base}}$ or DistilBERT$_{\text{base}}$ as the core architecture; \textsc{Ember}\xspace's default is the 40\% smaller, and 60\% faster DistilBERT model. We use models from HuggingFace Transformers~\citep{hf}; thus, integrating new architectures requires few additional lines of code. We remove the MLM head used in the preprocessing step for optional pretraining, and replace it with a fully connected layer that transforms BERT's default 768-dimensional output to a user-specified \texttt{embedding}\xspace output dimension, $d$. The output of the fully connected layer is a $d$-dimensional embedding for each input token. Users can choose one of two types of aggregation methods that will return a single $d$-dimensional output per input \texttt{sentence}\xspace: averaging all of the embeddings, or using the embedding of the leading \texttt{CLS} token that BERT appends to its input data (Figure~\ref{fig:preprocess}). \textsc{Ember}\xspace defaults to \texttt{CLS}-based aggregation with a 200-dimensional output. \minihead{\texttt{Encoder} training} The \texttt{encoder}s\xspace' goal is to learn a representation (\texttt{embedding}\xspace), for the data sources such that \texttt{sentence}s\xspace that refer to similar entities are grouped in the underlying embedding space. Recall that to perform a keyless join under an $\ell_p$-norm, each \texttt{encoder}\xspace must learn a function that maps elements of $D_i$ to the space $\mathbf{X}$, such that $\|x_{ij} - x_{kl}\|_p < \|x_{ij} - x_{mn}\|_p$ when the $j^{th}$ entity in the $i^{th}$ dataset is more closely related to the $l^{th}$ entity in the $k^{th}$ dataset than the $n^{th}$ entity in the $m^{th}$ dataset. We directly optimize for this objective function by training \texttt{encoder}s\xspace using a contrastive, triplet loss together with user-provided supervision. Given an anchor \texttt{record}\xspace $d_{0\text{a}}$ from $D_0$, and \texttt{record}s\xspace $d_{1\text{p}}$ and $d_{1\text{n}}$ in $D_1$ that are related and unrelated to $d_{0\text{a}}$, respectively, let $F_0(d_{0\text{a}}) = x_{0\text{a}}$, $F_1(d_{1\text{p}}) = x_{1\text{p}}$, and $F_1(d_{1\text{n}}) = x_{1\text{n}}$ be their \texttt{embedding}s\xspace following the composition of the \texttt{sentence}\xspace \texttt{preparer}\xspace $P$ and \texttt{encoder}\xspace $E_i$ operators ($F_i=E_i \circ P$). We minimize the triplet loss, defined as: $$ \mathcal{L}(x_{0\text{a}}, x_{1\text{p}}, x_{1\text{n}}) = \max\{\|x_{0\text{a}} - x_{1\text{p}}\|_p, \|x_{0\text{a}} - x_{1\text{n}}\|_p + \alpha, 0\}$$ \noindent where $\alpha$ is a hyperparameter controlling the margin between related and unrelated \texttt{embedding}s\xspace. Users could use an alternative \texttt{loss}\xspace function: a cosine similarity loss would provide representations that similarly encourage related points to be close and unrelated points to be far, and a standard binary cross-entropy loss may be used as well, where the final layer in the trained \texttt{encoder}\xspace would be the end embeddings. However, they do not explicitly optimize for \textit{relative} distances between related and unrelated records. Users often have examples of related pairs, but no unrelated examples to form triples. In our tasks, only the search workload provides triples, while the rest provide lists of related pairs, which we represent with a \texttt{labeler}\xspace. As a result, we provide negative \texttt{sampler}\xspace operators to convert \texttt{labeler}s\xspace that operate over pairs to the triples required by the triplet \texttt{loss}\xspace. If the user-provided \texttt{labeler}\xspace already contains a related and unrelated example for a \texttt{record}\xspace, we form a triple using these examples. If a \texttt{record}\xspace does not contain a related and unrelated example, for each \texttt{record}\xspace $d_{0j}$ in $D_0$ with a labeled related record, we use either a random \texttt{sampler}\xspace or a stratified hard negative \texttt{sampler}\xspace. The random \texttt{sampler}\xspace selects a \texttt{record}\xspace at random (that is not a supervised related pair) as an example unrelated \texttt{record}\xspace. The stratified \texttt{sampler}\xspace provides tiers for different degrees of relatedness for the negative examples---a user can specify a region of hard examples to sample from, given prior domain knowledge. We provide a default stratified \texttt{sampler}\xspace with a single tier of relatedness defined using BM25 or Jaccard similarity, though any unsupervised join method can be used (including AutoFJ~\citep{autofj}). We show that a hard negative \texttt{sampler}\xspace improves recall by up to \red{30\%} compared to a random \texttt{sampler}\xspace in Section~\ref{subsec:micros}. \minihead{Multi-Dataset Extension} The \texttt{encoder}\xspace configuration and architecture are unchanged in the multi-dataset case. There are two options for the \texttt{encoder}\xspace training procedure. The first scenario follows the context enrichment problem definition---where a base table $D_0$ must be augmented with several auxiliary data sources $D$. In this case, each \texttt{encoder}\xspace can be trained pairwise with $D_0$ and $D_i$ as described above. In the case where multiple data sources must be aligned in sequence, a user can successively apply \textsc{Ember}\xspace over a data DAG created using their prior knowledge---effectively creating several, sequential context enrichment problems as described in Section~\ref{subsec:target} for multi-hop question answering. Else, \textsc{Ember}\xspace can induce a DAG and sequentially traverse the space of possible keyless joins based on the cardinality of each dataset, in ascending order. \section{\textsc{Ember}\xspace} \label{sec:ember} We develop \textsc{Ember}\xspace,\footnote{https://github.com/sahaana/ember} an open-source system for no-code context enrichment. \textsc{Ember}\xspace implements a keyless join abstraction layer that meets the specification in Section~\ref{subsec:keyless_spec}. \textsc{Ember}\xspace first represents input records using transformer-based embeddings directly optimized for the condition in Section~\ref{subsec:keyless}. \textsc{Ember}\xspace then populates a reusable index with these embeddings based on the \texttt{join type}, and configures index retrieval based on the \texttt{join sizes}. We now provide an overview of \textsc{Ember}\xspace's usage, API and architecture; data types and operators are in Table~\ref{table:types}, with an architecture overview in Figure~\ref{fig:pipeline}. \subsection{Usage} \label{subsec:api} As input, \textsc{Ember}\xspace requires the join specification parameters: a base data source $D_0$ ("left"), auxiliary data sources $D=\{D_1,...,D_M\}$ ("right"), labeled examples of related data points that represent similar entities, \texttt{join type}, and \texttt{join sizes}. Labeled examples are provided in one of two supervision forms: pairs of related records, one from each table, or a triple where a record from $D_0$ is linked to a related and unrelated record from each $D_i$. That is, unrelated examples are optional, but related ones are required. Recall that we focus on the $M = 1$ case, but describe extensions in Sections~\ref{sec:preprocessing}-\ref{sec:joining}. As output, \textsc{Ember}\xspace retrieves the data points enriched based on the \texttt{join type} and \texttt{join sizes} as a list of tuples. Users configure \textsc{Ember}\xspace using a json configuration file that exposes the join specification and lower-level \textsc{Ember}\xspace-specific parameters (see Section~\ref{subsec:extensibility}). \subsection{API and Architecture} \label{subsec:arch} Keyless joins learn a representation that quantifies data point relatedness, and retrieve these points regardless of the input schema. We propose a modular system with three architectural elements to enable this: data preprocessing, representation learning, and data joining. \textsc{Ember}\xspace consists of dataflow operators that transform inputs into the formats required for each step (see Table~\ref{table:types}). \textsc{Ember}\xspace represents input data records $d_{ij}$ as {\texttt{record}s\xspace} in key-value pairs. Supervision is represented via \texttt{labeler}s\xspace. An \textsc{Ember}\xspace pipeline consists of {\texttt{preparer}s\xspace}, {\texttt{encoder}s\xspace}, \texttt{sampler}s\xspace, \texttt{loss}es\xspace, and \texttt{retriever}s\xspace. \textsc{Ember}\xspace uses \texttt{preparer}s\xspace to transform \texttt{record}s\xspace into \texttt{sentence}s\xspace. \textsc{Ember}\xspace uses \texttt{encoder}s\xspace to transform \texttt{sentence}s\xspace into \texttt{embedding}s\xspace that are optimized per a provided \texttt{loss}\xspace; \texttt{sampler}s\xspace mine negative examples if the provided supervision only provides examples of related records. The trained \texttt{embedding}s\xspace are stored in an index, and are retrieved using a \texttt{retriever}\xspace. We provide an API over these operators in the form of a customizable, high-level configuration, as described in Section~\ref{subsec:easy}. To enable functionality beyond that described, users must implement additional \texttt{preparer}s\xspace, \texttt{encoder}s\xspace, \texttt{sampler}s\xspace, or \texttt{retriever}s\xspace. Users configure \textsc{Ember}\xspace using pre-defined or custom operators, or use the following pre-configured default: \minihead{Preprocessing (Figure~\ref{fig:pipeline}A, \S\ref{sec:preprocessing})} \textsc{Ember}\xspace ingests any text or numeric data source with a pre-defined schema, and converts its records to a common representation. By default, \textsc{Ember}\xspace converts \texttt{record}s\xspace to \texttt{sentence}s using \texttt{sentence preparer} modules, which are fed as input to the pipeline's \texttt{encoders}. \textsc{Ember}\xspace optionally pretrains the \texttt{encoders} in this step using self-supervision. \minihead{Representation Learning (Figure~\ref{fig:pipeline}B, \S\ref{sec:representation})} \textsc{Ember}\xspace learns a mapping for each input data source's \texttt{record}s\xspace such that the transformed data is clustered by relatedness. To learn this mapping, \textsc{Ember}\xspace's \texttt{encoders} are fine-tuned with the input supervision (in the form of a \texttt{labeler}) and \texttt{loss}. \textsc{Ember}\xspace applies the learned mapping to each of the \texttt{sentence}s\xspace to generate \texttt{embedding}s\xspace passed to the final step. \minihead{Joining (Figure~\ref{fig:pipeline}C \S\ref{sec:joining})} \textsc{Ember}\xspace populates an index with the learned \texttt{embedding}s\xspace using Faiss~\citep{faiss}. A keyless join can be completed by issuing a similarity search query given an input \texttt{record}\xspace (transformed to an \texttt{embedding}\xspace) against this index. The dataset that is indexed is determined by the \texttt{join type}. \textsc{Ember}\xspace uses a k-NN \texttt{retriever} module to retrieve as many records specified by the \texttt{join sizes}. \section{\textsc{Ember}\xspace} \label{sec:ember} We develop \textsc{Ember}\xspace,\footnote{https://github.com/sahaana/ember} an open-source system for no-code context enrichment. \textsc{Ember}\xspace implements a keyless join abstraction layer that meets the specification in Section~\ref{subsec:keyless_spec}. \textsc{Ember}\xspace first represents input records using transformer-based embeddings directly optimized for the condition in Section~\ref{subsec:keyless}. \textsc{Ember}\xspace then populates a reusable index with these embeddings based on the \texttt{join type}, and configures index retrieval based on the \texttt{join sizes}. We now provide an overview of \textsc{Ember}\xspace's usage, API and architecture; data types and operators are in Table~\ref{table:types}, with an architecture overview in Figure~\ref{fig:pipeline}. \subsection{Usage} \label{subsec:api} As input, \textsc{Ember}\xspace requires the join specification parameters: a base data source $D_0$ ("left"), auxiliary data sources $D=\{D_1,...,D_M\}$ ("right"), labeled examples of related data points that represent similar entities, \texttt{join type}, and \texttt{join sizes}. Labeled examples are provided in one of two supervision forms: pairs of related records, one from each table, or a triple where a record from $D_0$ is linked to a related and unrelated record from each $D_i$. That is, unrelated examples are optional, but related ones are required. Recall that we focus on the $M = 1$ case, but describe extensions in Sections~\ref{sec:preprocessing}-\ref{sec:joining}. As output, \textsc{Ember}\xspace retrieves the data points enriched based on the \texttt{join type} and \texttt{join sizes} as a list of tuples. Users configure \textsc{Ember}\xspace using a json configuration file that exposes the join specification and lower-level \textsc{Ember}\xspace-specific parameters (see Section~\ref{subsec:extensibility}). \subsection{API and Architecture} \label{subsec:arch} Keyless joins learn a representation that quantifies data point relatedness, and retrieve these points regardless of the input schema. We propose a modular system with three architectural elements to enable this: data preprocessing, representation learning, and data joining. \textsc{Ember}\xspace consists of dataflow operators that transform inputs into the formats required for each step (see Table~\ref{table:types}). \textsc{Ember}\xspace represents input data records $d_{ij}$ as {\texttt{record}s\xspace} in key-value pairs. Supervision is represented via \texttt{labeler}s\xspace. An \textsc{Ember}\xspace pipeline consists of {\texttt{preparer}s\xspace}, {\texttt{encoder}s\xspace}, \texttt{sampler}s\xspace, \texttt{loss}es\xspace, and \texttt{retriever}s\xspace. \textsc{Ember}\xspace uses \texttt{preparer}s\xspace to transform \texttt{record}s\xspace into \texttt{sentence}s\xspace. \textsc{Ember}\xspace uses \texttt{encoder}s\xspace to transform \texttt{sentence}s\xspace into \texttt{embedding}s\xspace that are optimized per a provided \texttt{loss}\xspace; \texttt{sampler}s\xspace mine negative examples if the provided supervision only provides examples of related records. The trained \texttt{embedding}s\xspace are stored in an index, and are retrieved using a \texttt{retriever}\xspace. We provide an API over these operators in the form of a customizable, high-level configuration, as described in Section~\ref{subsec:easy}. To enable functionality beyond that described, users must implement additional \texttt{preparer}s\xspace, \texttt{encoder}s\xspace, \texttt{sampler}s\xspace, or \texttt{retriever}s\xspace. Users configure \textsc{Ember}\xspace using pre-defined or custom operators, or use the following pre-configured default: \minihead{Preprocessing (Figure~\ref{fig:pipeline}A, \S\ref{sec:preprocessing})} \textsc{Ember}\xspace ingests any text or numeric data source with a pre-defined schema, and converts its records to a common representation. By default, \textsc{Ember}\xspace converts \texttt{record}s\xspace to \texttt{sentence}s using \texttt{sentence preparer} modules, which are fed as input to the pipeline's \texttt{encoders}. \textsc{Ember}\xspace optionally pretrains the \texttt{encoders} in this step using self-supervision. \minihead{Representation Learning (Figure~\ref{fig:pipeline}B, \S\ref{sec:representation})} \textsc{Ember}\xspace learns a mapping for each input data source's \texttt{record}s\xspace such that the transformed data is clustered by relatedness. To learn this mapping, \textsc{Ember}\xspace's \texttt{encoders} are fine-tuned with the input supervision (in the form of a \texttt{labeler}) and \texttt{loss}. \textsc{Ember}\xspace applies the learned mapping to each of the \texttt{sentence}s\xspace to generate \texttt{embedding}s\xspace passed to the final step. \minihead{Joining (Figure~\ref{fig:pipeline}C \S\ref{sec:joining})} \textsc{Ember}\xspace populates an index with the learned \texttt{embedding}s\xspace using Faiss~\citep{faiss}. A keyless join can be completed by issuing a similarity search query given an input \texttt{record}\xspace (transformed to an \texttt{embedding}\xspace) against this index. The dataset that is indexed is determined by the \texttt{join type}. \textsc{Ember}\xspace uses a k-NN \texttt{retriever} module to retrieve as many records specified by the \texttt{join sizes}. \section{Evaluation} \label{sec:eval} In this section, we demonstrate that \textsc{Ember}\xspace and its operators are: \begin{enumerate} \item \textbf{General}: \textsc{Ember}\xspace enables context enrichment across five domains while meeting or exceeding similarity-join baseline recall and query runtime performance (Section~\ref{subsec:general}). \item \textbf{Extensible}: \textsc{Ember}\xspace provides a modular architecture, where each component affects performance (Section~\ref{subsec:micros}). \textsc{Ember}\xspace enables task-specific pipelines for various similarity-based queries, and provides task performance that can be fine-tuned by state-of-the-art systems (Section~\ref{subsec:extensibility}). \item \textbf{Low Effort}: \textsc{Ember}\xspace requires no more than five configuration changes (Table~\ref{table:datasets}) from its default, and does not always require large amounts of hand-labeled examples (Section~\ref{subsec:easy}). \end{enumerate} \input{tables/datasets} \subsection{Evaluation Metric and Applications} \minihead{Context Enrichment Evaluation Metric} Context enrichment identifies related records across a base and auxiliary dataset. We can view related records between the two datasets as forming edges in a bipartite graph: each record in each dataset represents a vertex in the graph. Under this framing, a context enrichment system must retrieve all of the outgoing edges (i.e., related records) for each record in the base dataset. This is equivalent to maximizing record-level recall, or the fraction of records for which we recover \emph{all} related records. We choose to define recall at the record-level, rather than the edge-level, as we view context enrichment systems as being repeatedly queried for new incoming data once instantiated. A na\"ive means to optimize for recall is to return \textit{all} auxiliary records as being related to each record in the base dataset. A precision metric greatly drops when we retrieve multiple records. Thus, our evaluation metric is \textbf{recall@k}, for small k (i.e., \texttt{join size}). \minihead{Applications} We evaluate \textsc{Ember}\xspace against workloads from five application domains: fuzzy joining, entity matching, search, question answering, and recommendation (summarized in in Table~\ref{table:datasets}). We make all our datasets publicly available post-\textsc{Ember}\xspace processing. \subsubsection{Fuzzy Join (FJ)} We build two workloads using a dataset and generation procedure from a 2019 scalable fuzzy join VLDB paper~\citep{surajit}. The first dataset consists of the Title, Year, and Genre columns from IMDb~\citep{imdb}. The second dataset is generated by perturbing each row in the first by applying a combination of token insertion, token deletion, and token replacement. The task $T$, is to join each perturbed row with the row that generated it. We generate two dataset versions: 5 perturbations per row (IMDb) and 15 perturbations per row (IMDb-hard), up to 25\% of the record length. As we focus on generalizablity more than scalability, to form a dataset, we randomly sample 10,000 movies and generate 5 perturbed rows for each. We hold out 20\% of records as the test set; no records from the same unperturbed record are in both the train and test sets. \subsubsection{Entity Matching (EM)} We use all 13 benchmark datasets~\citep{dmdata} released with DeepMatcher~\citep{deepmatcher}, spanning structured (EM-S), textual (EM-T), and dirty (EM-D) entity matching. The base and auxiliary datasets always share the same schema. In EM-T, all data records are raw text entries or descriptions. In EM-S, each data record is drawn from a table following a pre-defined schema, where text-based column values are restricted in length. In EM-D, records are similar to EM-S, but some column values are injected into the incorrect column. The task $T$ is to label a record pair (one from each dataset) as representing the same entity or not. Train, validation, and test supervision are lists of unrelated, and related pairs---we only use the related pairs for training \textsc{Ember}\xspace, as we identified mislabeled entries (false negatives) when using \textsc{Ember}\xspace to explore results. \subsubsection{Search (S)} We use the MS MARCO passage retrieval benchmark~\citep{marco}. MS MARCO consists of a collection of passages from web pages that were gathered by sampling and anonymizing Bing logs from real queries~\citep{marco}. The task $T$ is to rank the passage(s) that are relevant to a given query as highly as possible. Supervision is a set of 397M triples, with 1 relevant and up to 999 irrelevant passages for most queries. Irrelevant passages are retrieved via BM25. We report results over the publicly available labeled development set. \subsubsection{Question Answering (QA)} We modify the Stanford Question Answering Dataset (SQuAD)~\citep{squad}. SQuAD consists of Wikipedia passages and questions corresponding to each passage. The task $T$ is to identify the beginning of the text span containing the answer to each question. As described in Section~\ref{sec:applications}, a retriever module, used in retriever-reader models for QA~\citep{retriever}, performs context enrichment. We modify SQuAD by splitting each each passage at the sentence-level, and combining these sentences to form a new dataset. The modified task is to recover the sentence containing the answer \subsubsection{Recommendation (R)} We construct a workload using IMDb and Wikipedia to mimic the e-commerce example from Figure~\ref{fig:example}. For the first dataset, we denormalize four IMDb tables using KFK joins: movie information (title.basics), principal cast/crew for each movie (title.principals) and their information (name.basics), and movie ratings (title.ratings)~\citep{imdb}. For the second dataset, we extract the summary paragraphs of the Wikipedia entry for each IMDb movie by querying latest Wikipedia snapshot; we extract 47813 overlapping records~\citep{wiki}. We remove the IMDb ID that provides a KFK relationship to induce a need for keyless joins. We construct this workload to enable two applications. In Application A, we show that \textsc{Ember}\xspace can join datasets with dramatically different schema. In Application B, we show how to estimate the rating for movies in the test set given ratings for the train set by performing similarity-based analyses enabled by \textsc{Ember}\xspace. Supervision is provided as exact matches and movie ratings with an 80-20 train-test set split. \input{tables/baselines} \eat{\minihead{Evaluation Metrics} We evaluate all EM workloads with respect to F1 score, as is standard in existing work~\citep{deepmatcher,ditto}. For the remainder of the workloads, we report MRR@k and Retrieval@k for k = 1, 10. MRR@k refers to the average of the multiplicative inverse of the rank of the first relevant item in the top k ranked items, and is an information retrieval standard~\citep{marco}. We define Retrieval@k to be the percentage of the test set whose true match is present in the top-k returned nearest neighbors by the \texttt{retriever}\xspace. We report Retrieval@k as a modification of Recall@k, to reflect that we are only looking for a single match in these join scenarios. MRR@1 is equivalent to Retrieval@1.} \subsection{Experimental Setup} \label{sec:setup} \minihead{Baselines} We first evaluate all workloads compared to seven similarity-based joins with respect to recall@1 and recall@10. Our baselines are joins using Levenshtein distance, four variations of Jaccard Similarity, BM25, Auto-FuzzyJoin~\citep{autofj}, and a pretrained embedding-based approach. We evaluate downstream EM and search workloads with respect to previously reported state-of-the-art and benchmark solutions~\citep{deepmatcher,deeper,ditto,marcohomepage,bertmarco}. The remainder of our workloads were constructed to isolate context enrichment from the downstream task, and do not have standard baselines. \minihead{\textsc{Ember}\xspace Default Configuration} Tasks use a \texttt{sentence}\xspace \texttt{preparer}\xspace, and perform 20 epochs of self-supervised pretraining. \textsc{Ember}\xspace uses a single DistilBERT$_{\text{base}}$ \texttt{encoder}\xspace trained with a triplet \texttt{loss}\xspace and \red{stratified} hard negative \texttt{sampler}\xspace. Self-supervision and the \texttt{sampler}\xspace use BM25 to identify similar \texttt{sentence}s\xspace to concatenate from each data source, and to mark as hard negatives, respectively. The output \texttt{embedding}\xspace size is 200, and models are trained with a batch size of 8 using an ADAM optimizer~\citep{adam} with initial learning rate of $1\mathrm{e}{-5}$. The default \texttt{join sizes} are 1 and 10. Results are five-trial averages. \minihead{Implementation} We use a server with two Intel Xeon Gold 6132 CPUs (56 threads) with 504GB of RAM, and four Titan V GPUs with 12GB of memory. We implement \textsc{Ember}\xspace in Python and PyTorch~\citep{pytorch}, with pretrained models and tokenizers from HuggingFace Transformers~\citep{hf}. We use Faiss for MIPS~\citep{faiss}, Magellan for similarity join baselines~\citep{magellan}, rank-BM25 for BM25~\citep{bm25_code}, and AutoFuzzyJoin~\citep{autofj}. \subsection{Generalizability} \label{subsec:general} We show that \textsc{Ember}\xspace's recall and runtime meets or outperforms that of the following similarity-join baselines in nearly all tasks: \minihead{Levenshtein-Distance (LD)} LD is the number of character edits needed to convert one string to another. This join returns the closest records with respect to single-character edits over provided key columns. We filter and only return results under a 30 edit threshold. \minihead{Jaccard-Similarity, Specified Key (JK-WS, JK-2G)} The Jaccard similarity between sets $A$ and $B$ is $J(A, B) = \frac{|A\cap B|}{|A \cup B|}$. Defining a Jaccard-similarity based join over textual inputs requires tokenizer selection. We consider a whitespace tokenizer (WS) and a 2-gram tokenizer (2G) to capture different granularities. JK-WS and JK-2G return the closest records with respect to Jaccard similarity over provided key columns using a WS or 2G tokenizer. We set a filtering threshold to return results with at least 0.3 Jaccard similarity. \minihead{Jaccard-Similarity, Unspecified Key (J-WS, J-2G)} J-WS and J-2G return the closest records with respect to Jaccard similarity using a WS or 2G tokenizer, after a \texttt{sentence}\xspace \texttt{preparer}\xspace. We set a filtering threshold to return results with over 0.3 Jaccard similarity. \minihead{BM25 (BM25)} BM25 is a bag-of-words ranking function used in retrieval~\citep{bm25}. This join returns the closest records with respect to the Okapi BM25 score using default parameters k1=1.5 and b=0.75. \minihead{Pretrained-Embedding (BERT)} BERT generates embeddings for each prepared \texttt{sentence}\xspace via a pretrained DistilBERT$_{\text{base}}$ model, and returns the closest records based on the $\ell_2$-norm between them. \red{\minihead{Auto-FuzzyJoin (AutoFJ)} AutoFJ automatically identifies join functions for unsupervised similarity joins~\citep{autofj} by assuming one input is a "reference table" with few or no duplicates, which does not always hold in context enrichment. If duplicates are present, or records in the reference table are not sufficiently spread, precision estimation may break down (\textsc{Ember}\xspace trivially accounts for these scenarios). AutoFJ optimizes for a precision target, and does not expose any \texttt{join size} semantics. We find a single result is typically returned per record, so we only consider recall@1 at a low precision target of 0.5. We comment on workloads that completed in 1.5 days on our machines using all cores. As AutoFJ exhaustively computes record similarities for each considered join configuration, this means we omit results for MS MARCO, EM-T Company, EM-S BeerAdvo-RateBeer, and several others consisting of large text spans, or where blocking may not be as effective. Users must manually align \emph{matching} columns, which do not always exist thus ignore information in our tasks (e.g., IMDb-wiki): as input, we pass the output of a \texttt{sentence}\xspace \texttt{preparer}\xspace if column names are not identical. } \\ \noindent For multi-column datasets, we provide a plausible key column if the method requires. In FJ, EM, and R, this is a title or name column. \subsubsection{Retrieval Quality} We show that \textsc{Ember}\xspace is competitive with or exceeds the best performing alternatives with respect to Recall@1 and Recall@10 (Table~\ref{tab:baselines}). In both tables, we highlight the methods that are within 1\% of the top performing method. No method dominates the others across the different workloads, while BERT underperformed all alternatives. Broadly, character-based joins (LD, JK-2G, J-2G) tend to perform well in scenarios where a join key exists but may be perturbed (FJ, EM-S, EM-D); word-based joins (J-WS, BM25) tend to perform well in scenarios with word-level join keys (EM-S), or where a join key does not exist but common phrases still link the two datasets (R, EM-D). Neither performs well otherwise (S, EM-T). \textsc{Ember}\xspace most consistently outperforms or is comparable with alternatives across the tasks: a learned approach is necessary for generalization. The exception is with the synthetic FJ workload that is, by construction, suited for character-based joins. \red{We do not report AutoFJ in Table~\ref{tab:baselines} due to incompleteness. AutoFJ is tailored for the EM and FJ: many-to-one joins with identical schema. Of those completed, \textsc{Ember}\xspace is sometimes outperformed by up to 8\% recall@1 (Amazon-Google), but is otherwise comparable or far exceeds AutoFJ when considering recall@10. AutoFJ's recall is 37.9\% for QA, and 38.5\% for R. As AutoFJ over the Wikipedia summary (task R) did not terminate, we only use the title column. } \subsubsection{Query Runtime} Using optimized MIPS routines improved query runtime performance by up to two orders of magnitude. We note that this reflects \textsc{Ember}\xspace joining time, not pretraining and representation learning, which may require several hours. As the two FJ datasets are synthetic and follow identical generation methods, we consider just IMDb-hard. For our largest dataset, MS MARCO (S) with 8.8M auxiliary records, \textsc{Ember}\xspace indexes and retrieves results from the entire corpus, but each baseline only considers each of the up to 1000 relevant records provided by the MS MARCO dataset for each base record. Even when using CPU-only Faiss~\citep{faiss}, \textsc{Ember}\xspace takes \red{7.24} seconds on average for the MIPS-based joining step. Embedding the query table takes \red{24.52} seconds on average. The most expensive dataset with respect to MIPS runtime is MS MARCO (S), which required \red{1.97} minutes when indexing all 8.8M records; excluding it reduces the average to \red{0.31} seconds. For embedding time, this was EM-T Company, requiring \red{3.96} minutes, whose exclusion reduces the average to \red{11.19} seconds. In contrast, the fastest baseline method (JK-WS), took \red{5.02} minutes on average; excluding MS MARCO (\red{79.73} minutes) reduces the average to \red{21.18} seconds. The slowest method (LD), took \red{23.64} minutes on average, with the most expensive dataset, EM-T Company, requiring \red{321.98} minutes. \subsection{Extensibility: Architecture Lesion} \label{subsec:micros} We demonstrate modularity and justify our architectural defaults by evaluating \textsc{Ember}\xspace's performance when modifying components as follows, each of which requires a single line configuration change (all reported percentages are relative unless explicitly specified): \begin{enumerate} \item Replacing MLM pretraining and representation learning (RL) with a pretrained \texttt{encoder}\xspace. \item Removing RL, leaving only MLM pretraining. \item Replacing the fine-tuned Transformer model with a frozen pretrained embedding and a learned dense layer. \item Removing MLM pretraining. \item Random negatives compared to hard negative sampling \item Using an \texttt{encoder}\xspace for each dataset versus a single \texttt{encoder}\xspace. \item Removing the joining index-query optimization. \end{enumerate} \subsubsection{Pretrained \texttt{encoder}\xspace (\textsc{-mlm, rl})} We remove MLM pretraining and RL, and use a pretrained DistilBERT$_{\text{base}}$ encoder---i.e., the same as BERT in Table~\ref{tab:baselines}. We report our results in Figure~\ref{fig:lesion} normalized by \textsc{Ember}\xspace's default. \textsc{Ember}\xspace's performance dramatically declines, sometimes by three orders of magnitude (e.g., recall dropped to 0.04 in R). It is only feasible when the contents of the datasets to be joined are similar, as in certain EM-S and EM-D tasks, and FJ-IMDb. \subsubsection{Removing Representation Learning (\textsc{-rl})} We remove representation learning (RL) and only pretrain an \texttt{encoder}\xspace using the BM25-based MLM procedure from Section~\ref{sec:preprocessing}. We report our results in Figure~\ref{fig:lesion}. \textsc{Ember}\xspace's performance declines by up to an order of magnitude, though it improves performance compared to \textsc{-mlm, rl} on tasks whose datasets do not match the original natural text Wikipedia corpus (e.g., EM-S, FJ). Primarily textual datasets do not see as large an improvement over \textsc{-mlm, rl}, and for QA, where the corpus is derived from Wikipedia, \textsc{-rl} performs slightly worse. \subsubsection{Remove Transformer fine-tuning (\textsc{-ft})} We replace RL with fixed MLM pretrained embeddings followed by a learned fully-connected layer (i.e., we do not fine tune the entire BERT-based \texttt{encoder}\xspace, just the final output layer). We report our results in Figure~\ref{fig:lesion}. Without end-to-end Transformer fine-tuning, \textsc{Ember}\xspace slightly outperforms using just a pretrained encoder (\textsc{-rl}) at times. We primarily observe benefits in text-heavy workloads, where the pretrained encoder provides meaningful representations (QA, S, R, EM-T) without relying on positional information from Transformers. While we do not perform an exhaustive comparison of pretrained embeddings or non-Transformer-based architectures, this shows that \textsc{Ember}\xspace's architecture is a strong out-of-the-box baseline. \subsubsection{Remove MLM Pretraining (\textsc{-mlm})} We eliminate MLM pretraining from the pipeline, and report our results in Figure~\ref{fig:lesion} as \textsc{-mlm}. \textsc{Ember}\xspace meets or exceeds this setting in all but QA, though by a smaller margin than the previous experiments (up to 20.5\% in IMDb-hard). MLM pretraining is not effective for QA as the corpus is drawn from Wikipedia---one of the two corpora BERT was trained with---and both base and auxiliary datasets consist of the same, primarily textual vocabulary. In such cases, users may wish to disable MLM pretraining, although performance is not significantly impacted. In contrast, of the non-EM tasks, MLM pretraining is most helpful for FJ IMDb-hard, where random perturbations result in many records with words that are not in the original vocabulary. \subsubsection{No Negative Sampling (\textsc{-NS})} We replace hard negative sampling with random sampling of unrelated records, and report our results in Figure~\ref{fig:lesion}. Hard negative sampling tends to improve performance by a similar margin as MLM pretraining, and only negatively impacted the EM-T Company dataset (by up to 8.72\% absolute recall). We find larger improvements when the join condition is more ambiguous than recovering a potentially obfuscated join key, as in tasks S (30\% R@1), QA (15\% R@1), and EM-D (15\% R@1). We use BM25-based sampling for all but FJ and QA, where we have prior knowledge, and develop custom samplers based on Jaccard similarity, and sentence origin, respectively. This improved performance over the BM25-based sampler by 1\% absolute recall for FJ, and 8.7\% and 5.6\% absolute recall@1 and recall@10, respectively, for QA. \begin{figure*} \includegraphics[width=\textwidth]{figures/lesion_s.pdf} \caption{Architecture lesion displaying recall@k normalized to the default seen in Table~\ref{tab:baselines} (All) for: a pretrained DistilBERT$_{\text{base}}$ model with no representation learning (\textsc{-mlm,rl}), MLM pretraining with no RL (\textsc{-rl}), RL with no Transformer fine tuning (\textsc{-ft}), RL with no MLM pretraining (\textsc{-mlm}), no hard negative sampling (\textsc{-ns}), and one encoder per dataset (\textsc{te}).} \label{fig:lesion} \end{figure*} \subsubsection{\texttt{encoder}\xspace Configuration (\textsc{te})} We use two \texttt{encoder}s\xspace, one for each dataset, instead of our default single \texttt{encoder}\xspace configuration, and report our results in Figure~\ref{fig:lesion}. We find that using two \texttt{encoder}s\xspace performs up to two orders of magnitude worse than using a single encoder, especially for strictly structured datasets. We observe that through the course of the \texttt{encoder}\xspace training procedure, the performance of using two identically initialized \texttt{encoder}s\xspace often \emph{degrades}---inspecting the resulting embeddings even when running \textsc{Ember}\xspace over two identical tables shows that the exact same terms diverge from one another in the training process. However, we still provide the option to use a distinct encoder for each data source for future extension to non text-based data, such as audio or image. \subsubsection{Index Optimization} For \texttt{INNER} and \texttt{FULL OUTER JOIN}s, we optimize for join execution time by indexing the larger dataset, which reduces the number of queries made by the system. Due to \texttt{encoder}\xspace training, this reflects a small fraction of the end-to-end pipeline execution time at our data sizes, but can be a substantial cost at scale. We evaluate this optimization by running the joining step while indexing the larger dataset, and then the smaller dataset for \emph{all} tasks. On average, this optimization reduces join time by \red{1.76}$\times$, and up to \red{2.81}$\times$. However, this improvement is only meaningful in the MS MARCO workload, saving \red{2.7} minutes. \subsection{Extensibility: End-to-End Workloads} \label{subsec:extensibility} We show how to extend and use \textsc{Ember}\xspace in an end-to-end context. \minihead{Entity Matching} Recent deep-learning-based EM systems focus on the matching phase of that two-part (i.e., blocking and matching) end-to-end EM pipeline~\citep{deeper,deepmatcher,ditto}: given a pair of candidate records, these systems must identify if the pair correspond to the same entity. For end-to-end EM, \textsc{Ember}\xspace must generate candidate blocks with a low rate of false negatives such that it can be efficiently followed by downstream matchers; we verify this in Table~\ref{table:dm_all} (R@10). Perhaps surprisingly, we find that treating \textsc{Ember}\xspace results from a top-1 query as binary classifier achieves performance that is comparable to or better than previous, custom-built state-of-the-art with respect to F1 score. We believe incorporating general operators for data augmentation and domain knowledge integration to enable the custom advances presented in the current state-of-the-art EM system, Ditto, may allow \textsc{Ember}\xspace to entirely bridge this gap~\citep{ditto}. \input{tables/dm} \minihead{Search} In MS MARCO passage ranking, results are ranked in relevance order, and rankings are evaluated via mean reciprocal rank (MRR) of the top 10 results. We rank \textsc{Ember}\xspace results based on their query distance, and compare MRR@10 with existing MS MARCO baselines. We obtain \red{MRR@10 of $0.266$} on the dev set after just 2.5M training examples, outperforming the official Anserini BM25 baseline solution of $0.167$. Our results exceed K-NRM, a kernel based neural model, with a dev set MRR@10 of 0.218~\citep{knrm}, and is slightly below the state-of-the-art from the time, IRNet, with 0.278 MRR@10~\citep{marcohomepage}. For comparison, the first state-of-the-art BERT-based model uses BERT$_\text{large}$ to achieve MRR@10 of 0.365 after training with 12.8M examples~\citep{bertmarco}, and current state-of-the-art is 0.439~\citep{rocketqa}. By developing an additional joining operator, \textsc{Ember}\xspace can implement ColBERT~\citep{colbert}, a previous state-of-the-art method that achieves 0.384 MRR@10 in MS MARCO document ranking that operates on larger input passages: we must remove the pooling step from \textsc{Ember}\xspace's \texttt{encoder}\xspace (1 line config change), and develop a \texttt{retriever}\xspace that indexes and retrieves bags of embeddings for each record. \minihead{Recommendation} In Application B of task R, we estimate the IMDb ratings of movies in the test set given a training dataset and Wikipedia corpus. We report the mean squared error (MSE) between the rating estimates and the true rating. The task is easy: predicting the average training rating returns 1.19 MSE, and a gradient-boosted decision tree (GBDT) over the joined data returns 0.82 MSE. We aim to show extensibility while meeting GBDT performance. There are two approaches to enable this analysis with \textsc{Ember}\xspace by reusing the representation learned for the IMDb-wiki task: similarity defined in a single hop in terms of the labeled training data, or by first going through the Wikipedia data in two hops. In the first method, users configure \textsc{Ember}\xspace to index labeled IMDb training data (with ratings) and retrieve records related to the test data (without ratings) via an \texttt{INNER JOIN}. Users then post-process the output by averaging the labels of the returned \texttt{record}s\xspace. In the second method, users require two \texttt{LEFT JOIN}s that index the Wikipedia training data against the IMDb test dataset, and the IMDb train dataset against the Wikipedia training data. Following a two-hop methodology, users first retrieve the closest Wikipedia summary to each test IMDb record, and then retrieve the closest labeled IMDb instances to each previously retrieved Wikipedia summary, which is post-processed via averaging. Both approaches reuse the pretrained encoder from the IMDb-wiki task, and require at most \red{6} configuration changes and a 7-line post-processing module. We report results when aggregating with a \texttt{join size} of 1, 10, 20, and 30; both approaches improve performance as the number of neighbors increase, until a plateau is reached. The two-hop approach attains MSE of 1.69, 0.92, 0.89, and 0.89 for \texttt{join size} 1, 10, 20, and 30, respectively, while the one-hop approach performs better with 1.59, 0.89, 0.86, and 0.85. \subsection{Low Development Effort} \label{subsec:easy} We describe \textsc{Ember}\xspace's configuration to show the low number of config changes we made, and comment on the supervision required. \subsubsection{Configuration} Perhaps surprisingly, we found that exposing only join specification parameters (Listing~\ref{listing:config}) is a strong out-of-the-box baseline. We require input datasets and supervision to follow a fixed naming convention, under which obtaining the results in Table~\ref{tab:baselines} relies on a default set of configurations options, where only the data directory must be changed. In Table~\ref{table:datasets}, we list how many config changes are required for the best results from Figure~\ref{fig:lesion}. \eat{ \begin{lstlisting}[frame=single,caption={Core configuration lines annotated with options.},captionpos=b,float=t,label={listing:config}] \begin{Verbatim}[commandchars=\\\{\}] \small \dred{"data_dir"}: \dred{"IMDb-wiki"}, \dred{"join_type"}: \dred{"INNER"}, \textcolor{teal}{# or "LEFT", "RIGHT", "FULL"} \dred{"left_size"}: 1, \dred{"right_size"}: 1, \end{Verbatim} \end{lstlisting} } \begin{lstlisting}[frame=single,caption={Core configuration lines annotated with options.},captionpos=b,float=t,label={listing:config}, language=Python,basicstyle=\small,commentstyle=\textcolor{teal},stringstyle=\dred] "data_dir": "IMDb-wiki", "join_type": "INNER", # or "LEFT", "RIGHT", "FULL" "left_size": 1, "right_size": 1, \end{lstlisting} We generate each result in Figure~\ref{fig:lesion} by altering the following unsurfaced options: number of encoders, encoder intialization, encoder finetuning (boolean), fraction of supervision, negative sampler. Users can additionally specify lower-level hyperparameters, which we fix across our experiments: epochs, batch size, embedding size, pooling type, tokenizer, learning rate, loss function parameters. \eat{ \subsubsection{FJ: 1 Line Changed} \label{case:FJ} As an FJ task is symmetric (i.e., there is no difference between which dataset is considered the base or auxiliary for the downstream task), \textsc{Ember}\xspace can rely on the default configuration and indexing optimization to index the smaller of the two tables. This requires a change in the input directory path in the config file. \subsubsection{EM: 1 or 2 Lines Changed} \label{case:EM} EM tasks are symmetric. Thus, we rely on the indexing optimization to index the smaller of the two tables. As the output task is based on pairwise labels, given a pair of records that refer to as the query and target, we define a positive match as one where the target record is in the set of retrieved neighbors when querying \textsc{Ember}\xspace's index with the query record. The default configuration retrieves a single neighbor, and requires a single config change. To retrieve multiple neighbors requires an additional line changed. First, we can simply treat the closest retrieved record as a predicted positive example, and all other records as negatives. Our result post-processing script consists of a 9-lines of python code to process the retrieved results and compute the necessary precision, recall, and F1 metrics. \subsubsection{S: 2 Lines Changed} \label{case:IR} We denote the dataset with the queries as the base dataset, and the passage collection as the auxiliary dataset as the goal is to retrieve passages relevant to each query. This is the configuration set by \textsc{Ember}\xspace's default indexing optimization, as the passage collection is the larger of the two. Thus, we preserve the default configuration, but modify the \texttt{retriever}\xspace to return the top 10 most related \texttt{record}s\xspace, and add a post-processing module that computes MRR. This requires 2 changes to the config file, and our post-processing module consists of 11 lines of code. \subsubsection{QA: 2 Lines Changed} \label{case:QA} For the QA task, we denote the question dataset as the base dataset, and the collection of sentences as the auxiliary dataset. The sentence corpus is smaller than the question corpus, thus, we override the indexing optimization. As the SQuAD corpus is based off Wikipedia, the dataset is of the same vocabulary as the pretraining corpus used by BERT. Thus, \textsc{Ember}\xspace does not perform MLM pretraining by default. Overriding the indexing optimization requires one configuration line edited. \subsubsection{R Application A: 1 Line Changed} \label{case:rec} As both datasets are the same size, the choice of base and auxiliary dataset is irrelevant. This is a standard context enrichment problem, thus we preserve the default configuration for the join task. \subsubsection{R Application B: 3 or 5 Lines Changed} One means of solving the second application is to identify movies in the test set that are similar to those in the train set (with ratings), and aggregate the rating of the similar movies as the predicted rating. \textsc{Ember}\xspace can perform this operation with similarity defined in a single hop, in terms of the labeled training data, or in two hops, by first going through the Wikipedia data. We report the performance of both. In either instance---as there are no labeled examples connecting the train and test data---users retain the default operator configuration up to the representation learning step. In the first method, users configure \textsc{Ember}\xspace to index labeled IMDb training data (with ratings), and retrieve records related to the test data (without ratings) with a \texttt{retriever}\xspace set to return multiple related (labeled) records. The user then post-processes the output by averaging the labels of the returned \texttt{record}s\xspace. This requires 3 lines of config changes, and a 7-line post-processing module. In the second method, users configure \textsc{Ember}\xspace to index both the train Wikipedia and IMDb dataset. Following a two-hop methodology, users then configure a standard \texttt{retriever}\xspace over the Wikipedia index that returns the closest Wikipedia summary to each test IMDb record. Users configure a second \texttt{retriever}\xspace over the IMDb train dataset that returns the closest labeled IMDb instances to each previously retrieved Wikipedia summary, which can then be post-processed via averaging. This requires 5 lines of config changes, and a 7-line post-processing module } \subsubsection{Dependence on Labeled Data} A key user input is labeled examples of relevant record pairs. With the exception of MS MARCO, we use all available labeled examples of \textit{relevant pairs} in Table~\ref{tab:baselines} and Figure~\ref{fig:lesion}. In MS MARCO, we use 2.5M of the 397M of the provided labeled \textit{triples}, which is just $0.63\%$ of the provided triples. For the remaining datasets, we evaluate how many labeled examples are required to match performance of our reported results. We found that 9 of the 17 datasets required all of the provided examples. The remaining datasets required $54.4\%$ of labeled relevant data on average to meet Recall@1 performance, and $44.5\%$ for Recall@10. In the best case, for EM-S DBLP-ACM, only $30\%$ and $1\%$ of the data is required to achieve the same Recall@1 and Recall@10, respectively. \section{Introduction} Machine learning (ML) systems that extract structural and semantic context from unstructured datasets have revolutionzed domains such as computer vision~\citep{alexnet} and natural language processing~\citep{bert,gpt2}. Unfortunately, applying these sytems to structured and semi-structured data repositories that consist of datasets with pre-defined schemas is challenging as their context is often \textit{fragmented}: they frequently scatter information regarding a data record across domain-specific datasets with unique schemas. For instance, in Figure~\ref{fig:example}B, information regarding \textsc{Asics} shoes is scattered across three catalogs with unique schemas. These datasets adhere to fixed schemas that are optimized for task-specific querying, and often lack explicit linking keys, such as primary key-foreign key (KFK) relationships. This constrains users to a single view of an entity that is specialized for a specific business need. \begin{figure} \includegraphics[width=\columnwidth]{figures/tables.pdf} \caption{An end-to-end task requiring context enrichment. Predicting the rating of and recommending a new product (\texttt{A82}), requires relating the Asics products (highlighted in dark gray) via a keyless join (top). This process is manual due to data heterogeneity---we aim to automate it (bottom).} \label{fig:example} \vspace{-1em} \end{figure} Associating these fragmented data contexts is critical in enabling ML-powered applications over such datasets---a process we denote as \emph{context enrichment}---yet is a heavily manual endeavor due to task and dataset heterogeneity. Engineers develop solutions for context enrichment tailored to their task, such as similarity-based blocking in data integration~\citep{blocking}, retriever models in question answering~\citep{retriever}, or retrieval functions in search~\citep{bm25} (see Section~\ref{sec:applications}). Constructing these independent solutions is repetitive, time-consuming, and results in a complicated landscape of overlapping, domain-specific methods. For instance, consider the scenario depicted in Figure~\ref{fig:example}: \vspace{-7pt} \emph{\\An e-commerce company has a proprietary product catalog, and aggregates product information from several external vendors to perform market analysis. Each vendor uses a unique product catalog, each with unique product representations (i.e., schema) ranging from free-form text to tabular product descriptions; products may overlap and evolve (Figure~\ref{fig:example}B). Given normalized tables containing user and rating data, an engineer wishes to estimate the rating for a candidate new product (\texttt{A82}) and identify users to recommend the product to (Figure~\ref{fig:example}A). } \vspace{5pt} The engineer must first perform context enrichment by joining information across tables to extract features that capture similarities between the new (\texttt{A82}) and existing (\texttt{A80}, \texttt{P8}) products. They can then estimate the product rating, and recommend the new product to users based on how they rated related products. The classic data management approach is to denormalize datasets using KFK joins. This fails to solve the problem due to two reasons. First, not all tables can be joined when relying on only KFK relationships (e.g., there is no KFK relationship between Catalog B and Catalogs A or C). Second, even when KFK relationships exist, as between Catalogs A and C (\textsc{\texttt{ITEM}}), relying on only KFK semantics fails to capture the similarity between \texttt{A82} and \texttt{A80}. Alternatively, the engineer can rely on similarity-based join techniques, as in data blocking~\citep{blocking}, built to avoid exhaustive, pairwise comparison of potentially joinable records. However, as we show in Section~\ref{subsec:general}, the optimal choice of join operator to maximize recall of relevant records is task-dependent, and may not scale at query time when new records arrive. The engineer must first note that the \texttt{Description} column in Catalog A relates to the \texttt{Brand} and \texttt{Model} columns in Catalog B and the \texttt{Size}, \texttt{Make}, and \texttt{Color} columns in Catalog C. They can then select a custom join based on table properties: for matching primarily short, structured data records, they may want to join based on Jaccard similarity, whereas BM25 may be better suited for purely textual records (see Table~\ref{tab:baselines}). As database semantics do not natively support these \emph{keyless joins} that require similarity-based indexing, joining arbitrary catalogs remains heavily manual---even large companies rely on vendors to categorize listings, which results in duplicate listings.\footnote{https://sell.amazon.com/sell.html} To counter this manual process, we draw inspiration from recent no-code ML systems such as Ludwig~\citep{ludwig}, H20.ai~\citep{h20}, and Data Robot~\citep{robot} that are rapidly shifting practitioners towards higher-level configuration-based abstractions for developing ML applications. Despite their success, these systems leave context enrichment as a user-performed data preparation step.\footnote{https://cloud.google.com/automl-tables/docs/prepare} In this paper, we evaluate how to bring no-code semantics to context enrichment. No out-of-the-box query interface surfaces the relatedness between \texttt{A80}, \texttt{A82}, and \texttt{P8} (all \texttt{Asics}, two \texttt{GT-1000}, and two \texttt{blue}), and links these records to the Ratings table with minimal intervention. The challenge in developing a no-code context enrichment system to enable this is to construct an architecture that is simultaneously: \begin{enumerate} \item \textbf{General}: Applicable to a wide variety of tasks and domains. \item \textbf{Extensibile}: Customizable for domain or downstream needs. \item \textbf{Low Effort}: Usable with minimal configuration. \end{enumerate} Our key insight to enable such a system is to simplify context enrichment by abstracting an interface for a new class of join: a \textit{learned keyless join} that operates over record-level similarity. Just as traditional database joins provide an abstraction layer for combining structured data sources given KFK relationships, we formalize keyless joins as an abstraction layer for context enrichment. We then propose \textsc{Ember}\xspace: a no-code context enrichment framework that implements a keyless join abstraction layer. \textsc{Ember}\xspace creates an index populated with task-specific embeddings that can be quickly retrieved at query time, and can operate over arbitrary semi-structured datasets with unique but fixed schema. To provide generality, \textsc{Ember}\xspace relies on Transformers~\citep{transformers} as building blocks for embedding generation, as they have demonstrated success across textual, semi-structured, and structured workloads~\citep{picket,tabert,bert,gpt2,neuraldb}. To provide extensibility, \textsc{Ember}\xspace is composed of a modular, three step architecture with configurable operators. To provide ease of use, \textsc{Ember}\xspace can be configured using a simple json-based configuration file, and provides a default configuration that works well across five tasks with a single line change per task. As input, users provide \textsc{Ember}\xspace with: \textbf{(1)} a base data source, \textbf{(2)} an auxiliary data source, \textbf{(3)} a set of examples of related records across the sources. For each record in the base data source, \textsc{Ember}\xspace returns related records from the auxiliary data source as characterized by the examples, which can be post-processed for downstream tasks (e.g., concatenated or averaged). We present \textsc{Ember}\xspace's three-step modular architecture that enables index construction via Transformer-based embeddings to facilitate related record retrieval: preprocessing, representation learning, and joining (Figure~\ref{fig:overview}). \eat{ \begin{enumerate} \item A base data source \item An auxiliary data source \item A set of examples of related records across the sources \end{enumerate} } \minihead{Preprocessing} \textsc{Ember}\xspace transforms records from different data sources to a common representation, which allows us to apply the same methods across tasks. By default, \textsc{Ember}\xspace uses operators that convert each record to a natural language sentence for input to a Transformer-based encoder, which we optionally pretrain using self-supervision. We demonstrate that depending on the data vocabulary, encoder pretraining to bootstrap the pipeline with domain knowledge can increase recall of relevant records by up to \red{20.5\%}. \begin{figure} \includegraphics[width=\columnwidth]{figures/overview.pdf} \caption{\textsc{Ember}\xspace's interface for context enrichment. \textsc{Ember}\xspace retrieves related auxiliary records for each base record.} \label{fig:overview} \vspace{-1em} \end{figure} \minihead{Representation Learning} \textsc{Ember}\xspace tunes the preprocessed representations to identify contextually similar records as defined by supervised examples. Learning this representation is task-dependent: we show that a natural approach of using pretrained Transformer-based embeddings with no fine-tuning performs up to three orders of magnitude worse than a fine-tuned approach, often returning less than \red{10\%} of relevant records. Pretraining in the first step can increase recall by over \red{30\%}, but this is still insufficient. Thus, \textsc{Ember}\xspace relies on operators that use supervised examples of related records and a contrastive triplet loss~\citep{tripletloss} to learn a representation that encourages similar records to be close while pushing away dissimilar records in the induced embedding space. We evaluate how many labeled examples \textsc{Ember}\xspace needs to match the performance of using all provided examples, and find that at times, \red{1\%} of the labels is sufficient, and that operators for hard negative sampling improve performance by up to \red{30\%} recall, further improving ease of use. \minihead{Joining} \textsc{Ember}\xspace quickly retrieves related records using the tuned representations to perform the keyless join. \textsc{Ember}\xspace populates an index with the embeddings learned to capture record similarity, and uses optimized maximum inner product search (MIPS) to identify the nearest neighbors of a given record. This procedure allows \textsc{Ember}\xspace to capture one-to-one and one-to-many join semantics across a variety of downstream applications with low query-time overhead. We demonstrate that \textsc{Ember}\xspace meets or exceeds the performance of eight similarity-based join baselines including BM25~\citep{bm25}, Jaccard-similarity-based joins, Levenshtein distance-based joins, and AutoFuzzyJoin~\citep{autofj} with respect to recall and query runtime. Although conventional wisdom in data management often says to rely on domain-specific pipelines for context enrichment, we introduce no-code ML semantics to context enrichment and empirically show how a single system can generalize to heterogeneous downstream tasks. We report on our experiences in deploying \textsc{Ember}\xspace across five tasks: fuzzy joining, entity matching, question answering, search, and recommendation. We demonstrate that \textsc{Ember}\xspace generalizes to each, requires as little as a single line configuration change, and extends to downstream similarity-based analyses for search, entity matching, and recommendation as in Figure~\ref{fig:example}. In summary, we present the following contributions in this paper: \begin{itemize} \setlength\itemsep{.75em} \item We propose keyless joins with a join specification to serve as an abstraction layer for context enrichment. To our knowledge, this is the first work to generalize similarity-based tasks across data integration, natural language processing, search, and recommendation as a data management problem. \item We design and develop \textsc{Ember}\xspace, the first no-code framework for context enrichment that implements keyless joins, and provides an API for extending and optimizing keyless joins. \item We empirically demonstrate that \textsc{Ember}\xspace generalizes to five workloads by meeting or exceeding the recall of baselines while using \red{6} or fewer configuration line changes, and evaluate the modular design of \textsc{Ember}\xspace's default architecture. \end{itemize} \section{Joining} \label{sec:joining} In this section, we describe the last step of \textsc{Ember}\xspace's pipeline: joining. Given the \texttt{embedding}s\xspace output by the trained \texttt{encoder}s\xspace, \textsc{Ember}\xspace executes the keyless join by identifying related points across the input datasets, and processing them for downstream use. \textsc{Ember}\xspace indexes the learned \texttt{embedding}s\xspace and queries this index to find candidate related records. The \texttt{join sizes} determine the number of returned results per query, and we also allow users to configure a similarity threshold for each candidate match. We now detail the indexing and retrieval procedure, post-processing, and multi-dataset extension. \minihead{Indexing and Query Retrieval} Given two records, \textsc{Ember}\xspace computes the similarity between their \texttt{embedding}s\xspace to determine if the records are related. Many traditional solutions to our motivating applications perform such pairwise checks across all possible pairs either na\"ively or with blocking~\citep{deepmatcher, blocking, bertmarco} to identify related records. However, the choice of operator is both domain-specific, and scales quadratically at query time with the size of the input datasets and blocking mechanisms used (see Section~\ref{subsec:general}). We eliminate the need for pairwise checking by indexing our \texttt{embedding}s\xspace, which are optimized for clustering related records, and rely on efficient libraries for maximum inner product search (MIPS)~\citep{faiss}. For a \texttt{LEFT} or \texttt{RIGHT OUTER JOIN}, \textsc{Ember}\xspace constructs an index over the base ($D_0$) or auxiliary ($D_1$) datasets, respectively. \textsc{Ember}\xspace then queries the index with each \texttt{embedding}\xspace of the remaining dataset, and returns the \texttt{record}\xspace and \texttt{embedding}\xspace corresponding to the most similar records using a \texttt{retriever}\xspace operator. For a \texttt{FULL OUTER} or \texttt{INNER JOIN}, \textsc{Ember}\xspace may jointly index and query both datasets to identify related entries in either direction. By default, \textsc{Ember}\xspace only indexes the larger dataset to reduce runtime---an optimization we evaluate in Section~\ref{subsec:micros} that improves query runtime by up to \red{2.81}$\times$. \textsc{Ember}\xspace's default configuration is an \texttt{INNER JOIN}. \minihead{Post-Processing} The user-provided \texttt{join size} configures the \texttt{retriever}\xspace to return the top-$k$ records with the closest embeddings in the indexed dataset. \textsc{Ember}\xspace additionally supports threshold-based retrieval. The former is useful for applications such as search, where a downstream task may be to display the top-$k$ search results to a user in sorted order. The latter is useful for applications where there may not be related records for each record in the base dataset. \textsc{Ember}\xspace's default \texttt{retriever}\xspace is configured for a 1-to-10 join. If the task $T$ is not to simply return related records, users can construct pipelines on top of \textsc{Ember}\xspace's outputs, relying on keyless-join-based context enrichment as a key primitive. Examples of such workloads include the recommendation example from Figure~\ref{fig:example}, which we simulate as a case study in Section~\ref{subsec:extensibility}, open domain question answering, data augmentation, or applications that involve humans in the loop to verify matches or drive business needs. \minihead{Multi-Dataset Extension} The joining step may vary in the multi-dataset case in two ways. In a first scenario, each auxiliary data source $D_i$ is indexed, and the query retrieval phase will query each of these indexes and return candidate related data points for each pairwise interaction. If multiple data sources must be sequentially aligned and a DAG can be specified over this sequence, a user can chain context enrichment subroutines by querying the next index with the records retrieved by the previous subroutine; we provide a toy example of this scenario in Section~\ref{subsec:extensibility} under Recommendation. \section{Learned Keyless Joins for Context Enrichment} Although the applications in Section~\ref{sec:applications} implicitly or explicitly perform the \emph{same} context enrichment, many state-of-the-art systems for these tasks re-implement and rediscover primitives across domains spanning machine learning, databases, information retrieval, and natural language processing~\citep{colbert,ditto,knnlm,rpt}. We propose learned \textit{keyless joins} as an abstraction to unify context enrichment across these tasks and provide a vehicle to develop a no-code system with out-of-the-box recall exceeding na\"ive baselines. In this section, we define keyless joins, provide a keyless join API specification, and introduce Transformer models that enable general keyless joins. \subsection{Keyless Joins: Definition and Objective} \label{subsec:keyless} Context enrichment requires a similarity-based join that operates at the record-, not schema-, level to retrieve related records without primary key-foreign key (KFK) relationships. We propose learned \emph{keyless joins} as an abstraction to enable this functionality. The goal of a keyless join is to quantify the relatedness of records across different datasets to identify records referring to similar entities. A keyless join must learn a common embedding space $\mathbf{X}$ for all records $d_{ij}$ across datasets $D_0 \cup D$ that reflects entity similarity. For each $\mathbf{D_i}$, a keyless join learns a function $F_i: \mathbf{D_i} \rightarrow \mathbf{X}$ that maps elements of $D_i$ to the space $\mathbf{X}$. We denote each transformed data point $F_i(d_{ij})$ as $x_{ij}$. This mapping must be optimized such that related values map to similar feature vectors in $\mathbf{X}$ and unrelated values map to distant feature vectors in $\mathbf{X}$: $sim(x_{ij}, x_{kl}) > sim(x_{ij}, x_{mn})$ implies that the $j^{th}$ entity in the $i^{th}$ dataset is more closely related to the $l^{th}$ entity in the $k^{th}$ dataset than the $n^{th}$ entity in the $m^{th}$ dataset. For instance, if we define similarity with respect to an $\ell_p$-norm, the above condition is equal to optimizing for $\|x_{ij} - x_{kl}\|_p < \|x_{ij} - x_{mn}\|_p$. \begin{figure*} \includegraphics[width=\linewidth]{figures/full_pipeline.pdf} \caption{\textsc{Ember}\xspace system architecture.} \label{fig:pipeline} \end{figure*} \subsection{Join Specification for Context Enrichment} \label{subsec:keyless_spec} We propose a minimal join specification for our applications using keyless joins as a building block (Listing~\ref{listing:spec}). Given a pair of data sources to join (\texttt{base\_table\_ref}, \texttt{aux\_table\_ref}), and examples of similar records across them (\texttt{supervision}), users first specify the \texttt{join type}: an inner join to only return enriched records, or outer join (left, right, full) to return enriched and unenriched records. Users then specify the \texttt{join size}: how many records from one data source joins to a single record in the other data source to indicate one-to-one, one-to-many, or many-to-many semantics. As output, joined tuples (matches) between the two tables are the most similar records across them as learned using the keyless join objective. Results are ranked in order of greatest entity similarity, and the top k results are returned based on \texttt{join size}. \eat{ \begin{listing}[t] \small \begin{minted}{python} base_table_ref [join_type] "KEYLESS JOIN" aux_table_ref "LEFT SIZE" integer "RIGHT SIZE" integer "USING" supervision; join_type = "INNER" | "LEFT" | "RIGHT" | "FULL"; \end{minted} \caption{Keyless join specification and syntax, which defaults to an inner join.} \label{listing:spec} \end{listing} } \begin{lstlisting}[frame=single,caption={Keyless join specification (inner join default).},captionpos=b,float=t,label={listing:spec}, language=Python,commentstyle=\textcolor{teal},stringstyle=\dred,showstringspaces=false,belowskip=-2pt] base_table_ref [join_type] "KEYLESS JOIN" aux_table_ref "LEFT SIZE" integer "RIGHT SIZE" integer "USING" supervision; join_type = "INNER" | "LEFT" | "RIGHT" | "FULL"; \end{lstlisting} For instance, an entity matching application is written as follows to retrieve a single matching record between each data source: \vsepfbox{% \parbox{.975\linewidth}{% \small{\texttt{% entity\_mentions\_A \dred{INNER KEYLESS JOIN} entity\_mentions\_B \\ \dred{LEFT SIZE} 1 \dred{RIGHT SIZE} 1 \dred{USING} matching\_mentions; }} }% } \eat{\texttt{ \dred{entity\_mentions\_A} INNER KEYLESS JOIN \dred{entity\_mentions\_B} LEFT SIZE \dred{1} RIGHT SIZE \dred{1} }} A search application is written as follows to retrieve 10 documents for each search query, else return the unenriched query: \\ \vsepfbox{% \parbox{.975\linewidth}{% \small{\texttt{% query\_corpus \dred{LEFT KEYLESS JOIN} document\_corpus \\ \dred{LEFT SIZE} 1 \dred{RIGHT SIZE} 10 \dred{USING} relevant\_docs\_for\_query; }} }% } A recommendation application is written as follows to retrieve 10 items for each user, and 20 users who like each item: \\ \vsepfbox{% \parbox{.975\linewidth}{% \small{\texttt{% user\_database \dred{INNER KEYLESS JOIN} product\_database \\ \dred{LEFT SIZE} 20 \dred{RIGHT SIZE} 10 \dred{USING} relevant\_docs\_for\_query; }} }% } In the remainder of paper, we describe our prototype system that implements this keyless join abstraction layer for enrichment. \subsection{Background: Transformer-Based Encoders} \label{subsec:transformer} Our main tools for creating a representation optimized for the objective in Section~\ref{subsec:keyless} are Transformers~\citep{transformers}, as they have demonstrated success across a range of structured, semi-structured, and unstructured domains~\citep{tabert,bert,gpt2,neuraldb,picket}. They consist of an encoder-decoder architecture, where the Transformer first encodes the input to an intermediate representation, and then decodes this representation to produce the end output. Stacking encoder (e.g., BERT~\citep{bert}) or decoder (e.g., GPT-2~\citep{gpt2}) modules allows us to learn high-quality word embeddings that can either be used for a wide array of downstream applications. We focus on BERT-based embeddings. BERT embeddings used for a downstream task are trained in a two-step procedure. The first step is self-supervised pretraining using a masked language model (MLM) objective: a random subset of tokens are masked, and the model must predict each masked token given the surrounding text as context. Pretraining is performed with general purpose corpora such as Wikipedia. The second step is task-specific fine-tuning. Additional layers are appended to the final layer of the pretrained model based on the downstream task, and all model parameters are updated given small amounts of downstream supervision. Rather than relying solely on fine-tuning, an additional MLM pretraining step can be performed prior to fine-tuning to introduce additional domain knowledge. \section{0pt}{1pt plus 2pt minus 1pt}{1pt plus 2pt minus 1pt} \begin{document} \title{\textsc{Ember}\xspace: No-Code Context Enrichment via \\ Similarity-Based Keyless Joins} \eat{\author{Ben Trovato} \affiliation{% \institution{Institute for Clarity in Documentation} \streetaddress{P.O. Box 1212} \city{Dublin} \state{Ireland} \postcode{43017-6221} } \email{[email protected]} } \author{Sahaana Suri, Ihab F. Ilyas$^\ast$, Christopher R\'e, Theodoros Rekatsinas$^\dagger$} \affiliation{% \institution{Stanford University, University of Waterloo$^\ast$, UW-Madison$^\dagger$} } \input{abstract} \maketitle \pagestyle{\vldbpagestyle} \begingroup\small\noindent\raggedright\textbf{PVLDB Reference Format:}\\ \vldbauthors. \vldbtitle. PVLDB, \vldbvolume(\vldbissue): \vldbpages, \vldbyear.\\ \href{https://doi.org/\vldbdoi}{doi:\vldbdoi} \endgroup \begingroup \renewcommand\thefootnote{}\footnote{\noindent This work is licensed under the Creative Commons BY-NC-ND 4.0 International License. Visit \url{https://creativecommons.org/licenses/by-nc-nd/4.0/} to view a copy of this license. For any use beyond those covered by this license, obtain permission by emailing \href{mailto:[email protected]}{[email protected]}. Copyright is held by the owner/author(s). Publication rights licensed to the VLDB Endowment. \\ \raggedright Proceedings of the VLDB Endowment, Vol. \vldbvolume, No. \vldbissue\ % ISSN 2150-8097. \\ \href{https://doi.org/\vldbdoi}{doi:\vldbdoi} \\ }\addtocounter{footnote}{-1}\endgroup \ifdefempty{\vldbavailabilityurl}{}{ \vspace{.3cm} \begingroup\small\noindent\raggedright\textbf{PVLDB Artifact Availability:}\\ The source code, data, and/or other artifacts have been made available at \url{\vldbavailabilityurl}. \endgroup } \input{intro} \input{application} \input{keyless} \input{ember} \input{preprocessing} \input{representation} \input{joining} \input{evaluation} \input{relwork} \input{conclusion} \eat{\begin{figure*} \includegraphics[width=\textwidth]{figures/lesion_s.pdf} \caption{alternative to lesion -- what do you think?} \label{fig:lesion} \vspace{-1em} \end{figure*}} \bibliographystyle{ACM-Reference-Format} \section{Preprocessing} \label{sec:preprocessing} In this section, we describe the first step of \textsc{Ember}\xspace's pipeline: preprocessing. Users provide base and auxiliary datasets with examples of related records across the two. \textsc{Ember}\xspace first processes the input datasets so all records are represented in a comparable format. \textsc{Ember}\xspace then pretrains the \texttt{encoder}s\xspace for the representation learning step. We describe these phases, and then multi-dataset extension. \minihead{Data Preparing (Figure~\ref{fig:pipeline}A.1)} This phase converts each \texttt{record}\xspace $d_{ij}$ into a format that can be used for downstream Transformer-based \texttt{encoder}s\xspace regardless of schema. Motivated by recent work in representing structured data as sentences~\citep{tabert, neuraldb}, \textsc{Ember}\xspace's default pipeline uses a \texttt{sentence}\xspace \texttt{preparer}\xspace $P$ to convert input \texttt{record}s\xspace $d_{ij}$ into \texttt{sentence}s\xspace $P(d_{ij}) = s_{ij}$. Each key-value pair in $d_{ij}$ is converted to a string and separated by the \texttt{encoder}\xspace's separator token as \texttt{``key\_1 value\_1 [SEP] key\_2 value\_2 [SEP]..."} (Figure~\ref{fig:preprocess}). \minihead{Optional Pretraining (Figure~\ref{fig:pipeline}A.2)} Our default BERT-based \texttt{encoder}\xspace is trained over natural language corpora (Wikipedia and BookCorpus~\citep{wiki,bookcorpua}). Structured data is often domain-specific, and is of a different distribution than natural language. Thus, we find that bootstrapping the pipeline's \texttt{encoder}s\xspace via additional pretraining can improve performance by up to \red{2.08$\times$}. \textsc{Ember}\xspace provides a pretraining configuration option that is enabled by default. Users can pretrain the pipeline's \texttt{encoder}s\xspace via BM25-based self-supervision (out-of-the-box) or by developing weak supervision-based \texttt{labeler}s\xspace (custom-built). We add a standard Masked Language Modeling (MLM) head to each pipeline \texttt{encoder}\xspace, and pretrain it following the original BERT pretraining procedure that fits a reconstruction loss. To encourage the spread of contextual information across the two tables, we concatenate one \texttt{sentence}\xspace from each table to one other as pretraining input as \texttt{``$s_{ij}$ [SEP] $s_{kl}$"} (Figure~\ref{fig:preprocess}). We select \texttt{sentence}\xspace pairs that are likely to share information in an unsupervised manner via BM25, a bag-of-words relevance ranking function~\citep{bm25}, though any domain-specific unsupervised similarity join can be used, such as from Magellan~\citep{magellan} or AutoFJ~\citep{autofj}. We evaluate BM25-based MLM pretraining in Section~\ref{subsec:micros}. During development, we explored learning conditional representations of each table given the other by selectively masking one table's \texttt{sentence}s\xspace, but found no change in performance compared to uniform masking. \minihead{Multi-Dataset Extension} Depending on the encoder configuration used in the multi-dataset case, the BM25-based pretraining step will be applied to all \texttt{sentence}s\xspace across all datasets at once (anchored from the base table), or each dataset pairwise. \begin{figure} \includegraphics[width=\columnwidth]{figures/preprocessing.pdf} \caption{Examples of the data preparing and pretraining phases of the preprocessing architecture step.} \label{fig:preprocess} \vspace{-1em} \end{figure} \section{Related Work} \label{sec:relwork} \minihead{Similarity Joins} Similarity-based, or fuzzy, joins often focus on the unsupervised setting~\citep{surajit,fj1,fj2}. State-of-the art systems such as AutoFJ~\citep{autofj} are tailored for the case where tables can be joined using exact keys or shared phrases that do not differ greatly in distribution (e.g., our EM tasks)---not complex context enrichment. \textsc{Ember}\xspace generalizes to arbitrary notions of similarity and join semantics at the expense of supervised pairs, and can also leverage unsupervised methods for negative sampling or MLM pretraining. \minihead{Automated Machine Learning} Automated Machine Learning (AML) systems aim to empower users to develop high-performance ML pipelines minimal intervention or manual tuning. They support various types of data preprocessing, feature engineering, model training and monitoring modules. Examples of AML tools include Ludwig~\citep{ludwig}, Overton~\citep{overton}, Google Cloud AutoML~\citep{gcloud}, and H20.ai~\citep{h20}. However, these platforms do not focus on context enrichment, leaving it as an exercise for users to perform prior to data ingestion. \minihead{Relational Data Augmentation} Relational data augmentation systems seek to find new features for a downstream predictive task by deciding whether or not to perform standard database joins across a base table and several auxiliary tables~\citep{hamlet, hamletpp, arda}. Similar to context enrichment, these systems aim to augment a base table for a downstream ML workload. However, they assume the existence of KFK relationships that simply must be uncovered. \minihead{Data Discovery} Data discovery systems find datasets that may be joinable with or related to a base dataset, and to uncover relationships between different datasets using dataset schema, samples, and metadata~\citep{dd1,dd2,dd3,dd4,dd5,dd6,dd7}. These systems typically surface KFK relationships, and do not tune for downstream ML workloads. \minihead{NLP and Data Management} A recurring aim in data management is to issue natural language commands to interface with structured data~\citep{nlidb,csc}. Recent work in Neural Databases~\citep{neuraldb} aims to replace standard databases with Transformer-powered schemaless data stores that are updated and queried with natural language commands. Related to this work are systems that leverage advances in NLP to provide domain-specific functionality, such as converting text to SQL~\citep{text2sql1,text2sql2}, correlating structured and unstructured data~\citep{tabert}, enabling interpretable ML over structured data~\citep{tabnet}, or automating data preparation~\citep{rpt}. We focus on the broader problem of context enrichment of entities for downstream tasks. To our knowledge, this has not been formally addressed in the literature, which often assumes entity information has been resolved~\citep{neuraldb}. \section{Representation Learning} \label{sec:representation} In this section, we describe the second step of \textsc{Ember}\xspace's pipeline: representation learning. Given the \texttt{sentence}s\xspace and optionally pretrained \texttt{encoder}s\xspace from the first step, \textsc{Ember}\xspace fine-tunes the \texttt{encoder}s\xspace such that \texttt{embedding}s\xspace from related records are close in embedding space. These \texttt{embedding}s\xspace are then passed to the final pipeline step. Users can choose how many \texttt{encoder}s\xspace to configure, the \texttt{encoder}\xspace architecture and output dimension, and how to train the \texttt{encoder}s\xspace, which we now detail prior to describing multi-dataset extension. \minihead{\texttt{Encoder} configuration} \textsc{Ember}\xspace provides a choice of training independent \texttt{encoder}s\xspace, $E_i$ for each data source, or using a single \texttt{encoder}\xspace $E_0$ common to all data sources. In all of our scenarios, using a single, common \texttt{encoder}\xspace performs best, sometimes by over an order of magnitude, and is set as \textsc{Ember}\xspace's default configuration. In our tasks, we found that using separate encoders perturbs the representations such that exact matches no longer share a representation---thus, the encoders must relearn correspondences, and often fail to. However, to extend \textsc{Ember}\xspace to non-textual data (e.g., images, video, text-image for image captioning or joint sentiment analysis, or text-audio tasks), users must leverage source-specific \texttt{encoder}s\xspace---thus, we provide them as a configurable option. \minihead{\texttt{Encoder} architecture} \textsc{Ember}\xspace lets users configure each \texttt{encoder}\xspace's base architecture and the size of the learned \texttt{embedding}s\xspace. Users can choose BERT$_{\text{base}}$ or DistilBERT$_{\text{base}}$ as the core architecture; \textsc{Ember}\xspace's default is the 40\% smaller, and 60\% faster DistilBERT model. We use models from HuggingFace Transformers~\citep{hf}; thus, integrating new architectures requires few additional lines of code. We remove the MLM head used in the preprocessing step for optional pretraining, and replace it with a fully connected layer that transforms BERT's default 768-dimensional output to a user-specified \texttt{embedding}\xspace output dimension, $d$. The output of the fully connected layer is a $d$-dimensional embedding for each input token. Users can choose one of two types of aggregation methods that will return a single $d$-dimensional output per input \texttt{sentence}\xspace: averaging all of the embeddings, or using the embedding of the leading \texttt{CLS} token that BERT appends to its input data (Figure~\ref{fig:preprocess}). \textsc{Ember}\xspace defaults to \texttt{CLS}-based aggregation with a 200-dimensional output. \minihead{\texttt{Encoder} training} The \texttt{encoder}s\xspace' goal is to learn a representation (\texttt{embedding}\xspace), for the data sources such that \texttt{sentence}s\xspace that refer to similar entities are grouped in the underlying embedding space. Recall that to perform a keyless join under an $\ell_p$-norm, each \texttt{encoder}\xspace must learn a function that maps elements of $D_i$ to the space $\mathbf{X}$, such that $\|x_{ij} - x_{kl}\|_p < \|x_{ij} - x_{mn}\|_p$ when the $j^{th}$ entity in the $i^{th}$ dataset is more closely related to the $l^{th}$ entity in the $k^{th}$ dataset than the $n^{th}$ entity in the $m^{th}$ dataset. We directly optimize for this objective function by training \texttt{encoder}s\xspace using a contrastive, triplet loss together with user-provided supervision. Given an anchor \texttt{record}\xspace $d_{0\text{a}}$ from $D_0$, and \texttt{record}s\xspace $d_{1\text{p}}$ and $d_{1\text{n}}$ in $D_1$ that are related and unrelated to $d_{0\text{a}}$, respectively, let $F_0(d_{0\text{a}}) = x_{0\text{a}}$, $F_1(d_{1\text{p}}) = x_{1\text{p}}$, and $F_1(d_{1\text{n}}) = x_{1\text{n}}$ be their \texttt{embedding}s\xspace following the composition of the \texttt{sentence}\xspace \texttt{preparer}\xspace $P$ and \texttt{encoder}\xspace $E_i$ operators ($F_i=E_i \circ P$). We minimize the triplet loss, defined as: $$ \mathcal{L}(x_{0\text{a}}, x_{1\text{p}}, x_{1\text{n}}) = \max\{\|x_{0\text{a}} - x_{1\text{p}}\|_p, \|x_{0\text{a}} - x_{1\text{n}}\|_p + \alpha, 0\}$$ \noindent where $\alpha$ is a hyperparameter controlling the margin between related and unrelated \texttt{embedding}s\xspace. Users could use an alternative \texttt{loss}\xspace function: a cosine similarity loss would provide representations that similarly encourage related points to be close and unrelated points to be far, and a standard binary cross-entropy loss may be used as well, where the final layer in the trained \texttt{encoder}\xspace would be the end embeddings. However, they do not explicitly optimize for \textit{relative} distances between related and unrelated records. Users often have examples of related pairs, but no unrelated examples to form triples. In our tasks, only the search workload provides triples, while the rest provide lists of related pairs, which we represent with a \texttt{labeler}\xspace. As a result, we provide negative \texttt{sampler}\xspace operators to convert \texttt{labeler}s\xspace that operate over pairs to the triples required by the triplet \texttt{loss}\xspace. If the user-provided \texttt{labeler}\xspace already contains a related and unrelated example for a \texttt{record}\xspace, we form a triple using these examples. If a \texttt{record}\xspace does not contain a related and unrelated example, for each \texttt{record}\xspace $d_{0j}$ in $D_0$ with a labeled related record, we use either a random \texttt{sampler}\xspace or a stratified hard negative \texttt{sampler}\xspace. The random \texttt{sampler}\xspace selects a \texttt{record}\xspace at random (that is not a supervised related pair) as an example unrelated \texttt{record}\xspace. The stratified \texttt{sampler}\xspace provides tiers for different degrees of relatedness for the negative examples---a user can specify a region of hard examples to sample from, given prior domain knowledge. We provide a default stratified \texttt{sampler}\xspace with a single tier of relatedness defined using BM25 or Jaccard similarity, though any unsupervised join method can be used (including AutoFJ~\citep{autofj}). We show that a hard negative \texttt{sampler}\xspace improves recall by up to \red{30\%} compared to a random \texttt{sampler}\xspace in Section~\ref{subsec:micros}. \minihead{Multi-Dataset Extension} The \texttt{encoder}\xspace configuration and architecture are unchanged in the multi-dataset case. There are two options for the \texttt{encoder}\xspace training procedure. The first scenario follows the context enrichment problem definition---where a base table $D_0$ must be augmented with several auxiliary data sources $D$. In this case, each \texttt{encoder}\xspace can be trained pairwise with $D_0$ and $D_i$ as described above. In the case where multiple data sources must be aligned in sequence, a user can successively apply \textsc{Ember}\xspace over a data DAG created using their prior knowledge---effectively creating several, sequential context enrichment problems as described in Section~\ref{subsec:target} for multi-hop question answering. Else, \textsc{Ember}\xspace can induce a DAG and sequentially traverse the space of possible keyless joins based on the cardinality of each dataset, in ascending order.
{'timestamp': '2021-06-04T02:06:31', 'yymm': '2106', 'arxiv_id': '2106.01501', 'language': 'en', 'url': 'https://arxiv.org/abs/2106.01501'}
arxiv
\section*{Acknowledgements} We wish to thank the anonymous reviewers for their valuable feedback. \clearpage \bibliographystyle{named} \section{Conclusion} \label{sec:conclusion} We present a novel and effective Spline positional encoding scheme for learning 3D implicit signed distance fields from raw point clouds. The spline positional encoding enhances the representation power of MLPs and outperforms the existing positional encoding schemes like Fourier positional encoding and \textsc{Siren} in recovering SDFs. In the future, we would like to explore \textsc{Spe} in the following directions. \paragraph{Non-uniform spline knots.} Compared with uniform knots we used in spline functions, non-uniform knots provide more freedom to model complex and non-smooth spline functions and would also help reduce the parameter sizes of \textsc{Spe} while keeping the same approximation power. \paragraph{Composition of positional encoding.} As positional encoding has proved to be an effective way to distinguish nearby points in a higher dimension space, it would be interesting to composite multiple scale \textsc{Spe}s to strengthen the capability of \textsc{Spe} while using fewer parameters for each \textsc{Spe}. \section{Introduction} \label{sec:intro} Implicit neural representations learned via multilayer perceptrons (MLPs) have been proved to be effective and compact 3D representations~\cite{Park2019,Mescheder2019,Chen2019} in computer vision and graphics fields. The MLPs take 3D coordinates as input directly, denoted by \emph{coordinate-based MLPs}, and output the corresponding signed distance values or the occupancy values. They essentially define continuous implicit functions in 3D space whose zero level set depicts shape surfaces. Compared with conventional 3D discrete representations like point clouds or voxels, the MLP-based implicit representation has infinite resolutions due to its continuous nature, while being extremely compact. Apart from representing 3D shapes, coordinate-based MLPs are also capable of representing images, 3D textures, and 5D radiance fields, serving as general-purpose mapping functions. \begin{figure} \centering \begin{overpic}[width=1\linewidth]{teaser} \put(7, -3){\small \textsc{Gt}} \put(23, -3){\small (a) \textsc{Igr}} \put(40.5, -3){\small (b) \textsc{Siren}} \put(61, -3){\small (c) \textsc{Fpe}} \put(80, -3){\small (d) \textsc{Spe}} \end{overpic} \vspace{0.1mm} \caption{SDF learning via MLP-based methods. Upper: the extracted zero level set via marching cubes. Lower: a slice view of SDFs. \textsc{Siren}~\protect\cite{Sitzmann2020}, \textsc{Fpe}~\protect\cite{Tancik2020} and our \textsc{Spe} fit the input point coordinates and normals well, but \textsc{Fpe} contains many unwanted small branches. The SDFs from \textsc{Igr}~\protect\cite{Gropp2020} and \textsc{Spe} are more faithful to the ground-truth, while \textsc{Spe} recovers more details. } \label{fig:teaser} \end{figure} In this paper, we are interested in learning the signed distance field (SDF) effectively from an unorganized input point cloud sampled from a 3D shape, by MLPs. SDF defines the distance of a given point $\mx$ from the shape surface, with the sign determined by whether $\mx$ is inside the shape volume or not. SDFs are needed by a broad range of applications~\cite{Jones2006}, including, but not limited to, 3D reconstruction~\cite{Curless1996}, constructive solid geometry (CSG), collision detection~\cite{Bridson2015} and volume rendering~\cite{Hart1996}. The recent MLP-based approaches~\cite{Gropp2020,Atzmon2020} introduce the Eikonal equation constraint $|\nabla F(\mx)|\equiv 1$ to the mapping function $F: \mx \in \mathbb{R}^3$ to enforce $F$ to be an SDF, while its zero level set passes through the point cloud. However, due to the ``spectral bias'' of neural networks~\cite{Rahaman2019,xu2019training,Mildenhall2020,Tancik2020}, coordinate-based MLPs with ReLU activation are incapable of reconstructing high-frequency details of surfaces. An example produced by a coordinate-based MLP --- \textsc{Igr}~\cite{Gropp2020} is shown in \cref{fig:teaser}(a), where the output shape is over-smoothed compared to the ground-truth. To circumvent this problem, \textsc{Siren}~\cite{Sitzmann2020} uses Sine as the activation function in place of ReLU to improve the expressiveness of MLPs, and the Fourier Positional Encoding (abbreviated as \textsc{Fpe})~\cite{Mildenhall2020,Tancik2020,Zhong2020} is proposed to improve network capability by lifting input coordinates to a high-dimensional Fourier space via a set of sinusoidal functions before feeding the coordinates as the input of MLPs. However, both approaches fail to recover SDFs in good quality and are even worse than \textsc{Igr} (see \cref{fig:teaser}(b)\&(c)), although their zero level sets may fit the point cloud well. In this paper, we propose a novel \emph{Spline Positional Encoding} (abbreviated as \textsc{Spe}), with which the MLP can not only recover the high-frequency details of the surface but also recover the SDF well, as shown in \cref{fig:teaser}(d). Our \textsc{Spe} maps the input coordinates into a high-dimensional space via projecting them onto multiple trainable Spline functions, instead of hard-coded sinusoidal functions as \textsc{Fpe}. The Spline functions are defined as the weighted sum of a series of uniformly spaced local-support B-Spline bases, and the weights are trainable. As the Spline function can be used to approximate other continuous functions, our \textsc{Spe} can be regarded as a generalization of \textsc{Fpe}. \textsc{Spe} greatly increases the fitting ability of MLPs to reproduce high-frequency details. By subdividing the B-Spline bases, \textsc{Spe} can also be progressively refined. Based on this property, we also design a multi-scale training scheme to help MLPs converge to better local minima, which enables our network to recover SDFs and geometric details progressively and robustly. Through experiments and ablation studies, we demonstrate the efficacy and the superiority over other state-of-the-art encoding schemes of our \textsc{Spe} on the tasks of learning SDFs from a point cloud or a set of point clouds. Additionally, to test the generalizability of \textsc{Spe}, we also apply it to image reconstruction and achieve good performance. \section{Spline Positional Encoding} \label{sec:method} In this section, we first briefly review the loss functions for learning SDFs from a point cloud in \cref{subsec:learnsdf}, then introduce our spline positional encoding and its relations to prior arts in \cref{subsec:spe}, and our training scheme in \cref{subsec:training}. \subsection{SDF Learning} \label{subsec:learnsdf} Given a set of points with oriented normals sampled from the unknown surface $\mathcal{S}$ of a 3D shape, denoted by $\mathcal{X}=\{(\mx_i, \mn_i)\}_{i \in \mathcal{I}}$, the goal is to train an MLP $F(x)$ which represents the SDF of $\mathcal{S}$ and keeps $F(\mx_i) = 0, \nabla F(\mx_i) = \mn_i$, $\forall i \in \mathcal{I}$. To ensure $F(x)$ is an SDF, an additional constraint from the Eikonal equation $\|\nabla F(x) \|=1$ is added as recommended by \cite{Gropp2020}. The final loss function is in the following form. \begin{equation} \begin{aligned} L_{sdf} = & \sum_{i \in \mathcal{I}} (F(x_i) ^2 + \tau \, \| \nabla F(\mx_i) - \mn_i \|^2) + \\ & \lambda \, \mathbb{E}_x (\| \nabla F(\mx) \| - 1)^2. \end{aligned} \label{equ:loss} \end{equation} After training, $F(\mx)$ approximates the underlying SDF induced by the input point clouds, and the zero level set $F(\mx)=0$ approximates $\mathcal{S}$, which can be extracted as a polygonal mesh via Marching Cubes~\cite{Lorensen1987}. \subsection{Spline Positional Encoding} \label{subsec:spe} \begin{figure}[t] \centering \begin{overpic}[width=0.7\linewidth]{proj} \put(47,36){\small $\mathbf{x}$} \put(101,43){\small $x^\prime$} \put(48,76){\small $y^\prime$} \put(94,34){\small $x^{\prime\prime}$} \put(39,21){\small $y^{\prime\prime}$} \put(28,1){\small $x^{\prime\prime\prime}$} \put(29,59){\small $y^{\prime\prime\prime}$} \put(53,51){\small $\mathbf{p}^\prime$} \put(52,22){\small $\mathbf{p}^{\prime\prime}$} \put(9,28){\small $\mathbf{p}^{\prime\prime\prime}$} \end{overpic} \caption{Illustration of Spline positional encoding on 2D. Point $\mx$ is projected onto three Splines along three directions. The local heights of $\mathbf{p}^\prime$, $\mathbf{p}{^\prime\prime}$, $\mathbf{p}^{\prime\prime\prime}$ with respect to their own y-axis: $y^\prime$, $y^{\prime\prime}$, $y^{\prime\prime\prime}$ form the Spline positional encoding of $\mx$. } \label{fig:spe} \end{figure} The key idea of our \textsc{Spe} is to use a set of parametric Spline functions as encoding functions. Different from \textsc{Fpe} which uses predefined sinusoidal functions, our \textsc{Spe} is trainable and optimized together with MLPs. In our implementation, we choose the B-Spline function due to its simplicity. \paragraph{B-Spline function.} We first briefly introduce the B-Spline basis and B-Spline functions. The B-Spline basis $B^i(x)$ is a locally supported function, where $B^i: \mathbb{R} \mapsto \mathbb{R}$ and $i$ is its polynomial degree. The $B^{0}(x)$ is defined as follows: \begin{equation} B^0(x) = \begin{cases} 1 & \text{if}\; |x| < 0.5; \\ 0 & \text{otherwise}. \end{cases} \end{equation} $B^i(x)$ is set to the $n^{th}$ convolution of $B^0(x)$. The linear B-Spline basis $B^1(x)$ is supported in $[-1, 1]$, and the quadratic B-Spline $B^2(x)$ is supported in $[-1.5, 1.5]$. And for simplicity, we use $B(x)$ and omit the superscript. Given an input 1D domain, we first uniformly subdivide it to $K$ segments and get $(K+1)$ knot points $\{c_i\}_{i=0}^K$, and denote the interval between two knots as $\delta$. We scale and translate the B-Spline basis $B(x)$ to each knot point, and get $B_{\delta,c_i}(x) = B(\frac{x - c_i} {\delta})$. At the $i^{th}$ node point, we define an optimizable parameter $W_i$. The parametric Spline function is defined as \begin{equation} \mathbf{\psi}(x) = \sum_{i=0}^K W_i B_{\delta,{c_i}}(x). \label{equ:spline} \end{equation} If we further define $W_i$ as a $C$-channel vector, we can obtain $C$ spline functions. \paragraph{Spline positional encoding.} Without loss of generality, we assume the input domain for training MLP is $[-1, 1]^d$. We randomly select a set of unit directions $\mathbf{D}_1, \ldots, \mathbf{D}_m$, and these directions can determine a set of line segments with the same direction passing through the origin, whose two ends are on the unit sphere. On each line segment $L_k$, we can define a spline function $\mathbf{\psi}_{k}$ within the interval $[-1,1]$. Given a point $\mx \in [-1,1]^d$, its spline positional encoding is defined as follows. We first compute the 1-D coordinate of $\mx$ with represent to each direction $\mathbf{D}_k$, denoted by $x_k$, by projecting it onto $L_k$: \begin{equation} x_k := \langle \mx, \mathbf{D}_k \rangle. \end{equation} The \textsc{Spe} of $\mx$ is defined as: \begin{equation} \begin{aligned} \mathbf{\Phi}(\mx) = [\mathbf{\psi}_{1}(x_1), ... , \mathbf{\psi}_{M}(x_M)]. \end{aligned} \label{equ:spe} \end{equation} To be able to differentiate different points in $\mathbb{R}^d$, the projection directions should be independent, and the projection direction number should be larger than $d$. The above spline positional encoding lifts the point from a $d$-dimension vector up to a $C \times M$ tensor. In our experiments, we simply sum up the $M$ projections and get a $C$ dimension positional encoding. The total number of parameters used by \textsc{Spe} is $C \times (K+1) \times M + (d-1) \times M $. Here $(d-1) \times M$ is for the projection directions. All the parameters are differentiable in \cref{equ:spe}, thus can be trained to find their optimal values. \paragraph{Relationship with prior positional encodings.} For an MLP that directly takes coordinates as input, we can define its positional encoding as $\phi(\mx)=\mx$. The Fourier positional encoding proposed by~\cite{Tancik2020,Mildenhall2020,Zhong2020} is composed of a set of sinusoidal functions with different frequencies, which can be defined as \begin{align*} \Phi(\mx) = [ &\sin(2 \pi w_1^T x), \cos(2 \pi w_1^T x), \cdots, \\ & \sin(2 \pi w_M^T x), \cos(2 \pi w_M^T x)]. \end{align*} Since the spline function with sufficient knots can well approximate the Identity, Sine, and Cosine functions, our \textsc{Spe} can be regarded as a generalization of prior positional encodings. Actually, we can properly initialize $W_i$ in \cref{equ:spline} according to \textsc{Fpe} and fix $W_i$ during the optimization process and achieve the same effect as $\textsc{Fpe}$. \subsection{Training Scheme} \label{subsec:training} \paragraph{Multi-scale optimization of \textsc{Spe}.} The B-Spline bases can be subdivided in a multi-scale manner, which is widely used in the multi-resolution optimization in Finite Element Analysis~\cite{Logan2017}. Suppose a Spline function is composed by $K$ \emph{linear} Spline bases, as defined in \cref{equ:spline}, we can refine it by subdividing the input domain to $2K$ segments and initialize the new weights $\hat{W}_i$ via the following formula: \begin{equation} \hat{W}_j = \sum_{i=0}^K W_i B_{\delta,{c_i}}(\hat{c}_j) \label{equ:refine} \end{equation} where $\hat{c}_j$ represents the $j$-{th} refined knot. Other higher-order Spline bases can also be subdivided similarly, and we omit the detailed formulas for simplicity. When training the network with the loss function, we first warm up the training process with a coarse resolution \textsc{Spe}. With a coarse \textsc{Spe}, the MLP quickly fits the low-frequency part of SDFs and provides a good initialization. Then we progressively refine \textsc{Spe} to increase the fitting ability of MLPs. In this way, our network can converge to better local minima: both the SDF away from the input points and the geometric details on the surface are better recovered. \begin{table*}[t] \tablestyle{5pt}{1.1} \scalebox{0.9}{ \begin{tabular}{l|rr|rr|rr|rr|rr|rr|rr} \toprule Model & \multicolumn{2}{c|}{Armadillo} & \multicolumn{2}{c|}{Bimba} & \multicolumn{2}{c|}{Bunny} & \multicolumn{2}{c|}{Dragon} & \multicolumn{2}{c|}{Fandisk} & \multicolumn{2}{c|}{Gargogle} & \multicolumn{2}{c}{Dfaust} \\ & \small Chamfer & \small MAE & \small Chamfer & \small MAE & \small Chamfer & \small MAE & \small Chamfer & \small MAE & \small Chamfer & \small MAE & \small Chamfer & \small MAE & \small Chamfer & \small MAE \\ \midrule \textsc{Igr} & 13.6 & \textbf{1.9} & 5.1 & 1.1 & 2.5 & \textbf{0.7} & 62.1 & 1.8 & 2.3 & 1.0 & 17.2 & 6.1 & 17.6 & \textbf{1.4} \\ \textsc{Siren} & 2.2 & 22.1 & 5.6 & 18.9 & 1.5 & 16.3 & \textbf{1.4} & 2.3 & 243.3 & 20.3 & 2.8 & 17.0 & 9.3 & 32.9 \\ \textsc{Fpe} & 207.5 & 28.3 & 3867.2 & 27.1 & 263.7 & 25.4 & 528.2 & 30.3 & 6956.8 & 27.7 & 7342.5 & 24.9 & 116.7 & 38.5 \\ \textsc{Spe} & \textbf{1.3} & 3.1 & \textbf{1.6} & \textbf{0.6} & \textbf{1.5} & 0.8 & 1.8 & \textbf{2.1} & \textbf{1.3} & \textbf{0.4} & \textbf{2.4} & \textbf{1.3} & \textbf{9.1} & 2.0 \\ \bottomrule \end{tabular} } \caption{Numerical results on SDF reconstruction from unorganized point clouds. The Chamfer distance and MAE are multiplied by $10000$ and $100$. Our \textsc{Spe} has much lower Chamfer distance than \textsc{Fpe} and \textsc{Igr}, and better MAE than \textsc{Siren} and \textsc{Fpe}.} \label{tab:results} \end{table*} \paragraph{Network training.} By default, we use an MLP with 4 fully-connected (FC) layers with the Softplus activation function, each of which contains 256 hidden unit, and choose linear B-Spline bases for \textsc{Spe}. In each iteration during the training stage, we randomly sample 10k to 20k points from the input point cloud and the same number of random points from the 3D bounding box containing the shape. All input points are encoded via our \textsc{Spe}. We set the parameters of \textsc{Spe} to $K=256, C=64, M=3$, resulting a 64 dimension encoding for each point. As a reference, with \textsc{Fpe}, the dimension of per-point encoding is 256. The encoded point features are forwarded by the MLP. Then the loss in \cref{equ:loss} is calculated. The parameters $\lambda$ and $\tau$ in \cref{equ:loss} are set to $0.1$ and $1$. The MLP and \textsc{Spe} are optimized via the Adam~\cite{Kingma2014a} solver with a learning rate of $0.0001$, without using the weight decay and normalization techniques. For the multiscale optimization, we first initialize \textsc{Spe} with $K=2$, then progressively increase $K$ to 8, 32, 128, and 256, with the initialization method provided in \cref{equ:refine}. When optimizing MLPs with $K=2$, we occasionally observe the extracted surface containing spurious patches away from the input point cloud. Inspired by the geometric initialization proposed by~\cite{Atzmon2020} which initializes the network to approximate a sphere, we train a randomly initialized MLP to fit the SDF of a sphere. After training, the network weights are stored and used as the initialization of MLPs with $K=2$ in \textsc{Spe}. For learning shape spaces, we train an Auto-Decoder proposed by~\cite{Park2019}. Instead of relying on a global shape code to identity each shape~\cite{Park2019,Gropp2020}, our \textsc{Spe} itself is optimizable for each shape, which can be directly used to distinguish different shapes. Therefore, we train a shared MLP and specific \textsc{Spe} for each shape in the training set. The MLP is also composed of 4 FCs with 256 hidden units. After training, the network weights are fixed, and only the \textsc{Spe} is optimized to fit new shapes in the testing set. \section{Related Work} \label{sec:related} \paragraph{Coordinate-based MLPs.} The coordinate-based MLPs have caught great research interest as a continuous representation of shapes~\cite{Park2019,Mescheder2019,Chen2019}, scenes~\cite{Sitzmann2019}, images~\cite{Tancik2020,Sitzmann2020}, textures~\cite{Oechsle2019} and 5D radiance fields~\cite{Mildenhall2020}. These methods train MLPs by regressing the ground truth SDFs, point/pixel colors, or volume radiance values. Our work is motivated by the works~\cite{Atzmon2020a,Atzmon2020,Gropp2020} that use MLPs to reconstruct SDFs from raw point clouds, without knowing the ground truth SDFs. The limitation of coordinate-based MLPs with ReLU activation has been revealed by~\cite{Rahaman2019,Mildenhall2020}: the high-frequency fitting error decreases exponentially slower than the low-frequency error. To overcome this issue, there are multiple attempts to improve the representation power of MLPs as follows. \paragraph{Activation function.} \textsc{Siren}~\cite{Sitzmann2020} use Sine as the activation function and proposes a proper initialization method for training. It greatly improves the expressiveness of MLPs, and it is capable of recovering fine geometry details in the 3D reconstruction task. However, ReLU can provide strong implicit regularization when being under-constrained~\cite{Gropp2020} and offer a good approximation to SDF in the whole space. In our work, we choose Softplus as our activation function, which can be regarded as a differentiable ReLU. \paragraph{Positional encoding.} Sinusoidal encoding is a kind of positional encoding that is first used for representing 1D positions in natural language processing~\cite{Vaswani2017}. This type of positional encoding has proved to be able to improve the performance of MLPs in radiance fields fitting~\cite{Mildenhall2020} and 3D protein structure reconstruction~\cite{Zhong2020}. Tancik \etal~\shortcite{Tancik2020} build a theoretical connection between Sinusoidal mapping and Neural Tangent Kernels~\cite{Jacot2018} for proving the efficacy of sinusoidal mapping and further improve its performance by using random Fourier features~\cite{Rahimi2018}. Their Fourier Positional Encoding (\textsc{Fpe}) maps input points to a higher dimensional space with a set of sinusoids. However, \textsc{Fpe} is not suitable to minimize the loss function containing function gradient constraints as we reveal in \cref{sec:result}. \paragraph{Local MLPs.} Local MLPs improve the performance of a global MLP by dividing complex shapes or large-scale scenes into regular subregions~\cite{Peng2020,Chabra2020,Jiang2020,Genova2020} and fitting each subregion individually with the consideration of fusing the local output features or local output results. Our Spline Positional Encoding is composed of uniformly spaced locally supported basis functions along with different project directions. It shares the same sprite to local MLPs, but executes the local representation at the beginning of MLP. \section{Experiments and Evaluation} \label{sec:result} We have conducted the comparisons with several state-of-the-art methods to verify the effectiveness of our method. Specifically, we regard the MLP that directly takes the coordinates as input as the baseline, \ie, \textsc{Igr}~\cite{Gropp2020}. For the positional encoding, we compare our \textsc{Spe} with \textsc{Fpe} proposed by~\cite{Tancik2020}, which is an enhanced and improved version of the positional encoding in~\cite{Mildenhall2020,Zhong2020}, and \textsc{Siren}~\cite{Sitzmann2020}. By default, these networks are all composed of 4 FC layers with 256 hidden units. Our implementation is based on PyTorch, and all experiments were done with a desktop PC with an Intel Core i7 CPU (3.6 GHz) and GeForce 2080 Ti GPU (11 GB memory). Our code and trained models are available at \url{https://wang-ps.github.io/spe}. \begin{figure}[t] \centering \begin{overpic}[width=1\linewidth]{sdfs} \put(7, 0){\small \textsc{Gt}} \put(22, 0){\small (a) \textsc{Igr}} \put(38, 0){\small (b) \textsc{Siren}} \put(58, 0){\small (c) \textsc{Fpe}} \put(75, 0){\small (d) \textsc{Spe}} \end{overpic} \caption{Visual comparisons on SDF reconstruction from raw point clouds. The reconstructed shapes and SDF slices are illustrated.} \label{fig:recons} \end{figure} \subsection{Single Shape Learning} \label{sec:shape} In this section, we test our method on the task of reconstructing SDFs from raw point clouds. We evaluate both the quality of the reconstructed surface and SDFs. \paragraph{Dataset.} We collect 7 3D shapes as the benchmark, which include detailed geometric textures (Bunny, Armadillo, and Gargoyle), smooth surfaces (Bimba and Dragon), and sharp features (Fandisk). The Dfaust point cloud is produced by a real scanner provided by~\cite{Bogo2017}. For other models, we sample points with normals from the surface via uniformly placing virtual depth cameras around each shape. \paragraph{Evaluation metric.} We use the Chamfer distance to measure the quality of the extracted surface. Specifically, we randomly sample a set of $N$ points $\mathcal{X} = \{x_i\}_{i=1}^N$ from the extracted surface and ground-truth surface $\hat{\mathcal{X}} = \{\hat{x}_i\}_{i=1}^N$, where $N=25k$. And we use the following formula to calculate the Chamfer distance: \begin{equation} D(\mathcal{X},\hat{\mathcal{X}}) = \frac{1}{N} \sum_i \min_j \|x_i - \hat{x}_j\| + \frac{1}{N} \sum_j \min_i \|\hat{x}_i - x_j\| \label{equ:chamfer} \end{equation} We use the mean absolute error (MAE) between the predicted and ground-truth SDFs to measure the quality of the predicted SDFs. To calculate the MAE, we uniformly draw $256^3$ samples on both the predicted and ground-truth SDFs. \paragraph{Results.} The numerical results are summarized in \cref{tab:results}, and the visual results are shown in \cref{fig:recons}. As we can see, compared with \textsc{Igr}, the Chamfer distance of our method is greatly reduced, and the high-frequency geometric details are reconstructed much better, which verifies that with our \textsc{Spe} MLPs can easily reproduce the high-frequency details. For \textsc{Siren} and \textsc{Fpe}, their extracted surfaces may contain spurious components, as shown in \cref{fig:recons}. Note that it is non-trivial to fix this issue for their results: although the isolated small meshes can be easily removed, the incorrect components attached to the real surface are hard to remove and repair. Moreover, the implicit fields of \textsc{Fpe} and \textsc{Siren} have large deviations from the ground-truth SDFs, as revealed by significantly larger MAE. In \cref{fig:sdf}, we show an application using SDFs trained with our \textsc{Spe} to extract the different level sets for shape shrinking and dilation. \begin{figure} \centering \begin{overpic}[width=1\linewidth]{isovalues} \put(7, 0){\small -0.1} \put(28, 0){\small -0.05} \put(50, 0){\small 0} \put(68, 0){\small 0.05} \put(90, 0){\small 0.1} \end{overpic} \caption{Different level sets of trained SDFs by \textsc{Spe}. } \label{fig:sdf} \end{figure} \subsection{Ablation Study} \paragraph{Expressiveness of \textsc{Spe}.} We did an ablation study on how the choices of hyper-parameters (the segmentation number $K$, the channel of weights $C$, the projection number $M$, and the order of B-Spline basis), affect the performance of \textsc{Spe}. The experiments were done on the reconstruction of the Bimba model and we increased one hyper-parameter while keeping others unchanged. The baseline is $K=128,C=64,M=3$ with linear B-Spline bases. The results summarized in \cref{tab:expressiveness} show that larger hyper-parameters can result in better apprimation quality, while the segmentation number brings the most effective improvements. \begin{table}[t] \tablestyle{2pt}{1.1} \scalebox{0.85}{ \begin{tabular}{lccccc} \toprule (K, C, M) & (128, 64, 3) & (\textbf{256}, 64, 3) & (128, \textbf{128}, 3) & (128, 64, \textbf{6}) & (128, 64, 3)$^\star$\\ \midrule Chamfer & 1.72 & 1.63 & 1.67 & 1.69 & 1.71 \\ \bottomrule \end{tabular} } \caption{ Chamfer distances on the Bimba model with different parameter settings. (128, 64, 3)$^\star$ uses quadratic B-Spline bases. } \label{tab:expressiveness} \end{table} \begin{figure}[b] \centering \begin{overpic}[width=\linewidth]{mlp} \put(7, 0){\small \textsc{Gt}} \put(26, 0){\small \textsc{Igr}} \put(24, 21) {\small 5.1} \put(43, 0){\small \textsc{Igr}-deep} \put(44, 21) {\small 2.3} \put(63, 0){\small \textsc{Igr}-long} \put(64, 21) {\small 1.8} \put(87, 0){\small \textsc{Spe}} \put(84, 21) {\small 1.6} \end{overpic} \caption{ Test on vanilla MLP with different settings. From left to right: the ground-truth, the result of \textsc{Igr} as the baseline, \textsc{Igr}-deep: \textsc{Igr} with 4 times increased network depth, \textsc{Igr}-long: \textsc{Igr} with 10 times longer training time, and our \textsc{Spe} result. The numbers in the figure are the Chamfer distance. } \label{fig:mlp-igr} \end{figure} \paragraph{Can a vanilla MLP compete with \textsc{Spe}?} To check whether a vanilla MLP can fit the high-frequency details, we train vanilla MLP -\textsc{Igr} by increasing its network depth and training time on the task of reconstructing the Bimba model. The results are shown in \cref{fig:mlp-igr}. As we can see, even by increasing the network depth by 4 times or increasing the training time by 10 times, the results of vanilla MLPs are still worse than \textsc{Spe}. Without any kind of positional encoding, the vanilla MLP converges too slow to recover the fine details. \paragraph{Specialization of our \textsc{Spe}.} With proper initialization, our \textsc{Spe} can reproduce the MLP with \textsc{Fpe}, since B-Spline functions can fit sinusoidal functions well with sufficiently small $\delta$. In practice, we find that as long as the $\delta$ of B-Spline functions is similar to the period of a sinusoidal function, we can achieve similar effects. \begin{table}[t] \centering \scalebox{0.9}{ \begin{tabular}{c|ccccc} \toprule Method & \textsc{Igr} & \textsc{Siren} & \textsc{Fpe} & \textsc{Spe} \\ \midrule Chamfer &14.1 & 15.3 & 18.1 & \textbf{11.5} \\ MAE &3.6 & 34.7 & 30.4 & \textbf{3.4} \\ \bottomrule \end{tabular} } \caption{Comparisons of shape space learning on the D-Faust dataset.} \label{tab:space} \end{table} \begin{figure}[t] \centering \begin{overpic}[width=1\linewidth]{shapespace} \put(6, 0){\small \textsc{Gt}} \put(18, 0){\small (a) \textsc{Igr}} \put(31, 0){\small (b) \textsc{Siren}} \put(48, 0){\small (c) \textsc{Fpe}} \put(63, 0){\small (d) \textsc{Spe}} \end{overpic} \caption{Visual comparisons on shape space learning. 3 human body shapes from the testing set reconstructed by different methods and the corresponding SDF slices are shown.} \label{fig:space} \end{figure} \subsection{Shape Space Learning} \textsc{Spe} is also suitable to learn shape spaces from raw scans using auto-decoders~\cite{Park2019}. We compared our method with \textsc{Igr}, \textsc{Siren}, and \textsc{Fpe}, for which each shape has a specific shape code with dimension 256 and all the shapes share the same decoder. Our \textsc{Spe} optimizes the specific spline positional encoding for each shape and does not use a shape code. The parameters are set to $K=64, C=32, M=3$. We use the Chamfer distance and MAE defined in \cref{subsec:learnsdf} as the evaluation metrics to compare the quality of the reconstructed surface and SDFs on the unseen testing shapes. \paragraph{Dataset.} We conducted the experiment on the D-Faust dataset~\cite{Bogo2017} by following the setup of \cite{Gropp2020}. D-Faust contains real scans of human bodies in different poses, in which 6258 shapes are used for training and 181 shapes are used for testing. For each raw scans, we sample 250k points with normals as the input. \paragraph{Results.} After training, all the methods are tested on the test shapes by fixing the network weights and optimizing the shape code or our spline weights. \cref{tab:space} lists the Chamfer distance and the MAE of SDFs of the results generated by four methods. It is clear that our method outperforms the other three methods, and the second-best method is \textsc{Igr}. Although \textsc{Siren} and \textsc{Fpe} have a better fitting ability in single shape reconstruction, they are even worse than \textsc{Igr} in the shape space learning within the auto-decoder framework. The visual comparisons in \cref{fig:space} further confirm the better performance of our method. \subsection{Generalizability of \textsc{Spe}} In this section, we show the generalizability of our method via the tasks of fitting images and SDFs. \paragraph{Image fitting.} In this experiment, we trained an MLP to map 2D coordinates to the corresponding pixel values. We use the image dataset provided by~\cite{Tancik2020}, which contains 16 natural images and 16 text images. The MLP is trained with an $L_2$ loss. We use PSNR as the evaluation metric. The results are summarized in \cref{tab:img}. With similar size of parameters, our \textsc{Spe} achieves comparable results to \textsc{Siren} and \textsc{Fpe}, and is much better than a vanilla \textsc{Mlp}. With more projection directions ($M=32$), the performance of our \textsc{Spe} can be significantly improved. \cref{fig:image} illustrates the reconstruction results and zoom-in views by different methods. We notice that the resulting images of \textsc{Fpe} have visible noise patterns, as shown by the zoom-in figure, and the result of Siren is more blur than ours. \begin{table}[t] \centering \scalebox{0.9}{ \begin{tabular}{c|ccccc} \toprule Method & \textsc{Mlp} & \textsc{Siren} & \textsc{Fpe} & \textsc{Spe} & \textsc{Spe}$^\star$ \\ \midrule Natural Images & 18.3 & 31.1 & 30.8 & 30.1 & \textbf{33.6} \\ Text Images & 18.4 & 35.6 & 33.7 & 37.4 & \textbf{40.4} \\ \bottomrule \end{tabular} } \caption{PSNRs of the image reconstruction task. \textsc{Spe}$^\star$ is \textsc{Spe} with $M=32$. } \label{tab:img} \end{table} \begin{figure}[t] \centering \begin{overpic}[width=1\linewidth]{img} \put(7, -4){\small \textsc{Gt}} \put(23, -4){\small (a) \textsc{Mlp}} \put(42, -4){\small (b) \textsc{Siren}} \put(64, -4){\small (c) \textsc{Fpe}} \put(84, -4){\small (d) \textsc{Spe}$^\star$} \end{overpic} \vspace{0.01mm} \caption{Results of image reconstruction. The bottom row shows zoom-in views.} \label{fig:image} \end{figure} \begin{table}[t] \centering \scalebox{0.9}{ \begin{tabular}{ccccccc} \toprule Model & Arm. & Bimba & Bunny & Dragon & Fandisk & Garg. \\ \midrule \textsc{Mlp} & 9.69 & 4.69 & 3.76 & 11.59 & 2.06 & 9.94 \\ \textsc{Siren} & 1.19 & 1.41 & 1.48 & 1.23 & 1.44 & \textbf{1.66} \\ \textsc{Fpe} & 1.24 & 1.44 & 1.49 & 1.29 & 1.47 & 1.71 \\ \textsc{Spe} & \textbf{1.18} & \textbf{1.39} & \textbf{1.46} & \textbf{1.19} & \textbf{1.36} & 1.69 \\ \bottomrule \end{tabular} } \caption{Comparisons on the SDF regression task. The numbers are Chamfer distances.} \label{tab:regression} \end{table} \begin{figure}[t] \centering \begin{overpic}[width=1\linewidth]{regress} \put(7, 1){\small \textsc{Gt}} \put(23, 1){\small (a) \textsc{Mlp}} \put(42, 1){\small (b) \textsc{Siren}} \put(64, 1){\small (c) \textsc{Fpe}} \put(84, 1){\small (d) \textsc{Spe}} \end{overpic} \caption{Comparisons on shape regression. The results are shown in the first row, and the zoom-in figures are shown in the second row.} \label{fig:sdfregress} \end{figure} \paragraph{SDF fitting.} Instead of learning SDFs from raw points, we sample the ground-truth SDFs in the resolution of $256^3$. The MLP takes 3D coordinates as input and output 1D distance values and directly fits the ground-truth SDFs with an $L_1$ loss~\cite{Park2019}. We set the projection direction of our \textsc{Spe} as $16$ to get smoother results. We use the same dataset in \cref{sec:shape} and summarize the fitting results in \cref{tab:regression}. The zero isosurface results of the Fandisk example by different methods are illustrated in \cref{fig:sdfregress}. It can be seen that the results of \textsc{Spe} and \textsc{Siren} are more faithful to the ground truth than other methods, while the result of \textsc{Igr} is over-smoothed and the result of \textsc{Fpe} has visible noise patterns.
{'timestamp': '2021-10-29T02:13:42', 'yymm': '2106', 'arxiv_id': '2106.01553', 'language': 'en', 'url': 'https://arxiv.org/abs/2106.01553'}
arxiv
\section{Introduction}\label{introd} Text-based visual retrieval is a fundamental problem in multimedia information retrieval~\cite{hong2015learning,nie2012harvesting,yang2020tree,dong2018predicting,dong2021dual} which has achieved significant progress. Recently, Video Moment Retrieval (VMR) has emerged as a new task \cite{liu2018attentive,gao2017tall,hendricks2018localizing,anne2017localizing} and received increasing attention \cite{liu2018cross,chen2018temporally}. It aims to retrieve a specific moment in a video, according to a textual query. As shown in Figure \ref{fig1} (a), given a query "\textit{Person opens a door}", its goal is to predict the temporal location of the target moment.\footnote{Through this paper, unless otherwise stated, we use the term "\textbf{location}" to depict the "\textbf{temporal location}" of a video moment, rather than "\textit{physical location}."} This task is quite challenging, since it requires effective modeling of multimodal content and cross-modal relationship. The past few years have witnessed the notable development of VMR, largely driven by public benchmark datasets, \textit{e.g.}, {Charades-STA}~\cite{gao2017tall}. Most existing efforts first generate sufficient and diverse moment candidates, and then rank them based on their matching scores with the query. Benefiting from effective modeling of temporal contexts and cross-modal interactions, state-of-the-art (SOTA) models \cite{zhang2019learning,NIPS2019_8344,mun2020LGI} have reported significant performance on public datasets. However, does the reported results of SOTA models truly reflect the progress of VMR? The answer seems to be "\textit{No}". Recent studies \cite{otani2020uncovering} found empirical evidences that VMR models mostly exploit the temporal location biases in datasets, rather than learning the cross-modal matching. The true effect from the video content may be largely overlooked in the prediction. Such biased models have poor generalizability and are not effective for real-world application. We argue that the critical issue is rooted from two types of temporal location biases in dataset annotations: \begin{itemize} \item \textit{Long-tailed annotations}. As depicted in Figure \ref{fig1} (c), most annotations in Charades-STA start at the beginning of videos and last roughly 25\% of the video length. This leads to a strong bias toward the frequently annotated locations. If a model is trained to predict the target at the \textit{head} locations (yellow regions in Figure \ref{fig1} (c)) more frequently than at the \textit{tail} locations (green regions), the former is more likely to prevail over the latter during testing. \item \textit{High correlation between user queries and moment locations}. In Figure \ref{fig1} (d) and (e), the queries including a verb "open" mostly match target moments at the beginning of videos. While those corresponding to "leave" are often located at the end. That makes user queries and moment locations spuriously correlated. \end{itemize} Although the temporal location bias misleads the model prediction severely, it also has some good, \textit{e.g.,} the temporal location of a moment helps to better model the temporal context for answering the query with temporal languages~\cite{hendricks2018localizing}. Therefore, {the key of VMR is how to properly keep the good and remove the bad effect of moment location for a robust cross-modal matching. As far as we know, no similar effort is devoted to address this critical issue.} \begin{figure}[t] \centering \includegraphics[width=3.1in]{fig1_full.pdf} \vspace{-0.12in} \caption{(a) An example of VMR; (b) Causal graph: $Q$ (query), $V$ (video moment), $L$ (moment location), and $Y$ (prediction); The bottom three plots depict the temporal location distributions of moment annotations in Charades-STA based on the 2D structure of moments~\cite{zhang2019learning}: (c) Distribution of all moments; (d) and (e) describe the distributions of query-specific moments (\textit{i.e.}, including verbs like "\textit{open}" or "\textit{leave}").} \vspace{-0.24in} \label{fig1} \end{figure} In this paper, we present a causal VMR framework that builds structural causal model~\cite{pearl2016causal} to capture the causality between different components in VMR. The causal graph is depicted in Figure \ref{fig1} (b) which consists of four variables: $Q$ (query), $V$ (video moment), $Y$ (prediction), and $L$ (moment location). The prediction of traditional models is inferred by using the probability $P(Y|Q,V)$. In the causal graph, $L$ is a hidden confounder~\cite{pearl2018book} that spuriously associates ${V}$ and $Y$, which has been long ignored by traditional VMR models. The effect of $L$ on $Y$ mainly comes from the biases in datasets, while the effect of $L$ on $V$ is mainly due to the entanglement of latent location factor in the representation of $V$. Here, the confounder $L$ opens a backdoor path: ${V}$$\leftarrow$$L$$\rightarrow$$Y$ that hinders us from finding the true effect on $Y$ only caused by $(Q, V)$. To remove the harmful confounding effects \cite{pearl2018book} caused by moment location, we design a \textbf{Deconfounded Cross-modal Matching} (DCM) method. It first disentangles the moment representation to infer the core feature of visual content, and then applies causal intervention on the multimodal input based on backdoor adjustment \cite{pearl2016causal}. Specifically, we replace $P(Y|Q,V)$ with $P(Y|do(Q, V))$ by \textit{do} calculus which encourages the model to make an unbiased prediction. The query is forced to fairly interact with all possible locations of the target based on the intervention. We expect the deconfounding model to be able to robustly localize the target even when the distribution of moment annotations is significantly changed. This triggers another key question: {how to evaluate the generalizability of VMR models?} In general, the split of training and testing sets follows the independent and identically distributed (IID) assumption \cite{vapnik1999overview}. Due to the existence of temporal location biases in the datasets, the IID testing sets are insufficient to test the causality between ${(Q, V)}$ and $Y$. To address this issue, we introduce the \textbf{Out-Of-Distribution} (OOD) testing \cite{teney2020value} into evaluation. Our basic idea is to modify the location distribution of moment annotations in the testing sets by inserting a short video at the beginning/end of testing videos. It is only applied on testing sets, which does not introduce any new biases that affect the model training. Extensive experiments on both IID and OOD testing sets of {ActivityNet-Captions}~\cite{krishna2017dense}, {Charades-STA} \cite{gao2017tall}, and {DiDeMo}~\cite{anne2017localizing}, clearly demonstrate that DCM not only achieves higher retrieval performance but also endows the model with strong generalizability against distribution changes. In summary, this work makes the following main contributions: \begin{itemize} \item We build a causal model to capture the causalities in VMR and point out that the moment temporal location is a hidden confounding variable that hinders the pursuit of true causal effect. \item We propose a new method, DCM, for improving VMR, that applies causal intervention on the multimodal model input to remove the confounding effects of moment location. \item We conduct extensive experiments on the IID and OOD testing sets of three benchmark datasets, which show the ability of DCM to perform accurate and robust moment retrieval. \end{itemize} \section{Causal View of VMR} In this section, we first formally formulate the task of VMR and then introduce a causal graph to clearly reveal how the confounder $L$ spuriously correlate the multimodal input and prediction. \vspace{-0.5em} \subsection{Problem Formulation}\label{formulation} Given a query and a video with temporal length $\tau$, our task is to identify a target moment $\hat{v}$ in the given video, starting at timestamp $\tau_s$ and ending at timestamp $\tau_e$ ($\tau_s< \tau_e<\tau$), which semantically matches the query ${q}$. The given video is first processed into a set of video moment candidates $\{v_i\}_{i=1}^N$, with diverse temporal durations, either by multi-scale sliding window~\cite{gao2017tall,liu2018attentive,liu2018cross} or hierarchical pooling~\cite{zhang2019learning}, where $N$ is the number of moment candidates. Each moment $v$ is indexed by a temporal location $\ell$, \textit{i.e.}, a pair of timestamps $(t_s, t_e)$. We compute the relevance score ${y}$ (\textit{e.g.}, IoU score) between each moment candidate $v$ and target $\hat{v}$ as the supervision for training, where $y$ can be either binary $\{0,1\}$ or dense $\left(0,1\right)$. The candidates with $y\geq 0.5$ are usually treated as positive. As such, the task of video moment retrieval can be formally defined as: \begin{itemize} \item \textbf{Input}: A corpus of query-moment pairs and their relevance scores: $\{\mathcal{Q}, \mathcal{V}, \mathcal{Y}\}$, where $\mathcal{Q}, \mathcal{V}$, and $\mathcal{Y}$ denote the sets of queries, moments, and relevance scores, respectively. \item \textbf{Output}: A cross-modal matching function $f$: $\mathcal{Q}\times\mathcal{V}\rightarrow\mathbb{R}$ that maps each query-moment pair to a real value by effectively modeling intra-modality and inter-modality feature interactions. During inference, we rank the moment candidates based on the estimated matching scores, and return the best candidate to user. \end{itemize} The solution usually involves: 1) learning the representation of query $\mathbf{q}\in\mathbb{R}^d$ and moment $\mathbf{v}\in\mathbb{R}^d$, and 2) modeling the cross-modal relationship. We mainly focus on the second point. In particular, we will investigate how the temporal locations of video moments spuriously affect the prediction $f(\mathbf{q}, \mathbf{v})$, and then aim to remove the {spurious correlation} caused by the moment location. \vspace{-0.5em} \subsection{Causal Graph}\label{CausalGraph} We describe the causalities among four variables in VMR: query $Q$, video moment $V$, moment location $L$, and model prediction $Y$ with a simple causal graph in Figure \ref{fig1} (b). The direct link denotes the causality between two nodes: cause$\rightarrow$effect. The causal graph is a directed acyclic graph that indicates how the variables $\{Q, V, L, Y\}$ interact with each other through the causal links. Traditional VMR models, \textit{e.g.}, \cite{gao2017tall,zhang2019learning}, have only two links: $Q$$\rightarrow$$Y$ and $V$$\rightarrow$$Y$, and predict the target by joint probability $P(Y|Q,V)$. In our causal graph, the moment location $L$ is a confounder~\cite{pearl2016causal,pearl2018book} that influences both the correlated variable $Y$ and independent variable $V$, leading to spurious correlation between $V$ and $Y$: \begin{itemize} \item $L$$\rightarrow$$Y$ is rooted from the frequency prior $P(Y|L)$. Dataset annotators prefer to select short moments at specific locations of videos as the target~\cite{anne2017localizing}, \textit{e.g.}, the beginning or end of videos, as depicted in Figure \ref{fig1} (c), which leads to a \textit{long-tailed} location distribution of moment annotations. It introduces a harmful causal effect that misleads the prediction of targets at the \textit{tail} (green regions) location biased towards the data-rich \textit{head} (yellow regions) locations. The location $L$ leads to not only the direct effect $L$$\rightarrow$$Y$ but also the joint effect $(Q, L)$$\rightarrow$$Y$, which will be investigated in section \ref{exp}. \item $L$$\rightarrow$$V$ denotes the effect of $L$ on moment representation. In VMR, the temporal location of moments leads to a temporal context prior that affects the representation learning of moments in videos. {The extracted moment representation from a backbone network is usually {entangled} with a latent location factor.} Although it enriches the representation with location-aware features, it introduces the harmful spurious correlation between $(Q, V)$ and $Y$ via the backdoor path: $V$$\leftarrow$$L$$\rightarrow$$Y$. Similar feature entanglements are common in video domain~\cite{denton2017unsupervised}. \end{itemize} So far, we have clearly revealed how the moment location $L$ confound $V$ and $Y$ via the backdoor path that makes the effect of visual content largely overlooked, as reported by \cite{otani2020uncovering}. Next, we propose a deconfounding method to remove the confounding effects. \vspace{-0.4em} \section{METHODOLOGY}\label{methodology} Given the representation of query $\mathbf{q}$ and a moment candidate $\mathbf{v}$, our goal is to predict the matching score $s$ between the candidate and the query by a deconfounding method, DCM. As depicted in Figure \ref{fig2}, it is composed of two key steps to achieve the deconfounding: 1) feature disentangling on ${V}$ that infers the core feature to represent the visual content of moment candidate, reducing the effect of $L$ on $\mathbf{v}$; 2) causal intervention on the multimodal input to remove the harmful confounding effects of $L$ from $Y$. \vspace{-0.4em} \subsection{Moment Representation Disentangling}\label{disentangled} As discussed before, the moment representation is usually entangled with a location factor. To achieve the deconfounding, the first step is to ensure that the representations of $V$ and $L$ are independent with each other. In this section, we propose to disentangle $\mathbf{v}$ into two independent latent vectors: content $\mathbf{c}^v\in\mathbb{R}^d$ and location $\bm{\ell}^v\in\mathbb{R}^d$: \begin{equation} \mathbf{c}^v = g_c(\mathbf{v}), \bm{\ell}^v = g_{\ell}(\mathbf{v}), \end{equation} where $g_c(\cdot)$ and $g_\ell(\cdot)$ can be implemented by two fully connected layers. To achieve the disentangling, we introduce two learning constraints to optimize the parameters of $g_c(\cdot)$ and $g_\ell(\cdot)$. \begin{itemize} \item \textbf{Reconstruction}. Since we can access the original location $(t_s, t_e)$ of each moment $v$ during training, we use it to supervise $g_\ell(\cdot)$ by a reconstruction loss $\mathcal{L}_{recon}(\bm{\ell}^v, \mathbf{p})$, where $\mathbf{p}\in\mathbb{R}^d$ is a non-learnable positional embedding vector~\cite{vaswani2017attention} of $(t_s, t_e)$. $\mathcal{L}_{recon}(\cdot,\cdot)$ can be any reconstruction losses that force $\bm{\ell}^v$ to approximate the real location feature. Different from existing efforts \cite{anne2017localizing,mun2020LGI,zeng2020dense} that exploit $(t_s, t_e)$ as the side information to augment the moment representation, we focus on disentangling $\mathbf{v}$ to capture the core effect of visual content and remove the confounding effects of moment location. Injecting extra location feature into $\mathbf{v}$ will obviously exacerbate the correlation between $L$ and $V$. \item \textbf{Independence Modeling}. Different from $\bm{\ell}^v$, there is no supervision on the content $\mathbf{c}^v$. Besides, $\mathbf{c}^v$ and $\bm{\ell}^v$ are both estimated from $\mathbf{v}$, they do not immediately satisfy the \textit{independence} requirement. We introduce an independence learning regularizer $\mathcal{L}_{indep}(\bm{\ell}^v, \mathbf{c}^v)$ that forces $\bm{\ell}^v$ to be independent with $\mathbf{c}^v$ in the latent space. $\mathcal{L}_{indep}(\cdot,\cdot)$ can be any statistical dependence measures, \textit{e.g.}, distance correlation and mutual information. \end{itemize} We will describe the details of $\mathcal{L}_{indep}$ and $\mathcal{L}_{recon}$ in section \ref{losses}. The representation disentangling on $V$ reduces the correlation between $V$ and $L$, which cuts off the link $L$$\rightarrow$$V$ in the feature level. The next question is how to remove the harmful confounding effects of $L$ from $Y$ for making a robust prediction on each candidate. \begin{figure}[tb] \centering \includegraphics[width=3.2in]{Pipeline.pdf} \vspace{-0.15in} \caption{A brief overview of our deconfounded cross-modal matching for the task of VMR.} \vspace{-0.2in} \label{fig2} \end{figure} \vspace{-0.5em} \subsection{Causal Intervention}\label{intervention} As described before, $L$ is a confounder that leads to spurious correlation between $V$ and $Y$. For example, in an unbalanced VMR dataset, the high-frequency location $\ell_h$, has higher chance to be selected as the target location than the low-frequency location $\ell_l$: $P(Y|\ell_h)$$>$$P(Y|\ell_l)$. That will mislead the model towards predicting a higher score on the candidate $v_{\ell_h}$ at $\ell_h$ than the candidate $v_{\ell_l}$ at $\ell_l$, without truly looking into the details of multimodal input. Even if the query is considered, if not removing the confounding effects of moment location, the model will still be easily misled by the query-specific location prior (Figure \ref{fig1} (d) and (e)). In this section, {{as shown in Figure \ref{fig3}}}, we propose to use $do$-calculus~\cite{pearl2018book} to intervene the model input based on back-door adjustment. By applying the Bayes rule on the new casual graph, we have \begin{equation}\label{do-operation} P\left(Y|do\left(Q, V\right)\right) = P\left(Y|Q, do\left(V\right)\right) = \sum_{{\ell}\in L} P\left(Y|Q, V, \ell\right) P({\ell}), \end{equation} where $P({\ell})$ is the prior of location. We see from Eq. (\ref{do-operation}) that the aim of the \textit{intervention} is to force the query to fairly interact with all the possible locations of the target moment for making an unbiased prediction, subject to the prior $P({\ell})$. In this way, the model is prevented from memorizing the corresponding locations of target moments during training. Note that we force the prior $P({\ell})$ to be a constant $\frac{1}{N}$, following the assumption that each location has equal opportunity to be the target location. For the location confounder set $L$, since we can hardly enumerate all the moment locations in the real world, we approximate $L$ as the location set of all sampled moment candidates, \textit{i.e.}, $L=\{{\ell}_k\}_{i=1}^N$, where ${{\ell}_k}$ is represented by ${\bm{\ell}_k}\in\mathbb{R}^d$, \textit{i.e.}, the disentangled location feature from $\mathbf{v}_k$. \begin{figure}[tb] \centering \includegraphics[width=2.2in]{do-intervention.pdf} \vspace{-0.15in} \caption{A brief illustration of our causal intervention.} \vspace{-0.2in} \label{fig3} \end{figure} Given the representations of the query and a moment candidate, Eq. (\ref{do-operation}) is implemented as $\sum_{\bm{\ell}}p(y|\mathbf{q}, \mathbf{v}, \bm{\ell})P(\bm{\ell})$,~\footnote{To keep section \ref{intervention} self-contained, we still use $\mathbf{v}$ to denote the moment representation for simplicity. It can either be the original or disentangled representation of $V$.} where $p(y|\mathbf{q}, \mathbf{v}, \bm{\ell})$ is the output of a cross-modal matching network $f(\cdot)$ \begin{equation}\label{cross-modal-matching} p(y|\mathbf{q}, \mathbf{v}, \bm{\ell})=\sigma(f(\mathbf{q}, \mathbf{v}, \bm{\ell})), \end{equation} where $\sigma(\cdot)$ is the sigmoid function $\sigma(x)=\frac{1}{1+\textrm{exp}(-x)}$ that transforms the output of $f(\cdot)$ into $(0, 1)$. In summary, the implementation of Eq. (\ref{do-operation}) is formally defined as \begin{equation}\label{expectationE_l} P\left(Y|do\left(Q, V\right)\right) :=\mathbb{E}_{\bm{\ell}}\left[\sigma(f(\mathbf{q}, \mathbf{v}, \bm{\ell}))\right]. \end{equation} To calculate Eq. (\ref{expectationE_l}), we found that $\mathbb{E}_{\bm{\ell}}$ needs expensive sampling. Fortunately, following recent efforts~\cite{yue2020interventional,zhang2020causal}, we can first adopt the Normalized Weighted Geometric Mean (NWGM)~\cite{xu2015show} to approximately move outer expectation $\mathbb{E}_{\bm{\ell}}$ into the sigmoid function: \begin{equation}\label{sigma(E_l)} P\left(Y|do\left(Q, V\right)\right) :=\mathbb{E}_{\bm{\ell}}\left[\sigma(f(\mathbf{q}, \mathbf{v}, \bm{\ell}))\right] \approx \sigma\big(\mathbb{E}_{\bm{\ell}}\left[f(\mathbf{q}, \mathbf{v}, \bm{\ell})\right]\big). \end{equation The further calculating of Eq. (\ref{sigma(E_l)}) depends on the implementation of the matching network $f(\cdot)$. \textit{If $f(\cdot)$ is a linear model, we can further move the expectation into $f(\cdot)$, \textit{i.e.}, $\mathbb{E}(f(x))=f(\mathbb{E}(x))$}. Then we just need one forward pass to obtain the prediction. Besides, to seek the true effect of visual content of $V$ on $Y$, the representation $\mathbf{v}$ is implemented as the disentangled moment representation. We will describe the detailed implementation of $f(\cdot)$ in section \ref{dcm_imp}. So far, we have finished the causal intervention via backdoor adjustment~\cite{pearl2016causal,pearl2018book}, thus closing the backdoor path $V \leftarrow L\rightarrow Y$. \noindent{\textbf{Summary}}: From Eq. (\ref{sigma(E_l)}), we can see that the effect on $Y$ comes from $Q, V$, and all the possible locations of the target moment, \textit{i.e.}, $\{{\ell}_k\}_{i=1}^N$, which prevents the model from exploiting the location priors $P(Y|L)$ and $P(Y|Q, L)$. The disentangling module described in section \ref{disentangled} supports the deconfounding in the \textit{feature} level while the intervention module contributes more in the \textit{prediction} level. Both of them are indispensable for achieving the deconfounding. \vspace{-0.6em} \subsection{Model Implementation}\label{Implementation} This section presents the model implementation. It mainly consists of the moment candidate sampling and encoding, query encoding, cross-modal matching networks $f(\cdot)$, and the learning objective. \vspace{-0.5em} \subsubsection{\textbf{Moment Sampling and Encoding}} For a given video, we first segment it into a sequence of $T$ non-overlapping video clips by fixed-interval sampling. The clip feature can be obtained by applying pretrained CNNs, such as C3D~\cite{tran2015learning} and I3D~\cite{carreira2017quo}, on video frames. Then we enumerate all moment candidates from the given video by composing any ordered lists of video clips. Each clip can be also treated as a short moment. The representation $\mathbf{v}\in \mathbb{R}^d$ of each candidate is obtained by applying a stacked pooling network over the set of video clips, following \cite{zhang2019learning}. All the feature vectors of sampled moment candidates can be encoded into a moment feature tensor $\mathbf{V}\in \mathbb{R}^{d\times T \times T}$. The last two dimensions of $\mathbf{V}$ index the start and end coordinates of all sampled candidates. \subsubsection{\textbf{Query Encoding}} For the encoding of the query sentence $q$, we first extract the word embeddings by the pretrained Glove word2vec model~\cite{jeffreypennington2014glove}. We then use a three-layer unidirectional LSTM to capture the sequential information in $q$. The query representation $\mathbf{q}\in \mathbb{R}^d$ is the last hidden state of the LSTM output. \subsubsection{\textbf{Deconfounded Cross-modal Matching (DCM)}} \label{dcm_imp} Our proposed DCM method can be implemented with most existing matching architectures in VMR (proposals-based). In this work, we implement it with two kinds of cross-modal matching networks $f(\cdot)$: \begin{itemize} \item {Context-aware Multi-modal Interaction} (CMI). It is modified from the fusion module in \cite{gao2017tall}. We implement $f(\cdot)$ with CMI as: \begin{equation}\label{CMI} f(\mathbf{q}, \!\mathbf{v}, \!\bm{\ell})\!=\!\mathbf{w}^T\Big(\mathbf{W}_1\Big(\big(\bar{\mathbf{q}} \!\odot \!\phi_{\mathbf{V}}\big(\bar{\mathbf{v}}\!+\!{h}_{qv}(\bm{\ell})\big)\!\big) \!\oplus\! \big(\bar{\mathbf{q}} \!+ \!\phi_{\mathbf{V}}\big(\bar{\mathbf{v}}\!+\!{h}_{qv}(\bm{\ell})\big)\big)\Big)\!\Big), \end{equation} where $\bar{\mathbf{v}}$ and $\bar{\mathbf{q}}$ denote the transformed moment and query representations, respectively: $\bar{\mathbf{v}}=\mathbf{c}^v + \mathbf{W}_2 \bm{\ell}^v$ and $\bar{\mathbf{q}}=\mathbf{W}_3 \mathbf{q}$. The $\mathbf{w}\in\mathbb{R}^{d}$, $\mathbf{W}_1\in\mathbb{R}^{d\times 2d}$, $\mathbf{W}_2\in\mathbb{R}^{d\times d}$, and $\mathbf{W}_3\!\in\!\mathbb{R}^{d\times d}$ denote the learnable parameters of four fully-connected layers, respectively. The $\odot$ denotes the element-wise multiplication and $\oplus$ denotes the channel-wise vector concatenation. ${h}_{qv}(\bm{\ell})$ is a feature transformation of $\bm{\ell}$, parameterized by the features of $q$ and $v$. $\phi_{\mathbf{V}}(\bar{\mathbf{v}}+{h}_{qv}(\bm{\ell}))$ denotes a convolutional operation on the intervened moment tensor $\mathbf{V}'\!\in\! \mathbb{R}^{d\times T \times T}$, where each element has been changed from $\mathbf{v}$ to $\bar{\mathbf{v}}+{h}_{qv}(\bm{\ell})$, to aggregate the pre-context and post-context moment features~\cite{gao2017tall} into current moment $v$, with the weight parameter $\mathbf{W}_4 \in\mathbb{R}^{d\times d\times K \times K}$ ($K$ denotes the kernel size). We remove the non-linear activation function behind the convolution operation. Then, we {replace ${h}_{qv}(\bm{\ell})$ in Eq. (\ref{CMI}) with $\mathbb{E}_{\bm{\ell}}\big[{h}_{qv}\big(\bm{\ell}\big)\big]$} to approximately compute $\mathbb{E}_{\bm{\ell}}\big[f(\mathbf{q}, \mathbf{v}, \bm{\ell})\big]$. \item {Temporal Convolutional Network} (TCN)~\cite{zhang2019learning}. It is a SOTA matching network in VMR. We implement TCN-based $f(\cdot)$ as: \begin{equation}\label{TCN} f(\mathbf{q}, \mathbf{v}, \bm{\ell})=\mathbf{w}^T\Big(\phi^*_{\mathbf{V}}\Big(\bar{\mathbf{q}} \odot \big(\bar{\mathbf{v}}+{h}_{qv}(\bm{\ell})\big)\Big) \Big), \end{equation} where $\phi^*_{\mathbf{V}}(\cdot)$ denotes a multi-layer 2D CNN over the intervened moment tensor $\mathbf{V}'\in \mathbb{R}^{d\times T \times T}$ that captures the temporal dependencies between adjacent moments into current moment $v$. Eq. (\ref{TCN}) is non-linear due to the rectified linear unit $\textit{Relu} (\cdot)$ behind each convolutional layer. Fortunately, based on the theoretical analysis of \cite{baldi2014dropout} on the rectified linear unit, the approximation $\mathbb{E}(\textit{Relu} (x))\approx \textit{Relu}\left(\mathbb{E}\left[x\right]\right)$ still holds. Then we can obtain \begin{equation}\label{TCN2} \mathbb{E}_{\bm{\ell}}\left[f(\mathbf{q}, \mathbf{v}, \bm{\ell})\right] \approx \mathbf{w}^T\Big(\phi^*_{\mathbf{V}}\Big(\bar{\mathbf{q}} \odot \big({\bar{\mathbf{v}}+\mathbb{E}_{\bm{\ell}}\left[{h}_{qv}\big(\bm{\ell}\big)\right]}\big)\Big) \Big). \end{equation} \end{itemize} The key of the two above-mentioned cross-modal matching networks $f(\cdot)$ is to compute $\mathbb{E}_{\bm{\ell}}\left[{h}_{qv}\big(\bm{\ell}\big)\right]$. We implement ${h}_{qv}\big(\bm{\ell}\big)$ as the scaled Dot-Product attention \cite{vaswani2017attention} to adaptively assign weights on different location confounders in $\mathbf{L}=\left[\bm{\ell}_1, \cdots, \bm{\ell}_N\right]\in \mathbb{R}^{N\times d}$ with specific input of query $q$ and moment $v$. Then we have \begin{equation}\label{attention} \mathbb{E}_{\bm{\ell}}\left[{h}_{qv}\big(\bm{\ell}\big)\right]=\sum_{\bm{\ell}}\big[\mathrm{softmax}\big(\mathbf{K}^T\mathbf{m}/\sqrt{d}\big)\odot {\mathbf{L}'}\big]P(\bm{\ell}), \end{equation} where $\odot$ denotes the element-wise product that supports broadcast, and $\mathbf{m}=\mathbf{W}_5\mathbf{q} + \mathbf{W}_6\mathbf{c}^v$, $\mathbf{K}=\mathbf{W}_7\mathbf{L}^T$, and $\mathbf{L}'=\mathbf{L}\mathbf{W}_2^T$ with learnable parameters $ \mathbf{W}_5, \mathbf{W}_6, \mathbf{W}_7$, and $\mathbf{W}_2\in\mathbb{R}^{d\times d}$. So far, we have introduced the implementation of the proposed DCM. Note that, we do not use the feature of original moment location $(t_s, t_e)$ in the inference stage. Given the representation of query $\mathbf{q}$ and moment candidate $\mathbf{v}$, we can predict the deconfounded cross-modal matching score as $s=\sigma\big(\mathbb{E}_{\bm{\ell}}\left[f(\mathbf{q}, \mathbf{v}, \bm{\ell})\right]\big)$, where the confounder vector $\bm{\ell}$ is disentangled from moment representation. \subsubsection{\textbf{Learning Objective}} \label{losses}To train the DCM-based VMR methods, we use the scaled Intersection over Union (IoU) score \cite{zhang2019learning} between the locations of moment candidate $v$ and groundtruth $v_{gt}$ as the supervision $y$. The basic loss is the binary cross entropy loss: \begin{equation}\label{BCEloss} \mathcal{L}_{bce}(\mathbf{q},\mathbf{v}, y) = -\big(y\log(s) + (1-y)\log(1-s)\big). \end{equation} In this work, we not only train our method with positive query-video training pairs but also exploit the negative query-video pairs as \textbf{counterfactual} training data to optimize the network parameters. Existing efforts all assume that the existence of target moment in the given video is true, forgoing teaching the model the ability of \textit{counterfactual thinking}, \textit{i.e., What if the target moment does not exist in the given video?}. By introducing the \textit{counterfactual thinking}, we expect the learned model to focus more on the content of video and query, rather than the location of moment candidates. In summary, our model is trained with a linear combination of four losses: \begin{equation}\label{full_loss} \mathcal{L}=\mathcal{L}_{bce}^+ + \mathcal{L}_{bce}^- + \lambda_1 \mathcal{L}_{recon} + \lambda_2 \mathcal{L}_{indep}, \end{equation} where the \textbf{counterfactual loss} $\mathcal{L}_{bce}^-$ is computed over negative query-video pairs with the supervision $y=0$. $\mathcal{L}_{recon}$ and $\mathcal{L}_{indep}$ are two learning terms for feature disentangling in section \ref{disentangled} with two hyperparameters $\lambda_1$ and $\lambda_2$. We implement the reconstruction term by $\mathcal{L}_{recon}=\lVert \bm{\ell}^v - \mathbf{p} \rVert_2$ for its simplicity. The independence term is implemented based on distance correlation~\cite{szekely2007measuring}: $\mathcal{L}_{indep}={\textrm{dCov}(\bm{\ell}^v, \mathbf{c}^v)}/{\sqrt{\textrm{dVar}(\bm{\ell}^v) \cdot \textrm{dVar}(\mathbf{c}^v) }}$, where $\textrm{dCov}(\cdot)$ and $\textrm{dVar}(\cdot)$ denote the distance covariance and variance, respectively. The overall loss is computed as the average over a training batch. \section{Experiments}\label{exp} In this section, we evaluate the effectiveness of our DCM methods by extensive comparison with baseline methods (CMI and TCN) and SOTA VMR methods in both IID and OOD settings. \vspace{-0.5em} \subsection{Datasets and Experimental Setting} \subsubsection{\textbf{Datasets}} We validate the performance of DCM methods on three public datasets: \textbf{ActivityNet-Captions} (ANet-Cap)~\cite{krishna2017dense}, \textbf{Charades-STA}~\cite{gao2017tall}, and \textbf{DiDeMo}~\cite{anne2017localizing}: \noindent{(1) \textit{ANet-Cap}} depicts diverse human activities in daily life, consisting of about 20k videos taken from the ActivityNet caption dataset~\cite{krishna2017dense}. We follow the setup in \cite{zhang2019cross,zhang2019learning,NIPS2019_8344} to split the dataset; \noindent{(2) \textit{Charades-STA}} is constructed for VMR by \cite{gao2017tall} based on the Charades video dataset~\cite{sigurdsson2016hollywood}. The videos are about daily indoor activities. Currently, it is the most popular VMR dataset; \noindent{(3) \textit{DiDeMo}} is prepared by \cite{anne2017localizing} with more than 10k videos from YFCC100M. It depicts diverse human activities in real world. The detailed dataset statistics are summarized in Table \ref{dataset_statistics}. \begin{table}[tb] \renewcommand{\arraystretch}{0.97} \renewcommand\tabcolsep{3.4pt} \caption{The statistics of three public VMR datasets.} \vspace{-0.15in} \centering \scalebox{0.87}{% \begin{threeparttable} \begin{tabular}{c|c|c|c|c} \hline \hline Dataset & $\#$Videos &$\#$Anno. (train/val/test) &$\overline{L}_{\textrm{vid}}$ &$\overline{L}_{\textrm{mom}}\pm{\triangle}_{\textrm{mom}}$\\ \hline ANet-Cap&19,207 &37,417/17,505/17,031 &117.6s&36.2$\pm40.2$s\\ Charades-STA&6,672 & 12,408/-/3,720&30.6s&8.2$\pm 3.6$s\\ DiDeMo&10,464 &132,233/16,765/16,118 &30s&6.85$\pm3.5$s\\ \hline \end{tabular} \begin{tablenotes} \footnotesize \item[1] $\#$Anno. denotes the number of query-moment annotation pairs in different sets (train/val/test). \item[2] $\overline{L}_{\textrm{vid}}$ and $\overline{L}_{\textrm{mom}}$ denote the average lengths of videos and moments, respectively. \item[3] ${\triangle}_{\textrm{mom}}$ denotes the standard deviation of moment length. \item[4] In DiDeMo~\cite{anne2017localizing}, each query may have multiple moment annotations. \end{tablenotes} \end{threeparttable}} \vspace{-0.12in} \label{dataset_statistics} \end{table} \begin{table*}[tb] \renewcommand{\arraystretch}{0.9} \renewcommand\tabcolsep{2.8pt} \definecolor{white}{rgb}{1,1,1} \caption{Performance comparison (R@1,\%) with state-of-the-arts (SOTAs) and baselines (Bases) on three datasets (The higher the better). The $\dagger$ and $\ddagger$ denote relative improvements larger than $5\%$ and $10\%$ \textit{w.r.t.} R@1, respectively. The $\ast$ and $\star$ denote the statistical significance \textit{w.r.t.} mIoU for $p<0.05$ and $p<0.01$, respectively, compared with the baseline counterparts. \vspace{-0.12in} \centering \scalebox{0.86}{% \begin{threeparttable} \begin{tabular}{c|{c}||*{2}{l}{l}||*{2}{l}{l}||*{2}{l}{l}||*{2}{l}{l}||*{2}{l}{l} } \hline &\multirow{3}{*}{\textbf{Method}} & \multicolumn{3}{c||}{\textbf{ANet-Cap} (C3D)}&\multicolumn{3}{c||}{\textbf{Charades-STA}(C3D)}&\multicolumn{3}{c||}{\textbf{Charades-STA}(I3D)}&\multicolumn{3}{c||}{\textbf{Charades-STA}(VGG)}&\multicolumn{3}{c}{\textbf{DiDeMo} (Flow)}\\ \cline{3-16} & &\multicolumn{2}{c}{\textbf{IoU>m}} & \multirow{2}{*}{\textbf{mIoU}} &\multicolumn{2}{c}{\textbf{IoU>m}} & \multirow{2}{*}{\textbf{mIoU}} &\multicolumn{2}{c}{\textbf{IoU>m}} & \multirow{2}{*}{\textbf{mIoU}} &\multicolumn{2}{c}{\textbf{IoU>m}} & \multirow{2}{*}{\textbf{mIoU}} &\multicolumn{2}{c}{{\textbf{IoU>m}}} & \multirow{2}{*}{\textbf{mIoU}}\\ \cline{3-4} \cline{6-7} \cline{9-10} \cline{12-13} \cline{15-16} && 0.5 & 0.7 & & 0.5 & 0.7 & & 0.5 & 0.7 & & 0.5 & 0.7 && 0.7 & 1.0 & \\ \hline \hline \multirow{8}{*}{\rotatebox{90}{\textbf{SOTAs (IID)}} } & MAN\cite{zhang2019man} & -& -&- &- &- &- & - & - & - &46.5 &22.7 &- & - &27.0 &41.2 \\ & CBP \cite{wang2019temporally} & 35.8 & 17.8 & 36.9 &36.8 &18.9 &35.7 & - & - & & - & - & - & - &- & - \\ & SCDM \cite{NIPS2019_8344} & 36.8 & 19.9 & - &- & - &- &54.4&33.4 & - & - & - & - & - &- & - \\ & 2D-TAN\cite{zhang2019learning} & 44.5& {26.5} &43.2 &47.0 &27.2 &42.0 & 53.7&31.2 & 47.0 &42.8 &23.3 &- &35.3 &25.6 &47.8 \\ & DRN \cite{zeng2020dense} &\textbf{45.5} &24.4 &- &45.4 &26.4 &- & 53.1 & 31.8 & - &42.9 &23.7 &- & - &- & - \\ & LGI \cite{mun2020LGI} &43.0 &25.1 &42.6 &50.5 &27.7 &44.9 &59.5 &35.5 &51.4&44.7&24.0 &40.8 & - &- & - \\ & VSLNeT \cite{zhang-etal-2020-span} &43.2 &26.2 &{43.2} &47.3 &30.2&45.2 & 53.3&33.7 &49.9 & 39.2 &20.8 &40.3 & - &- & - \\ \hline \rowcolor{gray!12} \hline \hline \cellcolor{white}& Freq-Prior &29.7 &13.9 &32.0 & 29.7 &16.3 &30.1 & 29.7 &16.3 &30.1 & 29.7 &16.3 &30.1 &23.3&19.4 &31.9 \\ \rowcolor{gray!12} \cellcolor{white}& Blind-TAN &45.3 &\textbf{28.6} &\textbf{43.9}$\pm 0.4$ & 40.2 &23.5 &36.7$\pm 0.2$ & 40.2 &23.5 &36.7$\pm 0.2$ & 40.2 &23.5 &36.7$\pm 0.2$ &24.4 &19.4 &34.5$\pm 1.4$ \\ \cline{2-17} & CMI & 40.6 &23.2&41.1$\pm0.3$ &43.3&24.6&40.2$\pm0.4$ &48.5&28.1&43.6$\pm0.5$ &40.1&21.9&37.7$\pm 0.4$ &32.9 &25.1 &44.1$\pm 0.5$ \\ & \textbf{CMI+DCM} &41.4&23.9 &41.6$\pm0.3^\ast$ &52.8$^\ddagger$ & 32.1$^\ddagger$ &47.0$\pm0.4$$^{\star}$ &57.5$^\ddagger$&34.9$^\ddagger$ &50.4$\pm0.3^\star$ &45.2$^\ddagger$ &26.0$^\ddagger$ & 41.5$\pm 0.4^\star$ &\textbf{37.6}$^\ddagger$&\textbf{27.8}$^\ddagger$ &49.4$\pm 0.5^\star$ \\ \cline{2-17} & TCN &43.3 &26.1 &42.3$\pm0.5$ &48.0 &28.9 &43.1$\pm0.5$ &52.6 &32.3 &46.3$\pm0.4$ &43.1 &25.0 &39.3$\pm 0.8$ &35.1 &26.0 &47.4$\pm 0.7$\\ \multirow{-6}{*}{\rotatebox{90}{\textbf{Bases (IID)}}} &\textbf{TCN+DCM} &44.9 &{27.7}$^\dagger$ &{43.3}$\pm0.2$$^{\star}$ &\textbf{55.8}$^\ddagger$ &\textbf{34.4}$^\ddagger$ &\textbf{48.7}$\pm 0.5$$^{\star}$ &\textbf{59.7}$^\ddagger$& \textbf{37.8}$^\ddagger$&\textbf{51.5}$\pm 0.4^\star$ &\textbf{47.8}$^\ddagger$ &\textbf{28.0}$^\ddagger$&\textbf{43.1}$\pm 0.4^\star$ &37.5$^\dagger$ &27.6$^\dagger$ &\textbf{49.9}$\pm 0.5^\star$ \\ \hline \hline \rowcolor{gray!12}\cellcolor{white} & Freq-Prior &3.9 & 0 &20.6 &0.1 &0 &7.7 &0.1 &0 &7.7 &0.1 &0 &7.7 &0 & 0 & 0 \\ \rowcolor{gray!12}\cellcolor{white}& Blind-TAN &16.2 &6.4 &22.0$\pm0.2$ & 15.0 &6.1 &19.2$\pm 0.4$ & 15.0 &6.1 &19.2$\pm 0.4$ & 15.0 &6.1 &19.2$\pm 0.4$ &3.9 &2.1 &6.8$\pm 2.8$ \\ & {LGI} \cite{mun2020LGI} &16.3&6.2 &22.2 & 26.2&11.4 &26.8 &42.1 &18.6 &41.2 &24.1 &8.2 &27.8 & - & - & - \\ & {VSLNeT} \cite{zhang-etal-2020-span} & - & - & - &21.9&12.0 &30.0 &17.5 &8.8 &26.5 & - & - &- & - & - & - \\ \cline{2-17} & CMI &12.3 &5.2 &19.1$\pm 0.5$ &32.1 &15.3 &36.1$\pm 2.5$ &30.4 &16.4 &30.3$\pm 4.2$ &20.5 &8.0 &25.6$\pm 7.4$ &21.4 &18.1 &32.7$\pm0.6$ \\ & \textbf{CMI+DCM} &16.8$^{\ddagger}$ &6.4$^{\ddagger}$ &23.9$\pm0.3^\star$ & 33.7$^\dagger$ & \textbf{17.2}$^\ddagger$ & 37.4$\pm0.6$ &37.8$^\ddagger$ &\textbf{19.7}$^\ddagger$ &39.6$\pm0.8^\star$ &24.5$^\ddagger$&11.5$^\ddagger$ &31.3$\pm 0.8^\ast$ &29.9$^\ddagger$&23.7$^\ddagger$ &40.0$\pm 2.0^\star$ \\ \cline{2-17} & TCN &16.4 & 6.6 &23.2$\pm0.9$ &30.6 &13.2 &30.8$\pm2.3$ & 27.1 & 13.1 &25.7$\pm3.2$ & 21.8&9.1 &25.9$\pm 1.2$ &29.9 &21.9 &\textbf{42.1}$\pm1.6$ \\ \multirow{-8}{*}{\rotatebox{90}{\textbf{OOD-1}}}& \textbf{TCN+DCM} &\textbf{18.2}$^{\ddagger}$ & \textbf{7.9}$^{\ddagger}$ & \textbf{24.4}$\pm0.5$$^{\star}$ &\textbf{39.7}$^\ddagger$ &{16.3}$^\ddagger$ & \textbf{39.6}$\pm 0.9$$^{\star}$ &\textbf{44.4}$^\ddagger$&\textbf{19.7}$^\ddagger$& \textbf{42.3}$\pm 1.1^\star$ &\textbf{31.6}$^\ddagger$ &\textbf{12.2}$^\ddagger$&\textbf{34.3}$\pm 0.9^\star$ &\textbf{31.6}$^\dagger$ &\textbf{24.4}$^\ddagger$ &42.0$\pm 1.6$ \\ \hline \hline \rowcolor{gray!12} \cellcolor{white}& Freq-Prior &0.5 &0 & 18.4 &0 &0 &2.5 &0 &0 &2.5 &0 &0 &2.5 & 0& 0&0 \\ \rowcolor{gray!12}\cellcolor{white}& Blind-TAN &11.1 &3.7 &17.8$\pm0.4$ &13.4 &4.4 &16.1$\pm 0.5$ &13.4 &4.4 &16.1$\pm 0.5$ &13.4 &4.4 &16.1$\pm 0.5$ &3.9 &2.1 &6.7$\pm 2.5$ \\ & {LGI} \cite{mun2020LGI} &11.0&3.9 &17.3 &20.3 &7.4& 22.1 &35.8&13.5 &37.1 &18.8&5.3&24.3 & - & - & -\\ & {VSLNeT} \cite{zhang-etal-2020-span} & - & - & - & 17.4&9.2 &20.7 &10.2 &4.7 &18.4 & - & - & - & - & - & - \\ \cline{2-17} & CMI &10.0& 4.2 &16.8 $\pm0.6$ & 28.5&12.3&35.3$\pm2.4$ &28.1&13.6 &29.0$\pm4.8$ &16.0&5.31 &24.5$\pm 6.9$ &18.3 &15.7 &25.9$\pm 3.4$ \\ & \textbf{CMI+DCM} &\textbf{13.1}&\textbf{5.2} &\textbf{21.6}$\pm0.4$$^{\star}$ & 30.5$^\dagger$ & \textbf{15.2}$^\ddagger$ &35.4$\pm0.8$ &33.2$^\ddagger$ &\textbf{17.1}$^\ddagger$ &36.7$\pm1.1^\star$ &21.1$^\ddagger$ &\textbf{9.6}$^\ddagger$ &29.1$\pm 0.5^\ast$ &29.5$^\ddagger$&23.2$^\ddagger$ &39.3$\pm 2.6^\star$ \\ \cline{2-17} & TCN &11.5 & 3.9 &19.4$ \pm0.9$ & 25.7 & 9.3 &28.4$\pm2.5$ & 21.1 &8.8 &22.5$\pm2.9$ &17.6 &6.2 &22.2$\pm 1.5$ &28.0 &21.2 &\textbf{40.1}$\pm 1.6$ \\ \multirow{-8}{*}{\rotatebox{90}{\textbf{OOD-2}}}& \textbf{TCN+DCM} & 12.9$^{\ddagger}$ &4.8$^{\ddagger}$ & 20.7$\pm0.5$$^\ast$ &\textbf{33.8}$^\ddagger$ &12.4$^\ddagger$ & \textbf{36.3}$\pm 1.1$$^{\star}$ &\textbf{38.5}$^\ddagger$& 15.4$^\ddagger$&\textbf{39.0}$\pm 1.2^\star$ &\textbf{27.8}$^\ddagger$&9.3$^\ddagger$&\textbf{32.1}$\pm 1.0^\star$ &\textbf{30.0}$^\dagger$ &\textbf{23.4}$^\ddagger$ &39.8$\pm 1.7$ \\ \hline \end{tabular}% \begin{tablenotes} \footnotesize \item[1] We report the average performance of \textbf{10 runs on Charades-STA and DiDeMo, and 5 runs on ANet-Cap}, with different random seeds for network initialization. For each run, we select the best-performing model on original testing set to conduct two rounds of OOD testing, \textit{i.e.}, OOD-1 and OOD-2, with different values of $\rho$ mentioned in section \ref{OOD}. "-" means that the result on the dataset is not reported by the paper or its model is unavailable. \end{tablenotes} \end{threeparttable}} \vspace{-0.2in} \label{tab:SOTA} \end{table*} \subsubsection{\textbf{Metrics}} We adopt the rank-1 accuracy (\textbf{R@1}) with different IoU thresholds (\textbf{IoU>$m$}), and \textbf{mIoU} as the evaluation metrics, following \cite{gao2017tall,zhang2019learning,zhang-etal-2020-span}. The "R@1, IoU>$m$" denotes the percentage of queries having top-1 retrieval result whose IoU score is larger than $m$. "mIoU" is the average IoU score of the top-1 results over all testing queries. In our experiments, we use $m\in\{0.5,0.7\}$ for ANet-Cap and Charades-STA, and $m\in\{0.7, 1.0\}$ for DiDeMo. Different from existing efforts which also report "R@5" accuracy, we only report {"R@1, IoU>$m$" ($m\geq 0.5$) and "mIoU"} for stricter evaluation. \subsubsection{\textbf{Out-of-Distribution Testing}}\label{OOD} The split of datasets in Table \ref{dataset_statistics} follows the Independent and Identically Distributed (IID) assumption, which is insufficient to evaluate the generalization. Instead, we evaluate the models not only using IID testing, but also adopting {Out-of-Distribution (OOD)} testing~\cite{teney2020value}. The idea is to insert a randomly-generated video clip with $\rho$ seconds at the beginning of videos. Then the temporal length of each video is changed to $\tau + \rho$ and the timestamps of target moment are changed accordingly, \textit{i.e.}, $(\tau_s + \rho, \tau_e + \rho)$. For each dataset, we select the best-performing model on original testing set to conduct \textbf{two rounds of OOD testing} with different $\rho$. We use $\rho\in\{30,60\}$ for ANet-Cap, $\rho\in\{10,15\}$ for Charades-STA, and $\rho\in\{15,30\}$ for DiDeMo. The frame feature of the inserted video clip is randomly generated from a normal distribution. By the OOD testing, we keep the matching relationship unchanged while significantly changing the location distribution of moments to test the generalizability of models. \subsubsection{\textbf{Comparison Methods}} (1) \textit{Baselines}. As mentioned in section \ref{dcm_imp}, we implement our method with two matching networks: \textbf{CMI} and \textbf{TCN}. We use them as two baseline methods by just replacing $\bar{\mathbf{v}}+\mathbb{E}_{\bm{\ell}}\left[{h}_{qv}(\bm{\ell})\right]$ with original representation $\mathbf{v}$. Our methods are termed by adding a suffix: \textbf{+DCM}. The kernel size of the convolutional operation in CMI is $3\times 3$ and TCN is implemented by a 3-layer CNN with kernel size $5\times 5$. We also include two \textbf{biases-based methods} that explicitly exploit the temporal location biases: a) \textbf{Freq-Prior}: it models the moment frequency prior $P(Y|L)$ where the prediction on each moment candidate only depends on the frequency of location annotations in training set; b) \textbf{Blind-TAN}~\cite{otani2020uncovering}: it models $P(Y|Q,L)$ that excludes moment representation from the model input, implemented by replacing the moment feature in TCN with the positional embedding~\cite{vaswani2017attention} of moment location $(t_s,t_e)$. (2) \textit{State-of-the-art methods (SOTAs)}. We also compare our methods with the reported results of SOTAs on IID testing sets, such as SCDM~\cite{NIPS2019_8344}, 2D-TAN~\cite{zhang2019learning}, DRN~\cite{zeng2020dense}, LGI~\cite{mun2020LGI}, and VSLNeT~\cite{zhang-etal-2020-span}. \subsubsection{\textbf{Implementation Details}} For the language query, we use 300d glove vectors as the word embeddings. The dimension of query and moment representations is set to $d=512$. The batchsize is set to 64 for ANet-Cap and DiDeMo, and 32 for Charades-STA, respectively. We adopt Adam as the optimizer with learning rate $1e-4$. The hyperparameters $\lambda_1$ and $\lambda_2$ are fixed as 1 and 0.001, respectively. We use the PCA-reduced C3D~\cite{tran2015learning} features as frame-level representation of ANet-Cap. We use three widely-used backbone networks (C3D, I3D~\cite{carreira2017quo}, and VGG~\cite{VGG}) to extract video representation of Charades-STA, respectively. We use the flow features in \cite{anne2017localizing} as video representation of DiDeMo. We follow \cite{zhang2019learning} to sample moment candidates from video and set the number of clips $T$=16 for ANet-Cap and Charades-STA and $T$=6 for DiDeMo. \textit{Besides, we exclude the long moments ($L_\textrm{mom}/L_\textrm{vid}\geq0.5$, nearly 4k in testing set) for OOD testing on ANet-Cap, since we found the OOD performance of Freq-Prior on these long moments is quite high}. \subsection{Overall Performance Comparison} \subsubsection{\textbf{Comparison with Baselines}} \label{baselien_comp} We report the empirical results of all baseline methods in Table \ref{tab:SOTA} on both IID (\textit{i.e.}, original) and OOD testing sets. The relative improvement and statistical significance test are performed between DCM methods and their baseline counterparts. We have the following observations: \begin{itemize} \item All three datasets have strong temporal location biases, revealed by the two biased methods. By using the prior $P(Y|L)$ without training, Freq-Prior reports nearly 30\% mIoU on all IID testings. By using $P(Y|Q,L)$, Blind-TAN reports much higher R@1(IoU>0.5) accuracy. In particular, a SOTA result (45.3\%) is reported in ANet-Cap. When evaluated by OOD testing, their performances drop significantly. The results support the empirical analysis in \cite{otani2020uncovering} and indicate the necessity of OOD testing. \item The DCM methods consistently improve TCN and CMI in all settings, which suggests that DCM is agnostic to the methods, datasets, backbones, and distributions of testing sets. In particularly, the improvements on OOD testing are typically larger than those on IID testing. For example, the relative improvement \textit{w.r.t.} R@1(IoU>0.5) is 2.82\% on IID testing and 23.68\% on OOD testing on ANet-Cap. It reflects that traditional VMR models are vulnerable to the biases in datasets and sensitive to the distribution changes of moment annotations, and clearly demonstrates the high effectiveness of our DCM. We attribute such improvement to the following aspects: 1) the disentangling module reduces the effect of location on moment representation in the feature level, endowing the models with a stronger ability of precisely exploiting the video content; and 2) by the causal intervention, DCM is forced to fairly consider all the possible locations of target moment, via backdoor adjustment, to make a robust prediction which avoids exploiting the temporal location biases in datasets and therefore improves the generalizability of models. \item We find that the improvements of DCM on Charades-STA are much larger than those on the other datasets. It might be due to its relatively small training set, as shown in Table \ref{dataset_statistics}. Models can be more easily misled by the temporal location biases when trained with less data. In particular, the TCN method, with more training parameters, reports much worse generalization performance than the lightweight method, CMI, on the small dataset. \item Even on the two OOD testing sets, Blind-TAN still reports more than 10\% R@1(IoU>0.5) score on ANet-Cap and Charades-STA, which indicates the high correlation between query and location. In fact, the prior $P(Y|Q,L)$ can be mitigated by re-split the dataset based on moment locations, \textit{i.e.}, forcing the locations of target moments in testing set to be unseen in training set. For easy comparison with existing results, we do not re-split the datasets. \item We find the OOD evaluation results on ANet-Cap are much lower than those of other datasets, since we exclude the long moments from its ODD testing. The reason is that moment length also leads to a prior in $P(Y|L)$. For the long target moments with length $L_\textrm{mom}/L_\textrm{vid}\geq0.5$, we can obtain 100\% R@1(IoU>0.5) by just returning the whole video as the prediction. The number of long moments in the testing set of ANet-Cap is nearly 4K. We remove them to keep the effectiveness of OOD testing. \end{itemize} \subsubsection{\textbf{Comparison with State-of-the-art Results}} We include the reported results of recent SOTA methods, such as LGI~\cite{mun2020LGI} and VSLNet~\cite{zhang-etal-2020-span}, in Table \ref{tab:SOTA}. We observe that TCN+DCM and CMI+DCM achieve new SOTA results \textit{w.r.t.} R@1(IoU>0.7) on IID testing: 27.7\% on ANet-Cap, 27.8\% on DiDeMo, and {34.4\%, 37.8\%, 28\%} on Charades-STA with different backbones. We also report the OOD testing results of LGI and VSLNet using their released models or codes. We find that our DCM methods significantly outperform SOTA methods \textit{w.r.t.} R@1(IoU>0.7) on OOD testing, \textit{e.g.}, 27.4\% relative improvement on OOD-1 on ANet-Cap and 26.7\% improvement on OOD-2 on Charades-STA (I3D) over LGI. The result is consistent with the comparison with baseline counterparts. It demonstrates that DCM can not only retain the good location bias to improve the accuracy in original testing set, but also remove the bad confounding effects of location to improve the generalization. \begin{table}[tb] \renewcommand{\arraystretch}{0.95} \renewcommand\tabcolsep{3pt} \definecolor{white}{rgb}{1,1,1} \caption{Ablation studies. The $\ast$ and $\star$ denote the statistical significance for $p<0.05$ and $p<0.01$, respectively. \vspace{-0.12in} \centering \scalebox{0.9}{% \begin{threeparttable} \begin{tabular}{c|l||ll||ll||ll} \hline &\multirow{3}{*}{\textbf{TCN+DCM}} & \multicolumn{2}{c||}{\textbf{ANet-Cap}}&\multicolumn{2}{c||}{\textbf{Charades.}}&\multicolumn{2}{c}{\textbf{DiDeMo}}\\ \cline{3-8} &&\multicolumn{2}{c||}{\textbf{IoU>m}} &\multicolumn{2}{c||}{\textbf{IoU>m}} &\multicolumn{2}{c}{\textbf{IoU>m}} \\ \cline{3-8} & & 0.5 & 0.7 & 0.5 & 0.7 & 0.7 & 1.0 \\ \cline{1-8} &\textbf{Full Model}&\underline{44.9}&\underline{27.7}&\underline{59.7}&\underline{\textbf{37.8}} &\underline{\textbf{37.5}}&\underline{\textbf{27.6}} \\ \cline{2-8} &\textit{w/o feat. disent.}&43.7$^\star$&26.7$^\star$&\textit{55.0}$^\star$&\textit{33.7}$^\star$ &36.2$^\star$&26.7$^\star$\\ &\textit{w/o indep. loss}&44.7&27.7&\textbf{59.8}&37.4 &37.1$^\star$&27.3 \\ &\textit{w/o recon. loss}&\textit{42.7}$^\star$ &\textit{25.7}$^\star$&55.8$^\star$&34.5$^\star$ &\textit{35.7}$^\star$&\textit{26.6}$^\star$ \\ &\textit{w/o loc. feat.}&{44.4}$^\ast$ &{27.1}$^\ast$&\textbf{59.8}&37.3$^\ast$ &37.1$^\star$&27.4$^\ast$ \\ &\textit{w/o counterf. loss}&45.3&28.9$^\star$&58.2$^\star$&37.3$^\star$ &37.0$^\star$&26.7$^\star$\\ \multirow{-6}{*}{\rotatebox{90}{\textbf{IID Test}}}&\textit{w/o causal interv.}&\textbf{45.6}&\textbf{29.5}&57.7$^\star$&37.1$^\star$ &36.8$^\star$&26.9$^\star$ \\ \hline \hline &\textbf{Full Model}&\underline{\textbf{18.2}}&\underline{\textbf{7.9}}&\underline{\textbf{44.4}}&\underline{\textbf{19.7}} &\underline{\textbf{31.6}}&\underline{\textbf{24.4}}\\ \cline{2-8} &\textit{w/o feat. disent.}&17.7 &7.3$^\ast$&34.3$^\star$&17.0$^\star$ &{29.3}$^\star$&{22.4}$^\star$ \\ &\textit{w/o indep. loss}&18.1 &7.7&43.8&19.1 &31.0&23.9 \\ &\textit{w/o recon. loss}&17.8&7.2&38.2$^\star$&18.6 &30.7&22.7$^\star$ \\ &\textit{w/o loc. feat.}&{17.7} &{7.1}$^\ast$&43.5&19.2 &\textit{28.4}$^\star$&\textit{22.3}$^\star$ \\ &\textit{w/o counterf. loss}&17.0$^\ast$ &7.3&40.2$^\star$&18.0$^\star$ &31.1&23.5 \\ \multirow{-6}{*}{\rotatebox{90}{\textbf{OOD-1 Test}}} &\textit{w/o causal interv.}&\textit{16.4}&\textit{6.7}$^\star$&\textit{34.1}$^\star$&\textit{15.9}$^\star$ &31.1&23.3$^\star$ \\ \hline \end{tabular} \end{threeparttable}} \vspace{-0.14in} \label{tab:abl} \end{table} \subsection{Study of DCM}\label{study} For a better understanding of DCM, we use TCN+DCM as an example to analyze the contribution of individual components. Empirical results on the three datasets\footnote{If not specifically stated, we use the I3D backbone for Charades-STA by default.} are shown in Table \ref{tab:abl} and Figure \ref{fig4}. \subsubsection{\textbf{Effect of Feature Disentangling}} As a core of DCM, the disentangling module decomposes moment representation into two latent factors: content and location using two specific losses, which ensures the visual content of moments be fairly treated and perceived. Here, we investigate, in Table \ref{tab:abl}, how this module affect the performance by alternatively removing the whole module (\textit{w/o feat. disent.}), the independence loss (\textit{w/o indep. loss}), the reconstruction loss (\textit{w/o recon. loss}) , and the disentangled location feature $\bm{\ell}^v$ in $\bar{\mathbf{v}}$ (\textit{w/o loc. feat.}) from the model. We have several findings: \begin{itemize} \item We observe clear performance drop in all settings when removing the disentangling module. The reasons are two folds: 1) The entangled moment feature is weak in capturing the core feature of moment content. The latent location factor may dominate the moment representation, leading to poor generalization; and 2) without the disentangling, the confounder set has to be composed by the positional embedding of original locations $(\tau_s, \tau_e)$. As mentioned in section \ref{disentangled}, injecting the extra location feature into $\mathbf{v}$ may further exacerbate the correlation between $V$ and $L$, which hurts the model expressiveness. The results support the analysis in \cite{denton2017unsupervised} on the importance of video representation disentangling and clearly indicate the necessity of the module in DCM. \item We use distance correlation to model the independence between the moment content and location vectors. The comparisons, \textit{w.r.t.} distance correlation and R@1 accuracy, are reported in Figure \ref{fig4} (a) and Table \ref{tab:abl}, respectively. We observe that a better OOD performance is substantially coupled with a higher independence across the board. This also supports the correlation between the performance and feature disentangling mentioned above. \textit{w/o indep. loss} hurts less the IID performance, since we use a small $\lambda_2=0.001$ to modulate its effect for stable training. \item \textit{w/o recon. loss} leads to consistently worse IID and OOD results. The reason is that the latent location factor is not disentangled accurately, and then causal intervention fails to cut off the backdoor path. The result is consistent with the above analyses. \item In our implementation of DCM, we additionally keep the disentangled location feature $\bm{\ell}^v$ in the moment representation $\bar{\mathbf{v}}$ to slightly improve the weight of current location. We observe that \textit{w/o loc. feat.} leads to clear performance drop in OOD testing. The results suggest the necessity of keeping the good location bias. The location feature facilitates the temporal context modeling, which is especially crucial to handle the queries including temporal languages, such \textit{before} or \textit{after}. That can be supported by the performance comparison across 4 query subsets with different temporal languages in Figure \ref{fig4} (b). We find that, compared with the overall comparison (44.9\% \textit{vs.} 43.3\% \textit{w.r.t.} R@1(IoU>0.5)) between TCN+DCM and TCN on ANet-Cap, the improvements in Figure \ref{fig4} (b) are more significant. It further verifies the advantages of DCM in exploiting the good location bias. \end{itemize} \begin{figure}[tb] \centering \includegraphics[width=3.1in]{temporal_language_dcc.pdf} \vspace{-0.12in} \caption{(a) Distance correlation of TCN+DCM on 3 datasets; (b) Performance comparison (R@1, IID) on 4 query subsets of ANet-Cap with specific temporal languages.} \vspace{-0.2in} \label{fig4} \end{figure} \subsubsection{\textbf{Effect of Causal Intervention}} Causal Intervention is the key module in DCM. It intervenes the multimodal input based on backdoor adjustment to cut off the backdoor path. It consists of two components: 1) representation intervention, \textit{i.e.}, the addition of $\mathbb{E}_{\bm{\ell}}\left[{h}_{qv}(\bm{\ell})\right]$ to $\bar{\mathbf{v}}$; and 2) counterfactual loss $\mathcal{L}^{-}_{bce}$ that endows DCM with the ability of counterfactual thinking. We investigate its effect in Table \ref{tab:abl} by alternatively removing the whole module (\textit{w/o causal interv.}) and the counterfactual loss (\textit{w/o counterf. loss}) from the model. We have the following observations: \begin{itemize} \item \textit{w/o causal interv.} leads to significant performance drops in OOD testing results. Compared with the full model, the relative performance drops \textit{w.r.t.} R@1(IoU>0.7) are 15.2\%, 19.3\%, and 4.5\% on three datasets, respectively. In particular, we surprisingly observe a large IID improvement (27.7$\rightarrow$29.5) but a significant OOD drop (7.9$\rightarrow$6.7) on ANet-Cap (the largest dataset) when removing causal intervention. This suggests that, without causal intervention, the model is at higher risk of exploiting dataset biases while making less use of video content. It is consistent with the remarkable performance of Blind-TAN on ANet-Cap in Table \ref{tab:SOTA}, which demonstrates that the issue of dataset biases is more serious in ANet-Cap. Overall, the results and analysis clearly indicate the effectiveness of causal intervention and further highlight the importance of introducing OOD testing into evaluation. \item If only removing the counterfactual loss $\mathcal{L}^{-}_{bce}$ from our learning objective in Eq. (\ref{full_loss}), we observe substantial performance drop of OOD testing results. This is consistent with the observation of \textit{w/o causal interv.}, which suggests that counterfactual loss is a perfect complement to the representation intervention in the loss level. It is able to prevent DCM from exploiting the location biases by penalizing high prediction scores on the biased locations in a negative video, like the prediction of Freq-Prior and Blind-TAN. \end{itemize} \begin{figure}[tb] \centering \includegraphics[width=3in]{moment_lens.pdf} \vspace{-0.12in} \caption{Performance comparison (R@1, IID) \textit{w.r.t.} the temporal lengths of annotated moments in three datasets. The ratio of moment annotations in each group to the total number in training set is also plot.} \vspace{-0.2in} \label{fig5} \end{figure} \subsubsection{\textbf{On the Moment Length}} We investigate how DCM affect the IID performance \textit{w.r.t.} the moment length (\textit{the shorter the more challenging}). The empirical results are reported in Figure \ref{fig5}. We have the following findings: \begin{itemize} \item We find the temporal lengths of annotated moments in ANet-Cap are quite diverse and there are nearly 25\% annotations with duration $L_\textrm{mom}/L_\textrm{vid}\geq0.5$. The baseline TCN achieves higher performance \textit{w.r.t.} R@1(IoU>0.5) on the long moment groups. The improvement might be attributed to the usage of dataset bias on moment lengths, as analyzed at the end of section \ref{baselien_comp}. The finding supports the observation in \cite{otani2020uncovering}. With causal intervention and counterfactual training, DCM-based method is prevented from exploiting such kind of dataset bias, thus reporting lower performance on these moment groups. While on the short moment groups in Figure \ref{fig5} (a), TCN+DCM reports significantly better performance over TCN. These results are consistent with the observation on ANet-Cap in Table \ref{tab:abl}. \item We observe substantial improvement of TCN+DCM over its counterpart, \textit{w.r.t.} R@1(IoU>0.5), across all groups in Charades-STA. In particular, on the first group in Figure \ref{fig5} (b) where the average duration of moments is just about 3s, we observe 168\% relative improvement of TCN+DCM over TCN. The finding clearly demonstrates the advantages of DCM-based methods in retrieving very short video moments. We also observe a bad performance of TCN on the long moment group (\textit{0.6}). It is not contrast to the observation from Figure \ref{fig5} (a), since there are just 0.2\% long moments with normalized length \textit{0.6} in the training set of Charades-STA and thus the model can not learn the length bias of long moments with such limited data. \item For the comparison on DiDeMo, we observe from Figure \ref{fig5} (c) that most of its annotations fall into the short moment group (\textit{0.2}). Our DCM method achieves significant improvement (13.4\%, \textit{w.r.t.} R@1(IoU>0.7)) over its counterpart on this group. \end{itemize} Overall, the observations from Figure \ref{fig5} clearly indicate the effectiveness of our DCM on moment retrieval in videos. \begin{figure}[tb] \centering \includegraphics[width=3.1in]{visualization.pdf} \vspace{-0.12in} \caption{The sampled moment retrieval results, \textit{w.r.t.} R@1, on both IID and OOD testing sets of Charades-STA. } \vspace{-0.2in} \label{fig6} \end{figure} \subsubsection{\textbf{Qualitative Results}} In this section, we present some qualitative results, as shown in Figure \ref{fig6}, to give an intuitive impression of the effectiveness of our DCM for VMR. Figure \ref{fig6} shows a real example from Charades-STA: retrieving the specific moment of "\textit{Person opens a cabinet door}" in the given video. We illustrate the R@1 retrieval results of TCN+DCM and its counterpart by both IID and OOD testing. We have the following findings: \begin{itemize} \item For the query in Figure \ref{fig6}, TCN+DCM performs stably against the distribution changes of moment location. In particular, in Figure \ref{fig6} (a), its top-1 retrieval result is the moment at timestamps ($0.0s, 3.7s$), which has more than 70\% overlap with the groundtruth annotation. When moved to the OOD testing by inserting a randomly-generated video segment at the beginning of the video, TCN+DCM can still find the best candidate with high IoU score. It reflects that DCM is not only robust to the \textit{distribution changes} but also robust to the noisy temporal context. \item TCN is sensitive to the distribution changes. The IoU score of its top-1 retrieval result significantly drops from 58\% in Figure \ref{fig6} (a) to zero in (b). The result is consistent with the previous analysis. It indicates that the location biases have severely affected the training of TCN, leading to low robustness. \end{itemize} \section{Related Work} \subsubsection{\textbf{Video Moment Retrieval}} Video moment retrieval (VMR) \cite{gao2017tall,anne2017localizing}, also termed temporal grounding/localization, attracts increasing attention in recent years~\cite{chen2018temporally,hendricks2018localizing,NIPS2019_8344}. It aims to retrieve a short video segments in videos using language queries. The key to solving VMR is how to effectively learn the cross-modal matching relationship between the language and video segments. Existing works mainly follow a cross-modal matching framework~\cite{anne2017localizing,gao2017tall,hendricks2018localizing,liu2018attentive,liu2018cross} that first generates a set of candidate moments, and then ranks them based on the matching score between the moment candidates and the language query. Gao \textit{et al.}~\cite{gao2017tall} and Liu \textit{et al.}~\cite{liu2018attentive,liu2018cross} used the traditional multi-scale sliding window to sample the candidates, which is simple but has low recall of short candidates. Zhang \textit{et al.}~\cite{zhang2019learning} proposed a stacked pooling network to densely enumerate all the valid candidates and store them in a three-dimensional tensor matrix to preserve the temporal structure, which allows CNNs to be applied in VMR for learning moment representation. The modeling of temporal structure of video moments, introduced in~\cite{zhang2019learning}, becomes increasingly popular~\cite{liu2020jointly,wang2020dual}. The difference among existing efforts mainly lies in the design of multimodal fusion module, \textit{e.g.}, cross-modal feature fusion~\cite{liu2018attentive,mun2020LGI,zhang-etal-2020-span} or pairwise similarity learning~\cite{anne2017localizing} following metric learning framework~\cite{yang2017person}. The former is more popular. Chen \textit{et al.}~\cite{chen2018temporally}, Yuan \textit{et al.}~\cite{yuan2019find}, and Mun \textit{et al.}~\cite{mun2020LGI} designed a complex visual-textual interaction/attention modules for cross-modal interaction. In particular, Mun \textit{et al.}~\cite{mun2020LGI} presented a video-text interaction algorithm in capturing relationships of semantic phrases and video segments by modeling local and global contexts, reporting SOTA performance. Yuan \textit{et al.} \cite{NIPS2019_8344} and Zhang \textit{et al.} \cite{zhang2019man,zhang2019learning} applied layer-wise temporal CNNs to model the temporal relations between moments, receiving more attention recently. \\ \noindent{\textbf{Difference between DCM and existing works:}} \textbf{1)} We focus on improving the generalizability of models, since recent findings~\cite{otani2020uncovering} reported that SOTA models tend to exploit dataset biases while agnostic to video content. Specifically, our DCM applies causal intervention to remove the confounding effects of moment location, which encourages the model to fairly consider all the possible locations of target for making a robust prediction; \textbf{2)} We introduce counterfactual training that endows the model with the ability of counterfactual thinking to answer the question "What if the target moment does not exist in the given video?". Different from our work, existing methods all assume that the target moment must be in the give video; \textbf{3)} We demonstrate the importance and necessity of applying OOD testing to evaluate the generalizability of VMR models, beyond the widely-used IID testing; \textbf{4)} We empirically indicate that existing methods are vulnerable to the temporal location biases in datasets. Our DCM has the potential to be coupled with exiting methods to improve their generalizability. \subsubsection{\textbf{Causal Inference}} Recently, causal inference~\cite{pearl2016causal,pearl2018book} has attracted increasing attention in information retrieval and multimedia for removing dataset biases in domain-specific applications, such as recommendation~\cite{sato2020unbiased,wang2020causal,yap2007discovering,feng2021causalgcn,wang2021clickbait}, visual dialog~\cite{qi2020two}, segmentation~\cite{zhang2020causal}, unsupervised feature learning~\cite{wang2020visual}, video action localization~\cite{liu2021blessing}, and scene graph~\cite{zhang2020causal}, \textit{etc.} The general purpose of causal inference is to empower the models the ability of pursuing the causal effect, thus leading to more robust decision. In particular, Qi \textit{et al.}~\cite{qi2020two} presented causal principles to improve visual dialog, where causal intervention is used to remove the effect of an unobserved confounder. Zhang \textit{et al.}~\cite{zhang2020causal} introduced causal inference into weakly-supervised semantic segmentation by removing confounding bias of context prior. Wang \textit{et al.}~\cite{wang2020visual} proposed to use causal intervention to learn "sense-making" visual knowledge beyond traditional visual co-occurrences. \textbf{Different from existing work}, we make a new attempt of causal inference~\cite{pearl2016causal} to solve the task of VMR. Specifically, we reveal the causalities between different components in VMR and point out that the temporal location of a video moment is a confounder that spuriously correlates the model prediction and multimodal input. To remove the harmful confounding effects, we develop a deconfounding method, DCM, that first disentangles moment representation to learn the core feature of visual content and then intervenes the multimodal input based on backdoor adjustment. This is the first causality-based work that addresses the temporal location biases of VMR, which is significantly different from a new VMR work \cite{nan2021interventional}. \section{Conclusion} This paper proposed a deconfounded cross-modal matching method for the VMR task. By introducing out-of-distribution testing into the model evaluation, we empirically demonstrated that existing VMR models are sensitive to the distribution changes of moment annotations, and found that the temporal location biases, hidden in current datasets, may severely affect the model training and prediction. Our proposed deconfounding algorithm is effective in improving the generalizability of VMR models. It can not only eliminate the bad but also retain the good bias of moment temporal location in videos. Our method has the potential to be effectively integrated with most exiting methods to improve their generalizability. This work showed initial attempts toward robust video moment retrieval against the dataset biases. In the future, we will further explore the intervention strategy on the user query to ensure a comprehensive understanding of complex user intents. Besides, we will also apply our deconfounding approach on other location-sensitive tasks, \textit{e.g.}, visual grounding~\cite{hong2019learning,yang2020weakly} and temporal activity localization~\cite{liu2021blessing}, to mitigate their location biases in datasets. \section{Acknowledgments} This research/project is supported by the Sea-NExT Joint Lab. \bibliographystyle{ACM-Reference-Format}
{'timestamp': '2021-06-04T02:07:58', 'yymm': '2106', 'arxiv_id': '2106.01534', 'language': 'en', 'url': 'https://arxiv.org/abs/2106.01534'}
arxiv
\section*{Appendices} \section{Architectures} \label{app:architecture} Table~\ref{tab:arch} specifies the ViT~\citep{dosovitskiy2021an,vaswani2017attention} and MLP-Mixer~\citep{tolstikhin2021mlpmixer} architectures used in this paper. ``S'' and ``B'' denote the small and base model scales following~\citep{dosovitskiy2021an, touvron2021training, tolstikhin2021mlpmixer}, followed by the size of each image patch. For instance, ``B/16'' means the model of base scale with non-overlapping image patches of resolution $16\times 16$. We use the input resolution $224\times 224$ throughout the paper. Following~\citet{tolstikhin2021mlpmixer}, we sweep the batch sizes in $\{32, 64, \dots, 8192\}$ on TPU-v3 and report the highest throughput for each model. \begin{table}[!ht] \caption{Comparison under the adversarial training framework on ImageNet (numbers in the parentheses denote the improvement over the standard adversarial training without SAM). With similar model size and throughput, ViTs-SAM can still outperform ResNets-SAM for clean accuracy and adversarial robustness. } \label{tab:adv} \centering \resizebox{1.\textwidth}{!}{ \begin{tabular}{l|cc|ccc|ccc} \toprule \textbf{Model} & \textbf{\#params} & \textbf{\tabincell{c}{Throughput \\ (img/sec/core)}} & \textbf{ImageNet} & \textbf{Real} & \textbf{V2} & \textbf{PGD-10} & \textbf{ImageNet-R} & \textbf{ImageNet-C} \\ \midrule \midrule \multicolumn{9}{c}{\textbf{ResNet}} \\ \midrule ResNet-50-SAM & 25M & 2161 & 70.1 (-0.7) & 77.9 (-0.3) & 56.6 (-0.8) & 54.1 (+0.9) & 27.0 (+0.9) & 42.7 (-0.1) \\ ResNet-101-SAM & 44M & 1334 & 73.6 (-0.4) & 81.0 (+0.1) & 60.4 (-0.6) & 58.8 (+1.4) & 29.5 (+0.6) & 46.9 (+0.3) \\ ResNet-152-SAM & 60M & 935 & 75.1 (-0.4) & 82.3 (+0.2) & 62.2 (-0.4) & 61.0 (+1.8) & 30.8 (+1.4) & 49.1 (+0.6) \\ \midrule \multicolumn{9}{c}{\textbf{Vision Transformer}} \\ \midrule ViT-S/16-SAM & 22M & 2043 & 73.2 (+1.2) & 80.7 (+1.7) & 60.2 (+1.4) & 58.0 (+5.2) & 28.4 (+2.4) & 47.5 (+1.6) \\ ViT-B/32-SAM & 88M & 2805 & 69.9 (+3.0) & 76.9 (+3.4) & 55.7 (+2.5) & 54.0 (+6.4) & 26.0 (+3.0) & 46.4 (+3.0) \\ ViT-B/16-SAM & 87M & 863 & 76.7 (+3.9) & 82.9 (+4.1) & 63.6 (+4.3) & 62.0 (+7.7) & 30.0 (+4.9) & 51.4 (+5.0) \\ \midrule \multicolumn{9}{c}{\textbf{MLP-Mixer}} \\ \midrule Mixer-S/16-SAM & 18M & 4005 & 67.1 (+2.2) & 74.5 (+2.3) & 52.8 (+2.5) & 50.1 (+4.1) & 22.9 (+2.6) & 37.9 (+2.5) \\ Mixer-B/32-SAM & 60M & 4209 & 69.3 (+9.1) & 76.4 (+10.2) & 54.7 (+9.4) & 54.5 (+13.9) & 26.3 (+8.0) & 43.7 (+8.8) \\ Mixer-B/16-SAM & 59M & 1390 & 73.9 (+11.1) & 80.8 (+11.8) & 60.2 (+11.9) & 59.8 (+17.3) & 29.0 (+10.5) & 45.9 (+12.5)\\ \bottomrule \end{tabular}} \vspace{-5pt} \end{table} \begin{table}[!ht] \caption{Specifications of the ViT and MLP-Mixer architectures used in this paper. We train all the architectures with image resolution $224\times 224$. } \label{tab:arch} \centering \resizebox{.99\textwidth}{!}{ \begin{tabular}{l|ccccccccc} \toprule \textbf{Model} & \textbf{\#params} & \textbf{\tabincell{c}{Throughput \\ (img/sec/core)}} & \textbf{\tabincell{c}{Patch \\ Resolution}} & \textbf{\tabincell{c}{Sequence \\ Length}} & \textbf{Hidden Size} & \textbf{\#heads} & \textbf{\#layers} & \textbf{\tabincell{c}{Token MLP \\ Dimension}} & \textbf{\tabincell{c}{Channel MLP \\ Dimension}} \\ \midrule ViT-S/32 & 23M & 6888 & $32\times 32$ & 49 & 384 & 6 & 12 & -- & -- \\ ViT-S/16 & 22M & 2043 & $16\times 16$ & 196 & 384 & 6 & 12 & -- & -- \\ ViT-S/14 & 22M & 1234 & $14\times 14$ & 256 & 384 & 6 & 12 & -- & -- \\ ViT-S/8 & 22M & 333 & $8\times 8$ & 784 & 384 & 6 & 12 & -- & -- \\ ViT-B/32 & 88M & 2805 & $32\times 32$ & 49 & 768 & 12 & 12 & -- & -- \\ ViT-B/16 & 87M & 863 & $16\times 16$ & 196 & 768 & 12 & 12 & -- & -- \\ \midrule Mixer-S/32 & 19M & 11401 & $32\times 32$ & 49 & 512 & -- & 8 & 256 & 2048 \\ Mixer-S/16 & 18M & 4005 & $16\times 16$ & 196 & 512 & -- & 8 & 256 & 2048 \\ Mixer-S/8 & 20M & 1498 & $8\times 8$ & 784 & 512 & -- & 8 & 256 & 2048 \\ Mixer-B/32 & 60M & 4209 & $32\times 32$ & 49 & 768 & -- & 12 & 384 & 3072 \\ Mixer-B/16 & 59M & 1390 & $16\times 16$ & 196 & 768 & -- & 12 & 384 & 3072 \\ Mixer-B/8 & 64M & 466 & $8\times 8$ & 784 & 768 & -- & 12 & 384 & 3072 \\ \bottomrule \end{tabular}} \end{table} \begin{table} \caption{Hyperparameters for downstream tasks. All models are fine-tuned with $224\times 224$ resolution, a batch size of 512, cosine learning rate decay, no weight decay, and grad clipping at global norm 1. } \label{tab:finetune-details} \centering \resizebox{.7\textwidth}{!}{ \begin{tabular}{lccc} \toprule \textbf{Dataset} & \textbf{Total steps} & \textbf{Warmup steps} & \textbf{Base LR} \\ \midrule CIFAR-10 & 10K & 500 & \multirow{4}{*}{\{0.001, 0.003, 0.01, 0.03\}} \\ CIFAR-100 & 10K & 500 & \\ Flowers & 500 & 100 & \\ Pets & 500 & 100 & \\ \bottomrule \end{tabular}} \end{table} \begin{figure} \centering \subfigure{\includegraphics[width=0.4\linewidth]{fig/num-imagenet.png}}\quad\quad\quad\quad \subfigure{\includegraphics[width=0.4\linewidth]{fig/num-improve.png}} \caption{ ImageNet accuracy (\textbf{Left}) and improvement (\textbf{Right}) brought by SAM. } \label{fig:improve} \vspace{-10pt} \end{figure} \section{When SAM Meets Adversarial Training} \label{app:adversarial} Interestingly, SAM and adversarial training are both minimax problems except that SAM's inner maximization is with respect to the network weights, while the latter concerns about the input for defending contrived attack~\citep{madry2018towards, Wong2020Fast}. Moreover, similar to SAM, \citet{shafahi2019free} suggest that adversarial training can flatten and smooth the loss landscape. In light of these connections, we study ViTs and MLP-Mixers under the adversarial training framework~\citep{wu2020weight, madry2018towards}. We use the fast adversarial training~\citep{Wong2020Fast} (FGSM with random start) with the $l_\infty$ norm and maximum per-pixel change 2/255 during training. All the hyperparameters remain the same as the vanilla supervised training. When evaluating the adversarial robustness, we use the PGD attack~\citep{madry2018towards} with the same maximum per-pixel change 2/255. The total number of attack steps is 10, and the step size is 0.25/255. To incorporate SAM, we formulate a three-level objective: \begin{align} \min_w\ \max_{\epsilon \in \mathbb{S}_{sam}}\ \max_{\delta \in \mathbb{S}_{adv}} L_{train}(w+\epsilon, x+\delta, y), \end{align} where $\mathbb{S}_{sam}$ and $\mathbb{S}_{adv}$ denote the allowed perturbation norm balls for the model parameter $w$ and input image $x$, respectively. Note that we can simultaneously obtain the gradients for computing $\epsilon$ and $\delta$ by backpropagation only once. To lower the training cost, we use fast adversarial training~\citep{Wong2020Fast} with the $l_\infty$ norm for $\delta$, and the maximum per-pixel change is set as 2/255. Table~\ref{tab:adv} (see Appendices) evaluates the models' clean accuracy, real-world robustness, and adversarial robustness (under 10-step PGD attack~\citep{madry2018towards}). It is clear that the landscape smoothing significantly improves the convolution-free architectures for both clean and adversarial accuracy. However, we observe a slight accuracy decrease on clean images for ResNets despite gain for robustness. Similar to our previous observations, \textit{ViTs surpass similar-size ResNets when adversarially trained on ImageNet with Inception-style preprocessing for both clean accuracy and adversarial robustness.} \section{When SAM Meets Contrastive Learning} \label{app:contrastive} In addition to data augmentations and large-scale pre-training, another notable way of improving a neural model's generalization is (supervised) contrastive learning~\citep{chen2020simclr,He2020moco,caron2021emerging,khosla2020supcon}. We couple SAM with the supervised contrastive learning~\citep{khosla2020supcon} for 350 epochs, followed by fine-tuning the classification head by 90 epochs for both ViT-S/16 and ViT-B/16. We train ViTs under the supervised contrastive learning framework~\citep{khosla2020supcon}. We take the classification token output from the last layer as the encoded representation and retain the structures of the projection and classification heads~\citep{khosla2020supcon}. We employ a batch size 2048 without memory bank~\citep{He2020moco} and use AutoAugment~\citep{cubuk2019autoaugment} with strength 1.0 following~\citet{khosla2020supcon}. For the 350-epoch pretraining stage, the contrastive loss temperature is set as 0.1, and we use the LAMB optimizer~\citep{You2020Large} with learning rate $0.001\times \frac{\text{batch size}}{256}$ along with a cosine decay schedule. For the second stage, we train the classification head for 90 epochs via a RMSProp optimizer~\citep{Tieleman2012rmsprop} with base learning rate 0.05 and exponential decay. The weight decays are set as 0.3 and 1e-6 for the first and second stages, respectively. We use a small SAM perturbation strength $\rho=0.02$. Compared to the training procedure without SAM, we find considerable performance gain thanks to SAM's smoothing of the contrastive loss geometry, improving the ImageNet top-1 accuracy of ViT-S/16 from 77.0\% to 78.1\%, and ViT-B/16 from 77.4\% to 80.0\%. In comparison, the improvement on ResNet-152 is less significant (from 79.7\% to 80.0\% after using SAM). \section{When SAM Meets Transfer Learning} \label{app:downstream} We also study the role of smoothed loss geometry in transfer learning. We select four datasets to test ViTs and MLP-Mixers' transferabilities: CIFAR-10/100~\citep{Krizhevsky09learningmultiple}, Oxford-IIIT Pets~\citep{parkhi2012cats}, and Oxford Flowers-102~\citep{nilsback2008flower}. We use image resolution $224\times 224$ during fine-tuning on downstream tasks, other settings exactly follow~\citet{dosovitskiy2021an, tolstikhin2021mlpmixer} (see Table~\ref{tab:finetune-details}). Note that we do not employ SAM during fine-tuning. We perform a grid search over the base learning rates on small sub-splits of the training sets (10\% for Flowers and Pets, 2\% for CIFAR-10/100). After that, we fine-tune on the entire training sets and report the results on the respective test sets. For comparison, we also include ResNet-50-SAM and ResNet-152-SAM in the experiments. Table~\ref{tab:downstream} summarizes the results, which confirm that the enhanced models also perform better after fine-tuning and that MLP-Mixers gain the most from the sharpness-aware optimization. \begin{table} \caption{Accuracy on downstream tasks of the models pre-trained on ImageNet. SAM improves ViTs and MLP-Mixers' transferabilities. ViTs transfer better than ResNets of similar sizes.} \label{tab:downstream} \centering \resizebox{.99\textwidth}{!}{ \begin{tabular}{l|c|c|cc|cc|cc|cc} \toprule \textbf{\%} & \tabincell{c}{ResNet-\\50-SAM} & \tabincell{c}{ResNet-\\152-SAM} & ViT-S/16 & \tabincell{c}{ViT-S/16-\\SAM} & ViT-B/16 & \tabincell{c}{ViT-B/16-\\SAM} & Mixer-S/16 & \tabincell{c}{Mixer-S/16-\\SAM} & Mixer-B/16 & \tabincell{c}{Mixer-B/16-\\SAM} \\ \midrule \textbf{CIFAR-10} & 97.4 & 98.2 & 97.6 & 98.2 & 98.1 & 98.6 & 94.1 & 96.1 & 95.4 & 97.8 \\ \textbf{CIFAR-100} & 85.2 & 87.8 & 85.7 & 87.6 & 87.6 & 89.1 & 77.9 & 82.4 & 80.0 & 86.4 \\ \textbf{Flowers} & 90.0 & 91.1 & 86.4 & 91.5 & 88.5 & 91.8 & 83.3 & 87.9 & 82.8 & 90.0 \\ \textbf{Pets} & 91.6 & 93.3 & 90.4 & 92.9 & 91.9 & 93.1 & 86.1 & 88.7 & 86.1 & 92.5 \\ \midrule \textbf{Average} & 91.1 & 92.6 & 90.0 & 92.6 & 91.5 & 93.2 & 85.4 & 88.8 & 86.1 & 91.7 \\ \bottomrule \end{tabular}} \vspace{-5pt} \end{table} \section{Visualization} \label{app:vis} \subsection{Loss landscape} We use the ``filter normalization'' method~\citep{li2018visualize} to visualize the loss function curvature in Figure~\ref{fig:land} and~\ref{fig:land-aug}. For a fair comparison, we use the cross-entropy loss when plotting the landscapes for all architectures, although the original training objective is the sigmoid loss for ViTs and MLP-Mixers. Note that their sigmoid loss geometry is even sharper. We equally sample 2,500 points on the 2D projection space and compute the losses using 10\% of the ImageNet training images~\citep{chen2020simclr}, i.e., the i1k~(1/10) subset in the main text to save computation. \begin{figure} \centering \subfigure[ViT]{\includegraphics[width=0.22\linewidth]{fig/ViT-B-32-softmax.png}} \quad \subfigure[ViT-SAM]{\includegraphics[width=0.22\linewidth]{fig/ViT-B-32-SAM-softmax.png}} \quad \subfigure[ViT-AUG]{\includegraphics[width=0.22\linewidth]{fig/ViT-B-16-softmax.png}} \quad \subfigure[ViT-21k]{\includegraphics[width=0.22\linewidth]{fig/ViT-B-32-21k-softmax.png}} \caption{Cross-entropy loss landscapes of ViT-B/16, ViT-B/16-SAM, ViT-B/16-AUG, and ViT-B/16-21k. Strong augmentations and large-scale pre-training can also smooth the curvature. } \vspace{-5pt} \label{fig:land-aug} \end{figure} \begin{table}[!ht] \caption{The SAM perturbation strength $\rho$ for training on ImageNet. ViTs and MLP-Mixers favor larger $\rho$ than ResNets does. Larger models with longer patch sequences need stronger strengths. } \label{tab:rho} \centering \resizebox{.5\textwidth}{!}{ \begin{tabular}{l|cc} \toprule \textbf{Model} & \textbf{Task} & \textbf{SAM $\rho$} \\ \midrule \midrule \multicolumn{3}{c}{ResNet} \\ \midrule ResNet-50-SAM & supervised & 0.02 \\ ResNet-101-SAM & supervised & 0.05 \\ ResNet-152-SAM & supervised & 0.02 \\ ResNet-50x2-SAM & supervised & 0.05 \\ ResNet-101x2-SAM & supervised & 0.05 \\ ResNet-152x2-SAM & supervised & 0.05 \\ ResNet-50-SAM & adversarial & 0.05 \\ ResNet-101-SAM & adversarial & 0.05 \\ ResNet-152-SAM & adversarial & 0.05 \\ \midrule \multicolumn{3}{c}{ViT} \\ \midrule ViT-S/32-SAM & supervised & 0.05 \\ ViT-S/16-SAM & supervised & 0.1 \\ ViT-S/14-SAM & supervised & 0.1 \\ ViT-S/8-SAM & supervised & 0.15 \\ ViT-B/32-SAM & supervised & 0.15 \\ ViT-B/16-SAM & supervised & 0.2 \\ ViT-B/16-AUG-SAM & supervised & 0.05 \\ ViT-S/16-SAM & adversarial & 0.1 \\ ViT-B/32-SAM & adversarial & 0.1 \\ ViT-B/16-SAM & adversarial & 0.1 \\ ViT-S/16-SAM & supervised contrastive & 0.02 \\ ViT-B/16-SAM & supervised contrastive & 0.02 \\ \midrule \multicolumn{3}{c}{MLP-Mixer} \\ \midrule Mixer-S/32-SAM & supervised & 0.1 \\ Mixer-S/16-SAM & supervised & 0.15 \\ Mixer-S/8-SAM & supervised & 0.2 \\ Mixer-B/32-SAM & supervised & 0.35 \\ Mixer-B/16-SAM & supervised & 0.6 \\ Mixer-B/8-SAM & supervised & 0.6 \\ Mixer-B/16-AUG-SAM & supervised & 0.2 \\ Mixer-S/16-SAM & adversarial & 0.05 \\ Mixer-B/32-SAM & adversarial & 0.25 \\ Mixer-B/16-SAM & adversarial & 0.25 \\ \bottomrule \end{tabular}} \end{table} \subsection{Attention map} The visualization of the ViT's attention maps (Figure~\ref{fig:attn} in the main text) follows~\citep{caron2021emerging}. We average the self-attention scores of the ``classification token'' from the last MSA layer to obtain a matrix $A\in \mathbb{R}^{H/P \times W/P}$, where $H$, $W$, $P$ are the image height, width, and the patch resolution, respectively. Then we upsample $A$ to the image shape $H\times W$ before generating the figure. \section{Hessian Eigenvalue} \label{app:hessian} The Hessian matrix requires second-order derivative, so we compute the Hessian (and all the sub-diagonal Hessian) $\lambda_{max}$ using 10\% of the ImageNet training images (i.e., i1k~(1/10)) via power iteration~\footnote{\url{https://en.wikipedia.org/wiki/Power_iteration}}, where we use 100 iterations to ensure its convergence. \section{NTK Condition Number} \label{app:ntk} We approximate the neural tangent kernel on the i1k (1/10) subset by averaging over block diagonal entries (with block size $48\times 48$) in the full NTK. Notice that the computation is based on the architecture at initialization without training. As the activation plays an important role when computing NTK --- we find that smoother activation functions enjoy smaller condition numbers, we replace the GELU in ViT and MLP-Mixer with ReLU for a fair comparison with ResNet. \section{Training Details} \label{app:details} We use image resolution $224\times 224$ during fine-tuning on downstream tasks, other settings exactly follow~\citep{dosovitskiy2021an, tolstikhin2021mlpmixer} (see Table~\ref{tab:finetune-details}). Note that we do not employ SAM during fine-tuning. We perform a grid search over the base learning rates on small sub-splits of the training sets (10\% for Flowers and Pets, 2\% for CIFAR-10/100). After that, we fine-tune on the entire training sets and report the results on the respective test sets. Except for the experiments in Section~\ref{sec:aug-sam} (SAM with strong data augmentations) and Appendix~\ref{app:contrastive} (contrastive learning), we train all the models from scratch on ImageNet with the basic Inception-style preprocessing~\citep{szegedy2016inception}, i.e., a random image crop and a horizontal flip with probability 50\%. Please see Table~\ref{tab:details} for the detailed training settings. We simply follow the original training settings of ResNet and ViT~\citep{alexander202bit, dosovitskiy2021an}. For MLP-Mixer, we remove the strong augmentations in its original training pipeline and perform a grid search over the learning rate in $\{0.003, 0.001\}$, weight decay in $\{0.3, 0.1, 0.03\}$, Dropout rate in $\{0.1, 0.0\}$, and stochastic depth in $\{0.1, 0.0\}$. Note that training for 90 epochs is enough for ResNets to converge, and longer schedule brings almost no effect. For all the experiments, we use 128 TPU-v3 cores (2 per chip), resulting in 32 images per core. The SAM computation for $\hat{\epsilon}$ is conducted on each core independently. \begin{table} \caption{Hyperparameters for training from scratch on ImageNet with basic Inception-style preprocessing and $224\times 224$ image resolution. } \label{tab:details} \centering \resizebox{.65\textwidth}{!}{ \begin{tabular}{l|ccc} \toprule & \textbf{ResNet} & \textbf{ViT} & \textbf{MLP-Mixer} \\ \midrule Data augmentation & \multicolumn{3}{c}{Inception-style} \\ Input resolution & \multicolumn{3}{c}{$224\times 224$} \\ Batch size & \multicolumn{3}{c}{4,096} \\ Epoch & 90 & 300 & 300 \\ Warmup steps & 5K & 10K & 10K \\ Peak learning rate & $0.1\times \frac{\text{batch\ size}}{256}$ & 3e-3 & 3e-3 \\ Learning rate decay & cosine & cosine & linear \\ Optimizer & SGD & AdamW & AdamW \\ SGD Momentum & $0.9$ & -- & -- \\ Adam $(\beta_1, \beta_2)$ & -- & (0.9, 0.999) & (0.9, 0.999) \\ Weight decay & 1e-3 & 0.3 & 0.3 \\ Dropout rate & 0.0 & 0.1 & 0.0 \\ Stochastic depth & -- & -- & 0.1 \\ Gradient clipping & -- & 1.0 & 1.0 \\ \bottomrule \end{tabular}} \end{table} \begin{table} \caption{ImageNet top-1 accuracy (\%) of ViT-B/16 and Mixer-B/16 when trained from scratch with different perturbation strength $\rho$ in SAM. } \label{tab:rho-vary} \centering \resizebox{.8\textwidth}{!}{ \begin{tabular}{l|cccccccccc} \toprule SAM $\rho$ & 0.0 & 0.05 & 0.1 & 0.2 & 0.25 & 0.35 & 0.4 & 0.5 & 0.6 & 0.65 \\ \midrule ViT-B/16 & 74.6 & 77.5 & 78.8 & \textbf{79.9} & 79.3 & -- & -- & -- & -- & -- \\ Mixer-B/16 & 66.4 & 69.5 & -- & -- & 74.1 & 74.7 & 75.6 & 76.9 & \textbf{77.4} & 77.1 \\ \bottomrule \end{tabular}} \end{table} \subsection{Perturbation strength in SAM} Different architecture species favor different strengths of perturbation $\rho$. We perform a grid search over $\rho$ and report the best results --- Table~\ref{tab:rho} reports the corresponding strengths used in our ImageNet experiments. Besides, we show the results when varying $\rho$ in Table~\ref{tab:rho-vary}. Similar to~\citep{foret2021sharpnessaware}, we also find that a relative small $\rho \in [0.02, 0.05]$ works the best for ResNets. However, larger $\rho$ gives rise to the best results for ViTs and MLP-Mixers. We also observe that architectures with larger capacities and longer input sequences prefer stronger perturbation strengths. Interestingly, the choice of $\rho$ coincides with our previous observations. Since MLP-Mixers suffer the sharpest landscapes, they need the largest perturbation strength. As strong augmentations and contrastive learning already improve generalization, the suitable $\rho$ becomes significantly smaller. Note that we do not re-tune any other hyperparameters when using SAM. \subsection{Training on ImageNet subsets} In Section~\ref{sec:scale}, we train the models on ImageNet subsets, and the hyperparameters have to be adjusted accordingly. We simply change the batch size to maintain similar total iterations and keep all other settings the same, i.e., 2048 for i1k (1/2), 1024 for i1k (1/4), and 512 for i1k (1/10). We do not scale the learning rate as we find the scaling harms the performance. \subsection{Training with strong augmentations} We tune the learning rate and regularization when using strong augmentations (mixup with probability 0.5, RandAugment with two layers and magnitude 15) in Section~\ref{sec:aug-sam} following~\citep{tolstikhin2021mlpmixer}. For ViT, we use 1e-3 peak learning rate, 0.1 weight decay, 0.1 Dropout, and 0.1 stochastic depth; For MLP-Mixer, those hyperparameters are exactly the same as~\citep{tolstikhin2021mlpmixer}, peak learning rate as 1e-3, weight decay as 0.1, Dropout as 0.0, and stochastic depth as 0.1. Other settings are unchanged (Table~\ref{tab:details}). \section{Longer Schedule of Vanilla SGD} \label{app:longer} Since SAM needs another forward and backward propagation to compute $\hat{\epsilon}$, its training overhead is~$\sim 2\times$ of the vanilla baseline. We also experiment with $2\times$ schedule vanilla training (600 epochs). We observe that training longer brings no effect on both clean accuracy and robustness, indicating that the current 300 training epochs for ViTs and MLP-Mixers are enough for them to converge. \section{Varying Weight Decay Strangth} \label{app:decay} \begin{table}[!h] \caption{ImageNet accuracy and curvature analysis for ViT-B/16 when we vary the weight decay strength in Adam (AdamW).} \label{tab:decay} \centering \resizebox{.8\textwidth}{!}{ \begin{tabular}{l|c|ccccccccc} \toprule \textbf{Model} & \textbf{Weight decay} & \textbf{ImageNet (\%)} & $\|w\|_2$ & ${L}_{train}$ & ${L}_{train}^\mathcal{N}$ & $\lambda_{max}$ \\ \midrule \multirow{4}{*}{ViT-B/16} & 0.2 & 74.2 & 339.8 & 0.51 & 4.22 & 507.4 \\ & 0.3 & 74.6 & 269.3 & 0.65 & 6.66 & 738.8 \\ & 0.4 & 74.7 & 236.7 & 0.77 & 7.08 & 1548.9 \\ & 0.5 & 74.4 & 211.8 & 0.98 & 7.21 & 2251.7 \\ \midrule \multirow{4}{*}{ViT-B/16-SAM} & 0.2 & 79.9 & 461.4 & 0.69 & 0.72 & 13.1 \\ & 0.3 & 79.9 & 353.8 & 0.82 & 0.96 & 20.9 \\ & 0.4 & 79.4 & 301.1 & 0.85 & 0.98 & 26.1 \\ & 0.5 & 78.7 & 259.6 & 0.95 & 1.33 & 45.5 \\ \bottomrule \end{tabular}} \end{table} In this section, we vary the strength of weight decay and see the effects of this commonly used regularization approach. As shown in Table~\ref{tab:decay}, weight decay helps improve the accuracy on ImageNet when training without SAM, the weight norm also decreases when we enlarge the decay strength as expected. However, enlarging the weight decay aggravates the problem of converging to a sharper region measured by both ${L}_{train}^\mathcal{N}$ and $\lambda_{max}$. Another observation is that $\|w\|_2$ consistently increases after applying SAM for every weight decay strength in Table~\ref{tab:decay}, together with the improved ImageNet accuracy and smoother landscape curvature. \section{Introduction} Transformers~\citep{vaswani2017attention} have become the de-facto model of choice in natural language processing (NLP)~\citep{devlin2018bert,gpt}. In computer vision, there has recently been a surge of interest in end-to-end Transformers~\citep{dosovitskiy2021an,touvron2021training,liu2021swin,fan2021multiscale,arnab2021vivit,bertasius2021space,akbari2021vatt} and MLPs~\citep{tolstikhin2021mlpmixer,touvron2021resmlp,liu2021pay,melas2021you}, prompting the efforts to replace hand-wired features or inductive biases with general-purpose neural architectures powered by data-driven training. We envision these efforts may lead to a unified knowledge base that produces versatile representations for different data modalities, simplifying the inference and deployment of deep learning models in various application scenarios. Despite the appealing potential of moving toward general-purpose neural architectures, the lack of convolution-like inductive biases also challenges the training of vision Transformers (ViTs) and MLPs. When trained on ImageNet~\citep{deng2009imagenet} with the conventional Inception-style data preprocessing~\citep{szegedy2016inception}, Transformers \textit{``yield modest accuracies of a few percentage points below ResNets of comparable size''}~\citep{dosovitskiy2021an}. To boost the performance, existing works resort to large-scale pre-training~\citep{dosovitskiy2021an,arnab2021vivit,akbari2021vatt} and repeated strong data augmentations~\citep{touvron2021training}, resulting in excessive demands of data, computing, and sophisticated tuning of many hyperparameters. For instance, Dosovitskiy et al.~\citep{dosovitskiy2021an} pre-train ViTs using 304M labeled images, and~\citet{touvron2021training} repeatedly stack four strong image augmentations. In this paper, we show ViTs can outperform ResNets~\citep{he2016resnet} of even bigger sizes in both accuracy and various forms of robustness by using a principled optimizer, without the need for large-scale pre-training or strong data augmentations. MLP-Mixers~\citep{tolstikhin2021mlpmixer} also become on par with ResNets. We first study the architectures fully trained on ImageNet from the lens of loss landscapes and draw the following findings. First, visualization and Hessian matrices of the loss landscapes reveal that Transformers and MLP-Mixers converge at extremely sharp local minima, whose largest principal curvatures are almost an order of magnitude bigger than ResNets'. Such effect accumulates when the gradients backpropagate from the last layer to the first, and the initial embedding layer suffers the largest eigenvalue of the corresponding sub-diagonal Hessian. Second, the networks all have very small training errors, and MLP-Mixers are more prone to overfitting than ViTs of more parameters (because of the difference in self-attention). Third, ViTs and MLP-Mixers have worse ``trainabilities'' than ResNets following the neural tangent kernel analyses~\citep{pmlr-v119-xiao20b}. Therefore, we need improved learning algorithms to prevent the convergence to a sharp local minimum when it comes to the convolution-free ViTs and MLP-Mixers. The first-order optimizers (e.g., SGD and Adam~\citep{kingma2017adam}) only seek the model parameters that minimize the training error. They dismiss the higher-order information such as flatness that correlates with generalization~\citep{keskar2017largebatch, pmlr-v80-kleinberg18a, jastrzebski2018on, l.2018a, chaudhari2017entropysgd}. The above study and reasoning lead us to the recently proposed sharpness-aware minimizer (SAM)~\citep{foret2021sharpnessaware} that explicitly smooths the loss geometry during model training. SAM strives to find a solution whose entire neighborhood has low losses rather than focus on any singleton point. We show that the resultant models exhibit smoother loss landscapes, and their generalization capabilities improve tremendously across different tasks including supervised, adversarial, contrastive, and transfer learning (e.g., +5.3\% and +11.0\% top-1 accuracy on ImageNet for ViT-B/16 and Mixer-B/16, respectively, with the simple Inception-style preprocessing). The enhanced ViTs achieve better accuracy and robustness than ResNets of similar and bigger sizes when trained from scratch on ImageNet, without large-scale pre-training or strong data augmentations. Moreover, we demonstrate that SAM can even enable ViT to be effectively trained with (momentum) SGD, which usually lies far behind Adam when training Transformers~\citep{zhang2020why}. By analyzing some intrinsic model properties, we observe that SAM increases the sparsity of active neurons (especially for the first few layers), which contribute to the reduced Hessian eigenvalues. The weight norms increase, implying the commonly used weight decay may not be an effective regularization alone. A side observation is that, unlike ResNets and MLP-Mixers, ViTs have extremely sparse active neurons (see Figure~\ref{fig:loss-acc} (right)), revealing the potential for network pruning~\citep{akbari2021vatt}. Another interesting finding is that the improved ViTs appear to have visually more interpretable attention maps. Finally, we draw similarities between SAM and strong augmentations (e.g., mixup) in that they both smooth the average loss geometry and encourage the models to behave linearly between training images. \section{Background and Related Work} We briefly review ViTs, MLP-Mixers, and some related works in this section. \citet{dosovitskiy2021an} show that a pure Transformer architecture~\citep{vaswani2017attention} can achieve state-of-the-art accuracy on image classification by pre-training it on large datasets such as ImageNet-21k~\citep{deng2009imagenet} and JFT-300M~\citep{sun2017revisiting}. Their vision Transformer (ViT) is a stack of residual blocks, each containing a multi-head self-attention, layer normalization~\citep{layer-norm}, and a MLP layer. ViT first embeds an input image $x\in \mathbb{R}^{H\times W\times C}$ into a sequence of features $z\in \mathbb{R}^{N\times D}$ by applying a linear projection over $N$ nonoverlapping image patches $x_p \in \mathbb{R}^{N\times(P^2\cdot C)}$, where $D$ is the feature dimension, $P$ is the patch resolution, and $N=HW/P^2$ is the sequence length. The self-attention layers in ViT are global and do not possess the locality and translation equivariance of convolutions. ViT is compatible with the popular architectures in NLP~\citep{devlin2018bert,gpt} and, similar to its NLP counterparts, requires pre-training over massive datasets~\citep{dosovitskiy2021an,akbari2021vatt,arnab2021vivit} or strong data augmentations~\citep{touvron2021training}. Some works specialize the ViT architectures for visual data~\citep{liu2021swin,yuan2021tokenstotoken,fan2021multiscale,bertasius2021space}. More recent works find that the self-attention in ViT is not vital for performance, resulting in several architectures exclusively based on MLPs~\citep{tolstikhin2021mlpmixer,touvron2021resmlp,liu2021pay,melas2021you}. Here we take MLP-Mixer~\citep{tolstikhin2021mlpmixer} as an example. MLP-Mixer shares the same input layer as ViT; namely, it partitions an image into a sequence of nonoverlapping patches/tokens. It then alternates between token and channel MLPs, where the former allows feature fusion from different spatial locations. We focus on ViTs and MLP-Mixers in this paper. We denote by ``S'' and ``B'' the small and base model sizes, respectively, and by an integer the image patch resolution. For instance, ViT-B/16 is the base ViT model taking as input a sequence of $16\times16$ patches. Appendices contain more details. \begin{table} \caption{Number of parameters, NTK condition number $\kappa$, Hessian dominate eigenvalue $\lambda_{max}$, training error at convergence $L_{train}$, average flatness ${L}_{train}^\mathcal{N}$, accuracy on ImageNet, and accuracy/robustness on ImageNet-C. ViT and MLP-Mixer suffer divergent $\kappa$ and converge at sharp regions; SAM rescues that and leads to better generalization. } \label{tab:hessian} \centering \resizebox{.9\textwidth}{!}{ \begin{threeparttable} \begin{tabular}{l|cc|cc|cc} \toprule & ResNet-152 & \tabincell{c}{ResNet-152-\\SAM} & ViT-B/16 & \tabincell{c}{ViT-B/16-\\SAM} & Mixer-B/16 & \tabincell{c}{Mixer-B/16-\\SAM} \\ \midrule \textbf{\#Params} & \multicolumn{2}{c|}{60M} & \multicolumn{2}{c|}{87M} & \multicolumn{2}{c}{59M} \\ \textbf{NTK} $\bf{\kappa}$ \tnote{$\dagger$} & \multicolumn{2}{c|}{2801.6} & \multicolumn{2}{c|}{4205.3} & \multicolumn{2}{c}{14468.0} \\ \textbf{Hessian $\lambda_{max}$} & 179.8 & \textbf{42.0} & 738.8 & \textbf{20.9} & 1644.4 & \textbf{22.5} \\ \midrule $L_{train}$ & \textbf{0.86} & 0.90 & \textbf{0.65} & 0.82 & \textbf{0.45} & 0.97 \\ ${L}_{train}^\mathcal{N}$ \tnote{$\star$} & 2.39 & \textbf{2.16} & 6.66 & \textbf{0.96} & 7.78 & \textbf{1.01} \\ \midrule \textbf{ImageNet (\%)} & 78.5 & \textbf{79.3} & 74.6 & \textbf{79.9} & 66.4 & \textbf{77.4} \\ \textbf{ImageNet-C (\%)} & 50.0 & \textbf{52.2} & 46.6 & \textbf{56.5} & 33.8 & \textbf{48.8} \\ \bottomrule \end{tabular} \begin{tablenotes} \item[$\dagger$] As it is prohibitive to compute the exact NTK, we approximate the value by averaging over its sub-diagonal blocks (see Appendix~\ref{app:ntk} for details). We average the results for 1,000 random noises when calculating ${L}_{train}^\mathcal{N}$. \end{tablenotes} \end{threeparttable}} \vspace{-10pt} \end{table} \begin{figure} \centering \subfigure[ResNet]{\label{fig:land-resnet}\includegraphics[width=0.19\linewidth]{fig/R50.png}} \subfigure[ViT]{\label{fig:land-vit}\includegraphics[width=0.19\linewidth]{fig/ViT-B-32-softmax.png}} \subfigure[Mixer]{\label{fig:land-mixer}\includegraphics[width=0.19\linewidth]{fig/Mixer-B-32-softmax.png}} \subfigure[ViT-SAM]{\label{fig:land-vit-sam}\includegraphics[width=0.19\linewidth]{fig/ViT-B-32-SAM-softmax.png}} \subfigure[Mixer-SAM]{\label{fig:land-mixer-sam}\includegraphics[width=0.19\linewidth]{fig/Mixer-B-32-SAM-softmax.png}} \caption{Cross-entropy loss landscapes of ResNet-152, ViT-B/16, and Mixer-B/16. ViT and MLP-Mixer converge to sharper regions than ResNet when trained on ImageNet with the basic Inception-style preprocessing. SAM, a sharpness-aware optimizer, significantly smooths the landscapes. } \vspace{-15pt} \label{fig:land} \end{figure} \section{ViTs and MLP-Mixers Converge at Sharp Local Minima} The current training recipe of ViTs, MLP-Mixers, and related convolution-free architectures relies heavily on massive pre-training~\citep{dosovitskiy2021an,arnab2021vivit,akbari2021vatt} or a bag of strong data augmentations~\citep{touvron2021training,tolstikhin2021mlpmixer,cubuk2019autoaugment, cubuk2019randaugment, zhang2018mixup, yun2019cutmix}. It highly demands data and computing, and leads to many hyperparameters to tune. Existing works report that ViTs yield inferior accuracy to the ConvNets of similar size and throughput when trained from scratch on ImageNet without the combination of those advanced data augmentations, despite using various regularization techniques (e.g., large weight decay, Dropout~\citep{srivastava14dropout}, etc.). For instance, ViT-B/16~\citep{dosovitskiy2021an} gives rise to 74.6\% top-1 accuracy on the ImageNet validation set (224 image resolution), compared with 78.5\% of ResNet-152~\citep{he2016resnet}. Mixer-B/16~\citep{tolstikhin2021mlpmixer} performs even worse (66.4\%). There also exists a large gap between ViTs and ResNets in robustness tests (see Table~\ref{tab:compare} for details). Moreover, \citet{chen2021empirical} find that the gradients can spike and cause a sudden accuracy dip when training ViTs, and \citet{touvron2021training} report the training is sensitive to initialization and hyperparameters. These all point to optimization problems. In this paper, we investigate the loss landscapes of ViTs and MLP-Mixers to understand them from the optimization perspective, intending to reduce their dependency on the large-scale pre-training or strong data augmentations. \textbf{ViTs and MLP-Mixers converge at extremely sharp local minima.} It has been extensively studied that the convergence to a flat region whose curvature is small benefits the generalization of neural networks~\citep{keskar2017largebatch, pmlr-v80-kleinberg18a, jastrzebski2018on, pmlr-v119-chen20f, l.2018a, Zela2020Understanding, chaudhari2017entropysgd}. Following~\citet{li2018visualize}, we plot the loss landscapes at convergence when ResNets, ViTs, and MLP-Mixers are trained from scratch on ImageNet with the basic Inception-style preprocessing~\citep{szegedy2016inception} (see Appendices for details). As shown in~\Cref{fig:land-resnet,fig:land-vit,fig:land-mixer}, ViTs and MLP-Mixers converge at much sharper regions than ResNets. Besides, we calculate the training error under Gaussian perturbations on the model parameters ${L}_{train}^\mathcal{N} = \mathbb{E}_{\epsilon \sim \mathcal{N}}[L_{train}(w+\epsilon)]$ in Table~\ref{tab:hessian}, which reveals the \emph{average} flatness. Although ViT-B/16 and Mixer-B/16 achieve lower training error $L_{train}$ than that of ResNet-152, their loss values after random weight perturbation become much higher. We further validate the results by computing the dominate Hessian eigenvalue $\lambda_{max}$, which is a mathematical evaluation of the \emph{worst-case} landscape curvature. The $\lambda_{max}$ values of ViT and MLP-Mixer are orders of magnitude larger than that of ResNet, and MLP-Mixer suffers the largest curvature among the three species (see Section~\ref{sec:change} for a detailed analysis). \textbf{Small training errors.} This convergence at sharp regions coincides with the training dynamics shown in Figure~\ref{fig:loss-acc} (left). Although Mixer-B/16 has fewer parameters than ViT-B/16 (59M vs.\ 87M), it has a smaller training error (also see $L_{train}$ in Table~\ref{tab:hessian}) but much worse test accuracy, implying that using the cross-token MLP to learn the interplay across image patches is more prone to overfitting than ViTs' self-attention mechanism whose behavior is restricted by a softmax. To validate this statement, we simply remove the softmax in ViT-B/16, such that the query and key matrices can freely interact with each other. Although having lower $L_{train}$ (0.56 vs. 0.65), the obtained ViT-B/16-Free performs much worse than the original ViT-B/16 (70.5\% vs. 74.6\%). Its ${L}_{train}^\mathcal{N}$ and $\lambda_{max}$ are 7.01 and 1236.2, revealing that ViT-B/16-Free converges to a sharper region than ViT-B/16 (${L}_{train}^\mathcal{N}$ is 6.66 and $\lambda_{max}$ is 738.8) both on average and in the worst-case direction. Such a difference probably explains why it is easier for MLP-Mixers to get stuck in sharp local minima. \textbf{ViTs and MLP-Mixers have worse trainability.} Furthermore, we discover that ViTs and MLP-Mixers suffer poor trainabilities, defined as the effectiveness of a network to be optimized by gradient descent~\citep{pmlr-v119-xiao20b, burkholz2019init, shin2020trainability}. \citet{pmlr-v119-xiao20b} show that the trainability of a neural network can be characterized by the condition number of the associated neural tangent kernel (NTK), $\Theta(x, x') = J(x)J(x')^T$, where $J$ is the Jacobian matrix. Denoting by $\lambda_1 \geq \dots \geq \lambda_m$ the eigenvalues of NTK $\Theta_{train}$, the smallest eigenvalue $\lambda_m$ converges exponentially at a rate given by the condition number $\kappa=\lambda_1 / \lambda_m$. If $\kappa$ diverges then the network will become untrainable~\citep{pmlr-v119-xiao20b, chen2021neural}. As shown in Table~\ref{tab:hessian}, $\kappa$ is pretty stable for ResNets, echoing previous results that ResNets enjoy superior trainability regardless of the depth~\citep{yang2017mean, li2018visualize}. However, we observe that the condition number diverges when it comes to ViT and MLP-Mixer, confirming that the training of ViTs desires extra care~\citep{chen2021empirical,touvron2021training}. \begin{figure} \centering \subfigure{\includegraphics[width=0.31\linewidth]{fig/iteration-loss-acc.png}}\quad \subfigure{\includegraphics[width=0.31\linewidth]{fig/iteration-loss-acc-vit.png}}\quad \subfigure{\includegraphics[width=0.31\linewidth]{fig/layer-activate-full.png}} \vspace{-5pt} \caption{ \textbf{Left} and \textbf{Middle}: ImageNet training error and validation accuracy vs.\ iteration for ViTs and MLP-Mixers. \textbf{Right}: Percentage of active neurons for ResNet-152, ViT-B/16, and Mixer-B/16. } \vspace{-10pt} \label{fig:loss-acc} \end{figure} \section{A Principled Optimizer for Convolution-Free Architectures} The commonly used first-order optimizers (e.g., SGD~\citep{Nesterov1983AMF}, Adam~\citep{kingma2017adam}) only seek to minimize the training loss $L_{train}(w)$. They usually dismiss the higher-order information such as curvature that correlates with the generalization~\citep{keskar2017largebatch, chaudhari2017entropysgd, dziugaite2017computing}. However, the objective $L_{train}$ for deep neural networks are highly non-convex, making it easy to reach near-zero training error but high generalization error $L_{test}$ during evaluation, let alone their robustness when the test sets have different distributions~\citep{hendrycks2019benchmarking, hendrycks2020faces}. ViTs and MLPs amplify such drawbacks of first-order optimizers due to the lack of inductive bias for visual data, resulting in excessively sharp loss landscapes and poor generalization, as shown in the previous section. We hypothesize that smoothing the loss landscapes at convergence can significantly improve the generalization ability of those convolution-free architectures, leading us to the recently proposed sharpness-aware minimizer (SAM)~\citep{foret2021sharpnessaware} that explicitly avoids sharp minima. \subsection{SAM: Overview} Intuitively, SAM~\citep{foret2021sharpnessaware} seeks to find the parameter $w$ whose entire neighbours have low training loss $L_{train}$ by formulating a minimax objective: \begin{align} \min_w\ \max_{\|\epsilon\|_2\leq \rho} L_{train}(w+\epsilon), \end{align} where $\rho$ is the size of the neighbourhood ball. Without loss of generality, here we use $l_2$ norm for its strong empirical results~\citep{foret2021sharpnessaware} and omit the regularization term for simplicity. Since the exact solution of the inner maximization $\epsilon^\star = \argmax_{\|\epsilon\|_2\leq \rho}L_{train}(w+\epsilon)$ is hard to obtain, they employ an efficient first-order approximation: \begin{align} \hat{\epsilon}(w) = \argmax_{\|\epsilon\|_2\leq\rho}L_{train}(w) + \epsilon^T\nabla_w L_{train}(w) = \rho\nabla_wL_{train}(w)/\|\nabla_wL_{train}(w)\|_2. \end{align} Under the $l_2$ norm, $\hat{\epsilon}(w)$ is simply a scaled gradient of the current weight $w$. After computing $\hat{\epsilon}$, SAM updates $w$ based on the sharpness-aware gradient $\nabla_wL_{train}(w)|_{w+\hat{\epsilon}(w)}$. \subsection{Sharpness-aware optimization improves ViTs and MLP-Mixers} We train ViTs and MLP-Mixers with no large-scale pre-training or strong data augmentations. We directly apply SAM to the original ImageNet training pipeline of ViTs~\citep{dosovitskiy2021an} without changing any hyperparameters. The pipeline employs the basic Inception-style preprocessing~\citep{szegedy2016inception}. The original training setup of MLP-Mixers~\citep{tolstikhin2021mlpmixer} includes a combination of strong data augmentations, and we replace it with the same Inception-style preprocessing for a fair comparison. Note that we perform grid search for the learning rate, weight decay, Dropout \emph{before} applying SAM. Please see Appendices for training details. \textbf{Smoother regions around the local minima.} Thanks to SAM, both ViTs and MLP-Mixers converge at much smoother regions, as shown in \Cref{fig:land-vit-sam,fig:land-mixer-sam}. Moreover, both the average and the worst-case curvature, i.e., ${L}_{train}^\mathcal{N}$ and $\lambda_{max}$, decrease dramatically (see Table~\ref{tab:hessian}). \textbf{Higher accuracy.} What comes along is tremendously improved generalization performance. On ImageNet, SAM boosts the top-1 accuracy of ViT-B/16 from 74.6\% to 79.9\%, and Mixer-B/16 from 66.4\% to 77.4\%. For comparison, the improvement on a similarly sized ResNet-152 is 0.8\%. Empirically, \textit{the degree of improvement negatively correlates with the constraints of inductive biases built into the architecture.} ResNets with inherent translation equivalence and locality benefit less from landscape smoothing than the attention-based ViTs. MLP-Mixers gain the most from the smoothed loss geometry. In Table~\ref{tab:hybrid}, we further train two hybrid models~\citep{dosovitskiy2021an} to validate this observation, where the Transformer takes the feature map extracted from a ResNet-50 as the input sequence. The improvement brought by SAM decreases after we introduce the convolution to ViT, for instance, +2.7\% for R50-B/16 compared to +5.3\% for ViT-B/16. Moreover, SAM brings larger improvements to the models of larger capacity (e.g., +4.1\% for Mixer-S/16 vs.\ +11.0\% for Mixer-B/16) and longer patch sequence (e.g., +2.1\% for ViT-S/32 vs.\ +5.3\% for ViT-S/8). Please see Table~\ref{tab:compare} for more results. SAM can be easily applied to common base optimizers. Besides Adam, we also apply SAM on top of the (momentum) SGD that usually performs much worse than Adam when training Transformers~\citep{zhang2020why}. As expected, we find that under the same training budget (300 epochs), the ViT-B/16 trained with SGD only achieves 71.5\% accuracy on ImageNet, whereas Adam achieves 74.6\%. Surprisingly, SGD + SAM can push the result to 79.1\%, which is a huge +7.6\% absolute improvement. Although Adam + SAM is still higher (79.9\%), their gap largely shrinks. \textbf{Better robustness.} We also evaluate the models' robustness using ImageNet-R~\citep{hendrycks2020faces} and ImageNet-C~\citep{hendrycks2019benchmarking} and find even bigger impacts of the smoothed loss landscapes. On ImageNet-C, which corrupts images by noise, bad weather, blur, etc., we report the average accuracy against 19 corruptions across five levels. As shown in Tables~\ref{tab:hessian}~and~\ref{tab:compare}, the accuracies of ViT-B/16 and Mixer-B/16 increase by 9.9\% and 15.0\% (which are 21.2\% and 44.4\% \emph{relative} improvements), after SAM smooths their converged local regions. In comparison, SAM improves the accuracy of ResNet-152 by 2.2\% (4.4\% \emph{relative} improvement). We can see that SAM enhances the robustness even more than the \emph{relative} clean accuracy improvements (7.1\%, 16.6\%, and 1.0\% for ViT-B/16, Mixer-B/16, and ResNet-152, respectively). \begin{table} \caption{Performance of ResNets, ViTs, and MLP-Mixers trained from scratch on ImageNet with SAM (improvement over the vanilla model is shown in the parentheses). We use the Inception-style preprocessing (with resolution 224) rather than a combination of strong data augmentations. } \label{tab:compare} \centering \resizebox{1.\textwidth}{!}{ \begin{tabular}{l|cc|ccc|cc} \toprule \textbf{Model} & \textbf{\#params} & \textbf{\tabincell{c}{Throughput \\ (img/sec/core)}} & \textbf{ImageNet} & \textbf{ReaL} & \textbf{V2} & \textbf{ImageNet-R} & \textbf{ImageNet-C} \\ \midrule \midrule \multicolumn{8}{c}{\textbf{ResNet}} \\ \midrule ResNet-50-SAM & 25M & 2161 & 76.7 (+0.7) & 83.1 (+0.7) & 64.6 (+1.0) & 23.3 (+1.1) & 46.5 (+1.9) \\ ResNet-101-SAM & 44M & 1334 & 78.6 (+0.8) & 84.8 (+0.9) & 66.7 (+1.4) & 25.9 (+1.5) & 51.3 (+2.8) \\ ResNet-152-SAM & 60M & 935 & 79.3 (+0.8) & 84.9 (+0.7) & 67.3 (+1.0) & 25.7 (+0.4) & 52.2 (+2.2) \\ ResNet-50x2-SAM & 98M & 891 & 79.6 (+1.5) & 85.3 (+1.6) & 67.5 (+1.7) & 26.0 (+2.9) & 50.7 (+3.9) \\ ResNet-101x2-SAM & 173M & 519 & 80.9 (+2.4) & 86.4 (+2.4) & 69.1 (+2.8) & 27.8 (+3.2) & 54.0 (+4.7) \\ ResNet-152x2-SAM & 236M & 356 & 81.1 (+1.8) & 86.4 (+1.9) & 69.6 (+2.3) & 28.1 (+2.8) & 55.0 (+4.2) \\ \midrule \multicolumn{8}{c}{\textbf{Vision Transformer}} \\ \midrule ViT-S/32-SAM & 23M & 6888 & 70.5 (+2.1) & 77.5 (+2.3) & 56.9 (+2.6) & 21.4 (+2.4) & 46.2 (+2.9) \\ ViT-S/16-SAM & 22M & 2043 & 78.1 (+3.7) & 84.1 (+3.7) & 65.6 (+3.9) & 24.7 (+4.7) & 53.0 (+6.5) \\ ViT-S/14-SAM & 22M & 1234 & 78.8 (+4.0) & 84.8 (+4.5) & 67.2 (+5.2) & 24.4 (+4.7) & 54.2 (+7.0) \\ ViT-S/8-SAM & 22M & 333 & 81.3 (+5.3) & 86.7 (+5.5) & 70.4 (+6.2) & 25.3 (+6.1) & 55.6 (+8.5) \\ ViT-B/32-SAM & 88M & 2805 & 73.6 (+4.1) & 80.3 (+5.1) & 60.0 (+4.7) & 24.0 (+4.1) & 50.7 (+6.7)\\ ViT-B/16-SAM & 87M & 863 & 79.9 (+5.3) & 85.2 (+5.4) & 67.5 (+6.2) & 26.4 (+6.3) & 56.5 (+9.9) \\ \midrule \multicolumn{8}{c}{\textbf{MLP-Mixer}} \\ \midrule Mixer-S/32-SAM & 19M & 11401 & 66.7 (+2.8) & 73.8 (+3.5) & 52.4 (+2.9) & 18.6 (+2.7) & 39.3 (+4.1) \\ Mixer-S/16-SAM & 18M & 4005 & 72.9 (+4.1) & 79.8 (+4.7) & 58.9 (+4.1) & 20.1 (+4.2) & 42.0 (+6.4) \\ Mixer-S/8-SAM & 20M & 1498 & 75.9 (+5.7) & 82.5 (+6.3) & 62.3 (+6.2) & 20.5 (+5.1) & 42.4 (+7.8) \\ Mixer-B/32-SAM & 60M & 4209 & 72.4 (+9.9) & 79.0 (+10.9) & 58.0 (+10.4) & 22.8 (+8.2) & 46.2 (12.4) \\ Mixer-B/16-SAM & 59M & 1390 & 77.4 (+11.0) & 83.5 (+11.4) & 63.9 (+13.1) & 24.7 (+10.2) & 48.8 (+15.0) \\ Mixer-B/8-SAM & 64M & 466 & 79.0 (+10.4) & 84.4 (+10.1) & 65.5 (+11.6) & 23.5 (+9.2) & 48.9 (+16.9) \\ \bottomrule \end{tabular}} \end{table} \subsection{ViTs outperform ResNets without pre-training or strong augmentations} \label{sec:outperform} \begin{wraptable}{r}{0.5\textwidth} \vspace{-4.5mm} \centering \caption{Accuracy and robustness of two hybrid architectures.} \resizebox{\linewidth}{!}{ \begin{tabular}{l|ccc} \toprule \textbf{Model} & \textbf{\#params} & \textbf{\tabincell{c}{ImageNet \\ (\%)}} & \textbf{\tabincell{c}{ImageNet-C \\ (\%)}} \\ \midrule R50-S/16 & \multirow{2}{*}{34M} & 79.8 & 53.4 \\ R50-S/16-SAM & & 81.0 (+1.2) & 57.2 (+3.8) \\ \midrule R50-B/16 & \multirow{2}{*}{99M} & 79.7 & 54.4 \\ R50-B/16-SAM & & 82.4 (+2.7) & 61.0 (+6.6) \\ \bottomrule \end{tabular}} \vspace{-3mm} \label{tab:hybrid} \end{wraptable} The performance of an architecture is often conflated with the training strategies~\citep{bello2021revisiting}, where data augmentations play a key role~\citep{cubuk2019autoaugment,cubuk2019randaugment,zhang2018mixup,xie2020advprop,chen2021robust}. However, the design of augmentations requires substantial domain expertise and may not translate between images and videos, for instance. Thanks to the principled sharpness-aware optimizer, we can remove the advanced augmentations and focus on the architectures themselves. When trained from scratch on ImageNet with SAM, \textit{ViTs outperform ResNets of similar and greater sizes (also comparable throughput at inference)} regarding both clean accuracy (on ImageNet~\citep{deng2009imagenet}, ImageNet-ReaL~\citep{imagenet-real}, and ImageNet V2~\citep{imagenet-v2}) and robustness (on ImageNet-R~\citep{hendrycks2020faces} and ImageNet-C~\citep{hendrycks2019benchmarking}). ViT-B/16 achieves 79.9\%, 26.4\%, and 56.6\% top-1 accuracy on ImageNet, ImageNet-R, and ImageNet-C, while the counterpart numbers for ResNet-152 are 79.3\%, 25.7\%, and 52.2\%, respectively (see Table~\ref{tab:compare}). The gaps between ViTs and ResNets are even wider for small architectures. ViT-S/16 outperforms a similarly sized ResNet-50 by 1.4\% on ImageNet, and 6.5\% on ImageNet-C. SAM also significantly improves MLP-Mixers' results. \subsection{Intrinsic changes after SAM} \label{sec:change} We take a deeper look into the models to understand how they intrinsically change to reduce the Hessian' eigenvalue $\lambda_{max}$ and what the changes imply in addition to the enhanced generalization. \textbf{Smoother loss landscapes for every network component.} In Table~\ref{tab:hessian-layerwise}, we break down the Hessian of the whole architecture into small diagonal blocks of Hessians concerning each set of parameters, attempting to analyze what specific components cause the blowing up of $\lambda_{max}$ in the models trained without SAM. We observe that shallower layers have larger Hessian eigenvalues $\lambda_{max}$, and the first linear embedding layer incurs the sharpest geometry. This agrees with the finding in~\citep{chen2021empirical} that spiking gradients happen early in the embedding layer. Additionally, the multi-head self-attention (MSA) in ViTs and the Token MLPs in MLP-Mixers, both of which mix information across spatial locations, have comparably lower $\lambda_{max}$ than the other network components. SAM consistently reduces the $\lambda_{max}$ of all network blocks. \begin{table} \caption{Dominant eigenvalue $\lambda_{max}$ of the sub-diagonal Hessians for different network components, and norm of the model parameter $w$ and the post-activation $a_k$ of block $k$. Each ViT block consists of a MSA and a MLP, and MLP-Mixer alternates between a token MLP a channel MLP. Shallower layers have larger $\lambda_{max}$. SAM smooths every component.} \label{tab:hessian-layerwise} \centering \resizebox{\textwidth}{!}{ \begin{tabular}{lccccccccccc} \toprule \multirow{2}{*}{\textbf{Model}} & \multicolumn{7}{c}{\textbf{$\lambda_{max}$ of diagonal blocks of Hessian}} & \multirow{2}{*}{${\|w\|_2}$} & \multirow{2}{*}{${\|a_1\|_2}$} & \multirow{2}{*}{${\|a_6\|_2}$} & \multirow{2}{*}{${\|a_{12}\|_2}$} \\ \cmidrule{2-8} & Embedding & \tabincell{c}{MSA/\\Token MLP} & \tabincell{c}{MLP/\\Channel MLP} & Block1 & Block6 & Block12 & Whole & & & & \\ \midrule ViT-B/16 & 300.4 & 179.8 & 281.4 & 44.4 & 32.4 & 26.9 & 738.8 & 269.3 & 104.9 & 104.3 & 138.1 \\ ViT-B/16-SAM & 3.8 & 8.5 & 9.6 & 1.7 & 1.7 & 1.5 & 20.9 & 353.8 & 117.0 & 120.3 & 97.2 \\ \midrule Mixer-B/16 & 1042.3 & 95.8 & 417.9 & 239.3 & 41.2 & 5.1 & 1644.4 & 197.6 & 96.7 & 135.1 & 74.9 \\ Mixer-B/16-SAM & 18.2 & 1.4 & 9.5 & 4.0 & 1.1 & 0.3 & 22.5 & 389.9 & 110.9 & 176.0 & 216.1 \\ \bottomrule \end{tabular}} \vspace{-5pt} \end{table} We can gain insights into the above findings by the recursive formulation of Hessian matrices for MLPs~\citep{aleksandar2017practical}. Let $h_k$ and $a_k$ be the pre-activation and post-activation values for layer $k$, respectively. They satisfy $h_k = W_k a_{k-1}$ and $a_k = f_k(h_k)$, where $W_k$ is the weight matrix and $f_k$ is the activation function (GELU~\citep{hendrycks2020gaussian} in MLP-Mixers). Here we omit the bias term for simplicity. The diagonal block of Hessian matrix $H_k$ with respect to $W_k$ can be recursively calculated as: \begin{align} H_k = (a_{k-1} a_{k-1}^T)\otimes \mathcal{H}_k, \quad \mathcal{H}_k = B_k W_{k+1}^T\mathcal{H}_{k+1}W_{k+1}B_k + D_k, \label{eq:hessian1} \\ B_k = \text{diag}(f'_k(h_k)),\qquad D_k = \text{diag}(f''_k(h_k)\frac{\partial L}{\partial a_k}), \label{eq:hessian3} \end{align} where $\otimes$ is the Kronecker product, $\mathcal{H}_k$ is the pre-activation Hessian for layer $k$, and $L$ is the objective function. Therefore, the Hessian norm accumulates as the recursive formulation backpropagates to shallow layers, explaining why the first block has much larger $\lambda_{max}$ than the last block in Table~\ref{tab:hessian-layerwise}. \textbf{Greater weight norms.} After applying SAM, we find that in most cases, the norm of the post-activation value $a_{k-1}$ and the weight $W_{k+1}$ become even bigger (see Table~\ref{tab:hessian-layerwise}), indicating that the commonly used weight decay may not effectively regularize ViTs and MLP-Mixers (see Appendix~\ref{app:decay} for further verification when we vary the weight decay strength). \textbf{Sparser active neurons in MLP-Mixers.} Given the recursive formulation \Cref{eq:hessian1}, we identify another intrinsic measure of MLP-Mixers that contribute to the Hessian: the number of activated neurons. Indeed, $B_k$ is determined by the activated neurons whose values are greater than zero, since the first-order derivative of GELU becomes much smaller when the input is negative. As a result, the number of active GELU neurons is directly connected to the Hessian norm. Figure~\ref{fig:loss-acc} (right) shows the proportion of activated neurons for each block, counted using 10\% of the ImageNet training set. We can see that SAM greatly reduces the proportion of activated neurons for the first few layers of the Mixer-B/16, pushing them to much sparser states. This result also suggests the potential redundancy of image patches. \begin{table} \caption{Data augmentations, SAM, and their combination applied to different model architectures trained on ImageNet and its subsets from scratch.} \label{tab:aug} \centering \resizebox{1.\textwidth}{!}{ \begin{tabular}{l|cccc|cccc|cccc} \toprule \multirow{3}{*}{\textbf{Dataset}} & \multicolumn{4}{c|}{\textbf{ResNet-152}} & \multicolumn{4}{c|}{\textbf{ViT-B/16}} & \multicolumn{4}{c}{\textbf{Mixer-B/16}} \\ & Vanilla & SAM & AUG & \tabincell{c}{SAM \\ + AUG} & Vanilla & SAM & AUG & \tabincell{c}{SAM \\ + AUG} & Vanilla & SAM & AUG & \tabincell{c}{SAM \\ + AUG} \\ \midrule ImageNet & 78.5 & 79.3 & 78.8 & 78.9 & 74.6 & 79.9 & 79.6 & 81.5 & 66.4 & 77.4 & 76.5 & 78.1 \\ \midrule i1k (1/2) & 74.2 & 75.6 & 75.1 & 75.5 & 64.9 & 75.4 & 73.1 & 75.8 & 53.9 & 71.0 & 70.4 & 73.1 \\ i1k (1/4) & 68.0 & 70.3 & 70.2 & 70.6 & 52.4 & 66.8 & 63.2 & 65.6 & 37.2 & 62.8 & 61.0 & 65.8 \\ i1k (1/10) & 54.6 & 57.1 & 59.2 & 59.5 & 32.8 & 46.1 & 38.5 & 45.7 & 21.0 & 43.5 & 43.0 & 51.0 \\ \bottomrule \end{tabular}} \vspace{-5pt} \end{table} \textbf{ViTs' active neurons are highly sparse.} Although~\Cref{eq:hessian1,eq:hessian3} only involve MLPs, we still observe a decrease of activated neurons in the first layer of ViTs (but not as significant as in MLP-Mixers). More interestingly, we find that the proportion of active neurons in ViT is much smaller than another two architectures --- given an input image, less than 10\% neurons have values greater than zero for most layers (see Figure~\ref{fig:loss-acc} (right)). In other words, ViTs offer a huge potential for network pruning. This sparsity may also explain why one Transformer can handle multi-modality signals (vision, text, and audio)~\citep{akbari2021vatt}. \begin{figure} \centering \subfigure{\includegraphics[width=0.07\linewidth]{fig/attn/8.png}} \subfigure{\includegraphics[width=0.07\linewidth]{fig/attn/1.png}} \subfigure{\includegraphics[width=0.07\linewidth]{fig/attn/2.png}} \quad \quad \quad \subfigure{\includegraphics[width=0.07\linewidth]{fig/attn/8-S16.png}} \subfigure{\includegraphics[width=0.07\linewidth]{fig/attn/1-S16.png}} \subfigure{\includegraphics[width=0.07\linewidth]{fig/attn/2-S16.png}} \quad \quad \quad \subfigure{\includegraphics[width=0.07\linewidth]{fig/attn/8-S16-SAM.png}} \subfigure{\includegraphics[width=0.07\linewidth]{fig/attn/1-S16-SAM.png}} \subfigure{\includegraphics[width=0.07\linewidth]{fig/attn/2-S16-SAM.png}} \\ \subfigure{\includegraphics[width=0.07\linewidth]{fig/attn/5.png}} \subfigure{\includegraphics[width=0.07\linewidth]{fig/attn/6.png}} \subfigure{\includegraphics[width=0.07\linewidth]{fig/attn/22.png}} \quad \quad \quad \subfigure{\includegraphics[width=0.07\linewidth]{fig/attn/5-S16.png}} \subfigure{\includegraphics[width=0.07\linewidth]{fig/attn/6-S16.png}} \subfigure{\includegraphics[width=0.07\linewidth]{fig/attn/22-S16.png}} \quad \quad \quad \subfigure{\includegraphics[width=0.07\linewidth]{fig/attn/5-S16-SAM.png}} \subfigure{\includegraphics[width=0.07\linewidth]{fig/attn/6-S16-SAM.png}} \subfigure{\includegraphics[width=0.07\linewidth]{fig/attn/22-S16-SAM.png}} \\ \subfigure{\includegraphics[width=0.07\linewidth]{fig/attn/18.png}} \subfigure{\includegraphics[width=0.07\linewidth]{fig/attn/20.png}} \subfigure{\includegraphics[width=0.07\linewidth]{fig/attn/21.png}} \quad \quad \quad \subfigure{\includegraphics[width=0.07\linewidth]{fig/attn/18-S16.png}} \subfigure{\includegraphics[width=0.07\linewidth]{fig/attn/20-S16.png}} \subfigure{\includegraphics[width=0.07\linewidth]{fig/attn/21-S16.png}} \quad \quad \quad \subfigure{\includegraphics[width=0.07\linewidth]{fig/attn/18-S16-SAM.png}} \subfigure{\includegraphics[width=0.07\linewidth]{fig/attn/20-S16-SAM.png}} \subfigure{\includegraphics[width=0.07\linewidth]{fig/attn/21-S16-SAM.png}} \\ \subfigure{\includegraphics[width=0.07\linewidth]{fig/attn/16.png}} \subfigure{\includegraphics[width=0.07\linewidth]{fig/attn/17.png}} \subfigure{\includegraphics[width=0.07\linewidth]{fig/attn/3.png}} \quad \quad \quad \subfigure{\includegraphics[width=0.07\linewidth]{fig/attn/16-S16.png}} \subfigure{\includegraphics[width=0.07\linewidth]{fig/attn/17-S16.png}} \subfigure{\includegraphics[width=0.07\linewidth]{fig/attn/3-S16.png}} \quad \quad \quad \subfigure{\includegraphics[width=0.07\linewidth]{fig/attn/16-S16-SAM.png}} \subfigure{\includegraphics[width=0.07\linewidth]{fig/attn/17-S16-SAM.png}} \subfigure{\includegraphics[width=0.07\linewidth]{fig/attn/3-S16-SAM.png}} \caption{Raw images (\textbf{Left}) and attention maps of ViT-S/16 with (\textbf{Right}) and without (\textbf{Middle}) sharpness-aware optimization.} \vspace{-15pt} \label{fig:attn} \end{figure} \textbf{Visually improved attention maps in ViTs.} We visualize ViT-S/16's attention map of the classification token averaged over the last multi-head attentions in Figure~\ref{fig:attn} following~\citet{caron2021emerging}. Interestingly, the ViT model optimized with SAM appears to possess visually improved attention map compared with the one trained via the vanilla AdamW optimizer. \subsection{SAM vs. strong augmentations} \label{sec:aug-sam} Previous sections show that SAM can improve the generalization (and robustness) of ViTs and MLP-Mixers. Meanwhile, another paradigm to train these models on ImageNet from scratch is to stack multiple strong augmentations~\citep{touvron2021training,touvron2021resmlp,tolstikhin2021mlpmixer}. Hence, it is interesting to study the differences and similarities between the models trained by SAM and by using strong data augmentations. For the augmentation experiments, we follow \citet{tolstikhin2021mlpmixer}'s pipeline that includes mixup~\citep{zhang2018mixup} and RandAugment~\citep{cubuk2019randaugment}. \textbf{Generalization.} Table~\ref{tab:aug} shows the results of strong data augmentation, SAM, and their combination on ImageNet. Each row corresponds to a training set of a different fraction of ImageNet-1k. SAM benefits ViT-B/16 and Mixer-B/16 more than the strong data augmentations, especially when the training set is small. For instance, when the training set contains only 1/10 of ImageNet training images, ViT-B/16-SAM outperforms ViT-B/16-AUG by 7.6\%. Apart from the improved validation accuracy, we also observe that both SAM and strong augmentations increase the training error (see Figure~\ref{fig:loss-acc} (Middle) and Table~\ref{tab:aug-sam}), indicating their regularization effects. However, they have distinct training dynamics as the loss curve for ViT-B/16-AUG is much nosier than ViT-B/16-SAM. \begin{wraptable}{r}{0.49\textwidth} \vspace{-4.5mm} \centering \caption{Comparison between ViT-B/16-SAM and ViT-B/16-AUG. $R$ denotes the missing rate under linear interpolation.} \resizebox{\linewidth}{!}{ \begin{tabular}{lcccc} \toprule \textbf{Model} & $\lambda_{max}$ & $L_{train}$ & ${L}_{train}^\mathcal{N}$ & $R(\downarrow)$ \\ \midrule ViT-B/16 & 738.8 & 0.65 & 6.66 & 57.9\% \\ ViT-B/16-SAM & 20.9 & 0.82 & 0.96 & 39.6\% \\ ViT-B/16-AUG & 1659.3 & 0.85 & 1.23 & 21.4\% \\ \bottomrule \end{tabular}} \vspace{-3mm} \label{tab:aug-sam} \end{wraptable} \textbf{Sharpness at convergence.} Another intriguing question is as follows. Can augmentations also smooth the loss geometry similarly to SAM? To answer it, we also plot the landscape of ViT-B/16-AUG (see Figure~\ref{fig:land-aug} in the Appendix) and compute its Hessian $\lambda_{max}$ together with the average flatness ${L}_{train}^\mathcal{N}$ in Table~\ref{tab:aug-sam}. Surprisingly, strong augmentations even enlarge the $\lambda_{max}$. However, like SAM, augmentations make ViT-B/16-AUG smoother and achieve a significantly smaller training error under random Gaussian perturbations than ViT-B/16. These results show that both SAM and augmentations make the loss landscape flat \emph{on average}. The difference is that SAM enforces the smoothness by reducing the largest curvature via a minimax formulation to optimize the \emph{worst-case} scenario, while augmentations ignore the worse-case curvature and instead smooth the landscape over the directions induced by the augmentations. Interestingly, besides the similarity in smoothing the loss curvature on average, we also discover that SAM-trained models possess ``linearality'' resembling the property manually injected by the mixup augmentation. Following~\citet{zhang2018mixup}, we compute the prediction error in-between training data in Table~\ref{tab:aug-sam}, where a prediction $y$ is counted as a miss if it does not belong to $\{y_i, y_j\}$ evaluated at $x=0.5 x_i + 0.5 x_j$. We observe that SAM greatly reduces the missing rate ($R$) compared with the vanilla baseline, showing a similar effect to mixup that explicitly encourages such linearity. \section{Ablation Studies} In this section, we provide a more comprehensive study about SAM's effect on various vision models and under different training setups. We refer to~\Cref{app:adversarial,app:contrastive,app:downstream} for the adversarial, contrastive and transfer learning results. \subsection{When scaling the training set size} \label{sec:scale} Previous studies scale up training data to show massive pre-training trumps inductive biases~\citep{dosovitskiy2021an,tolstikhin2021mlpmixer}. Here we show SAM further enables ViTs and MLP-Mixers to handle small-scale training data well. We randomly sample 1/4 and 1/2 images from each ImageNet class to compose two smaller-scale training sets, i.e., i1k (1/4) and i1k (1/2) with 320,291 and 640,583 images, respectively. We also use ImageNet-21k to pre-train the models with SAM, followed by fine-tuning on ImageNet-1k without SAM. The ImageNet validation set remains intact. SAM can still bring improvement when pre-trained on ImageNet-21k (+0.3\%, +1.4\%, and 2.3\% for ResNet-152, ViT-B/16, and Mixer-B/16, respectively). As expected, fewer training examples amplify the drawback of ViTs and MLP-Mixers' lack of the convolutional inductive bias --- their accuracies decline much faster than ResNets' (see Figure~\ref{fig:improve} in the Appendix and the corresponding numbers in Table~\ref{tab:aug}). However, SAM can drastically rescue ViTs and MLP-Mixers' performance decrease on smaller training sets. Figure~\ref{fig:improve} (right) shows that \emph{the improvement brought by SAM over vanilla SGD training is proportional to the number of training images.} When trained on i1k (1/4), it boosts ViT-B/16 and Mixer-B/16 by 14.4\% and 25.6\%, escalating their results to 66.8\% and 62.8\%, respectively. It also tells that ViT-B/16-SAM matches the performance of ResNet-152-SAM even with only 1/2 ImageNet training data. \section{Conclusions and Limitations} \label{sec:conclusion} This paper presents a detailed analysis of the convolution-free ViTs and MLP-Mixers from the lens of the loss landscape geometry, intending to reduce the models' dependency on massive pre-training and/or strong data augmentations. We arrive at the sharpness-aware minimizer (SAM) after observing sharp local minima of the converged models. By explicitly regularizing the loss geometry through SAM, the models enjoy much flatter loss landscapes and improved generalization regarding accuracy and robustness. The resultant ViT models outperform ResNets of comparable size and throughput when learned with no pre-training or strong augmentations. Further investigation reveals that the smoothed loss landscapes attribute to much sparser activated neurons in the first few layers. Last but not least, we discover that SAM and strong augmentations share certain similarities to enhance the generalization. They both smooth the average loss curvature and encourage linearity. Despite achieving better generalization, training ViTs with SAM has the following limitations which could lead to potential future work. First, SAM incurs another round of forward and backward propagations to update $\epsilon$, which will lead to around 2x computational cost per update. Second, we notice that the effect of SAM diminishes as the training dataset becomes larger, so it is vital to develop learning algorithms that can improve/accelerate the large-scale pre-training process. \section*{Ethics Statement} We are not aware of any immediate ethical issues in our work. We hope this paper can provide new insights into the convolution-free neural architectures and their interplay with optimizers, hence benefiting future developments of advanced neural architectures that are efficient in data and computation. Possible negative societal impacts mainly hinge on the applications of convolution-free architectures, whose societal effects may translate to this work. \section*{Acknowledgement} This work is partially supported by NSF under IIS-1901527, IIS-2008173, IIS-2048280 and by Army Research Laboratory under agreement number W911NF-20-2-0158. \section*{Reproducibility Statement} We provide comprehensive experimental details and references to existing works and codebases to ensure reproducibility. The specification of all the architectures used in this paper is available in Appendix~\ref{app:architecture}. The instructions for plotting the landscape and the attention map are detailed in Appendix~\ref{app:vis}. We also present our approach to approximating Hessian's dominant eigenvalue $\lambda_{max}$ and the NTK condition number in \Cref{app:hessian,app:ntk}, respectively. Finally, Appendix~\ref{app:details} describes all the necessary training configurations, data augmentations, and SAM hyperparameters to ensure the reproducibility of our results.
{'timestamp': '2022-03-15T01:28:30', 'yymm': '2106', 'arxiv_id': '2106.01548', 'language': 'en', 'url': 'https://arxiv.org/abs/2106.01548'}
arxiv
\section{Introduction} Understanding the emotions partners feel during and after conflict interactions is important because of its long-term effects on couples’ relationship quality and stability \cite{Gottman1994}. Happy couples, for example, experience more positive and less negative emotions during conflict interactions compared to unhappy couples \cite{Levenson1994}. The current study focuses on one fundamental aspect of the conflict mechanism — how the emotional experience \textit{within} each partner is influenced by the behavioral exchange \textit{between} partners. A crucial aspect of conflict interaction in couples is how the behavioral exchange makes each person feel during and after the interaction \cite{Ruef2007}. But although both partners experience the same interaction, they can feel very differently about it. For example, if we assume that partner A shows contempt and criticizes partner B, we can assume that partner A might feel angry or superior whereas partner B might feel hurt or humiliated. Thus, the experience can be very different for the partner who communicates something compared to the partner who perceives it \cite{Butler2011}. This differentiation allows us to reflect on another mechanism, namely that the emotions a person experiences are the results of two kinds of influences. Obviously, a person’s emotional experience is constantly influenced by a partner's behavior as a kind of co-regulating force, talk turn by talk turn. In addition, however, each person has the ability to regulate one’s own emotional response (e.g., cognitive appraisal, emotion regulation) \cite{Gross2014}, which then affects one's own subsequent behavioral response. Thus, what partners experience emotionally during and at the end of a conflict interaction is a reflection of the co-regulation and self-regulation processes \cite{Boker2006}. To better understand emotions in couples and their impact on relationships, often self-report assessments are used in which each partner is asked to provide a rating of their own emotions right after an interaction, or partners are asked to watch a video recording of the interaction and provide continuous ratings using a joystick, for example, \cite{Ruef2007, Hilpert2020}. Self-reports are burdensome to complete and may not be collected frequently. This means that the relationship between behavior and emotions cannot be studied often. Thus, an automatic emotion recognition system would allow scaling of couples research. Various works have used linguistic features (i.e., \textit{what} has been said) and paralinguistic features (i.e., \textit{how} it was said) to predict the emotions of each partner in couples interactions more broadly \cite{black2010, lee2010, black2013, lee2014, xia2015, li2016, chakravarthula2015, tseng2016, tseng2017, chakravarthula2018, tseng2018} and in conflict interactions in particular \cite{Chakravarthula2019, boateng2020a}. Most of these works have used observer ratings (perceived emotions) as labels rather than self-reports (one’s actual emotions). Hence, the prediction task becomes that of recognizing external individuals’ perception of each partner’s emotion rather than each partner’s emotion per their own assessment. Though similar, the latter is more challenging than the former for a number of reasons. First, the rating might be biased and may not reflect their actual emotions over the period the rating is for (e.g., the past 5 minutes). Whereas for observer ratings, coders are generally trained over several weeks, it is done by more than one person and various approaches are employed to resolve ratings that are not in agreement and ensure the validity of the labels. Second, the self-reported emotion may not be reflected in that partner’s behavior in comparison to observer ratings which are purely based on behavioral observation. Despite these challenges, insights from psychology research could be leveraged to make the prediction task easier. Specifically, given that partners’ behaviors influence each other’s emotions in conflict interaction, the behavior of both partners could be considered to better predict each partner’s end-of-conversation emotion. However, it is yet to be investigated how doing so compares to using each partner’s own behavior only in terms of emotion prediction performance. In this work, we used a dataset collected from 368 couples who were recorded during an 8-minute conflict interaction, extracted linguistic and paralinguistic features, and used machine learning approaches to predict how each partner felt directly after the conflict interaction (self-reported emotion). We answer the following research questions (RQs) \textbf{RQ1:} \textit{How well can the end-of-conversation emotion of each partner be predicted by their own behavior — a combination of linguistic and paralinguistic data? (self-regulation)} \textbf{RQ2:} \textit{How does the prediction performance change when including the other partner’s behavior — (a) linguistic only, (b) paralinguistic only, and (c) combination of linguistic and paralinguistic data? (co-regulation) } Our contributions are (1) an evaluation of how well a partner’s own linguistic and paralinguistic features predict one’s own end-of-conversation emotion (2) an investigation of how the prediction performance changes when including one’s partner’s features (linguistic, paralinguistic, and both) (3) the use of a unique dataset — spontaneous, real-life, speech data collected from German-speaking, Swiss couples (n=368 couples, N=736 participants), which is the largest ever such dataset used in the literature for automatic recognition of partners’ end-of-conversation emotion. The insights from our work would advance the use of methods to automatically recognize the emotions of each partner which could enable research and applications to better understand couples’ relationships in therapy and the real world. The rest of the paper is organized as follows: In Section 2, we describe our data collection, preprocessing and feature extraction, in Section 3, we describe our experiments and evaluation, in Section 4 we present and discuss our results, in Section 5, we present limitations and future work, and we conclude in Section 6. \section{Methodology} \subsection{Data Collection and Preprocessing} This work used data from a larger dyadic interaction laboratory project conducted at the premises of the University of Zurich, Switzerland over 10 years with 368 heterosexual German-speaking, Swiss couples (N=736 participants; age 20-80) \cite{Kuster2015, uzh2020}. The inclusion criterion was to have been in the current relationship for at least 1 year. Couples had to choose one problematic topic for the conflict interaction from a list of common problems, and participants were then videotaped as they discussed the selected issue for 8 minutes. The data used in this work had one interaction from each couple and consequently, 368 8-minute interactions. After each conversation, each partner provided self-reported responses to the Multidimensional Mood questionnaire \cite{steyer1997} of their emotions on four bipolar dimensions — namely “good mood versus bad mood,” “relaxed versus angry,” “happy versus sad” and “calm versus stressed” — with the scale: 1 — very much, 2 — much, 3 — a little, 4 — a little, 5 — much, 6 — very much. In this work, we sort to focus on predicting emotional valence (positive or negative) based on Russell’s circumplex model of emotions \cite{Russell1980}. Hence, we used an average of the “good mood versus bad mood” and “happy versus sad” scales which enables us to get a more valid score since several dimensions that measure similar constructs are combined. We did not use the other two scales because their polarity also could represent the arousal dimension of emotion (low vs high arousal). We then binarized the averaged values similar to prior works (e.g., \cite{boateng2020a, black2010}) such that values greater than or equal to 3.5 were negative (0) and the rest were positive (1). Binarization enables us to map the data into Russell’s circumplex model of emotions which has 4 quadrants for emotions, further enabling its real-world utility — easily being able to tell which group of emotions are being felt by each partner using binarized valence and arousal dimensions. The speech data were manually annotated with the start and end of each speaker’s turn, along with pauses and noise. This was necessary in order to later be able to extract linguistic and paralinguistic features for each partner separately. In addition, speech content of both partners was manually transcribed for each partner separately and stored in 15-second chunks. Given that Swiss German is mostly spoken with different dialects across Switzerland, the spoken words were written as the corresponding German word equivalent. Some couples requested their data to be removed and some data were missing due to technical problems in data collection. Of the original 368 couples that took part in the study, we could use 338 samples for females (46 negative labels) and 341 samples for males (32 negative labels). The distribution highlights a significant class imbalance that is characteristic of real-world datasets and partners’ emotions as seen in other similar works (e.g., \cite{boateng2020a}). \subsection{Linguistic Features} We extracted linguistic features from the transcripts of the whole 8-minute interaction using a pre-trained model — Sentence-BERT (SBERT) \cite{Reimers2019}. Sentence-BERT is a modification of the BERT architecture with siamese and triplet networks to compute sentence embeddings such that semantically similar sentences are close in vector space. Sentence-BERT has been shown to outperform the mean and CLS token outputs of regular BERT models for semantic similarity and sentiment classification tasks. Given that the text is in German, we used the German BERT model \cite{germanbert} as SBERT’s Transformer model and the mean pooling setting. The German BERT model was pre-trained using the German Wikipedia dump, the OpenLegalData dump, and German news articles. The extraction resulted in a 768-dimensional feature vector. \subsection{Paralinguistic Features} We extracted acoustic features from the voice recordings. First, we used the speaker annotations to get the acoustic signal for each gender separately. Next, we used openSMILE \cite{Eyben2015} to extract the 88 eGeMAPS acoustic features which have been shown to be a minimalist set of features for affective recognition tasks \cite{Eyben2010}. The features are extracted in 25 ms sequences and then various functions (e.g., mean, median, range, etc.) are computed over the sequences resulting in 88 features for the whole 8-minute audio. The original audio was encoded with 2 channels. As a result, we extracted the features for each channel resulting in a 176-dimensional feature vector. \subsection{Multimodal and Dyadic Feature Fusion} Given that emotions are reflected in what and how people say things, we performed multimodal fusion (early fusion) by concatenating the linguistic and paralinguistic features resulting in a 944-dimensional feature. We did this separately for each partner. This feature vector was used as the baseline approach to answer research question (1). Additionally, we fused features from both partners to answer research question (2). Specifically, for partner A, we concatenated their multimodal feature vector with the features of partner B and used it to predict partner A’s emotion label. This process was done for partner B as well. In order to investigate which behavioral data of the interacting partner was most important in the prediction of the emotions, we included the features in the following order (1) linguistic only, (2) paralinguistic only, and (3) multimodal fusion of both. Consequently, we had four feature sets: (1) Multimodal fusion (baseline — own features), (2) Multimodal + Dyadic Fusion (with partner’s linguistic only), (2) Multimodal + Dyadic Fusion (with partner’s paralinguistic features only) (4) Multimodal + Dyadic Fusion (with partner’s combined linguistic and paralinguistic only). These were passed to machine learning models to answer the two research questions. \section{Experiments and Evaluation} We run experiments using scikit-learn \cite{Pedregosa2011} the following machine learning models: support vector machine (SVM) algorithm with linear and radial basis function kernel, and random forests. We trained models to perform binary classification of each partner's self-reported positive and negative emotion using different feature sets. We used the four feature sets described in the previous section. To train and evaluate the models, we used nested K-fold cross-validation (CV). The nested procedure consisted of utilising an “inner” run of 5-fold CV for hyperparameter tuning, followed by an “outer” run of 10-fold CV which utilizes the best values for each hyperparameter found by the “inner” run. We prevented data from the same couple from being in both the train and test folds, thereby evaluating the model’s performance on data from unseen couples. As the data was imbalanced, we used the metric balanced accuracy which is the unweighted average of the recall of each class and confusion matrices for evaluation. We used the “balanced” hyperparameter for all the models to mitigate the class imbalance while training. We compare to a random baseline of 50\% balanced accuracy. \begin{table}[t] \caption{Prediction Results of the Best Models for the Fusion Approaches } \label{tab:results} \begin{tabular}{|l|c|c|} \hline \textbf{Approach} & \multicolumn{2}{c|}{\textbf{\begin{tabular}[c]{@{}c@{}}Balanced \\ Accuracy (\%)\end{tabular}}} \\ \hline & \textbf{Male} & \textbf{Female} \\ \hline Multimodal fusion (baseline) & 49.8 & 59 \\ \hline \begin{tabular}[c]{@{}l@{}}Multimodal + Dyadic Fusion (with partner’s \\ combined linguistic and paralinguistic only)\end{tabular} & 52.3 & 63.2 \\ \hline \begin{tabular}[c]{@{}l@{}}Multimodal + Dyadic Fusion (with partner’s \\ linguistic features only)\end{tabular} & 53.5 & \textbf{64.8} \\ \hline \begin{tabular}[c]{@{}l@{}}Multimodal + Dyadic Fusion (with partner’s \\ paralinguistic only)\end{tabular} & \textbf{56.1} & 59.9 \\ \hline \end{tabular} \end{table} \section{Results and Discussion} Our results are shown in Table \ref{tab:results}. The baseline approach with multimodal fusion was not better than chance in predicting men’s emotions at the end of the conflict interaction (49.8\%). This is unexpected as this indicates that men’s own behaviors during the interaction are not related to how they feel at the end of the interaction. This might be due to self-regulation processes or not showing much emotions during the interaction. This is clearly different from women as their emotions can be predicted by their own behavior (59\%). Thus, it seems that women seem to express their emotions more clearly in their behavior. These results of poorer prediction performance for men compared to women is consistent with the results of \cite{boateng2020a}. Including features from the interacting partner improved the results for both men (52.3\%) and women (63.2\%). These results are consistent with psychology research that the behavior of partners’ have an effect on each other’s emotions in conflict interaction \cite{Gottman2014, Butler2011}. This is a crucial finding because (i) previous research shows that the behavior of one person influences the behavior of the other person \cite{Gottman1994} (ii) as well as that the emotional changes of one person affect the emotions of the other \cite{Butler2011}. However, this is the first study showing that behavioral features assessed during the conflict interaction can be used to predict one partner’s emotion at the end of the conversation. In addition, the improvement in women’s emotion prediction at the end of interaction is greater when including their partner’s linguistic data (64.8\%) whereas there is hardly any difference when including partner’s paralinguistic features. This is a surprising finding as women generally pay more attention to paralinguistic cues \cite{Gottman1992}. Notably, the results are different for men. The prediction for men’s emotions slightly increases when including their partner’s linguistic features but the prediction improves substantially when including women’s paralinguistic features. Although we do not know which specific paralinguistic features are the main drivers for predicting the emotions, this finding is in line with prior findings — when women “nag”, men experience strong negative physiologic reactions and tend to withdraw \cite{Gottman1992, Gottman1994}. Future research is needed to investigate which aspects of one partner’s behavior exactly cause their own emotion prediction performance to decline. In addition, these results have implications for the kind of behavioral information to consider to best predict each partner’s end-of-conversation emotions. We show the confusion matrices for the best models for the men and women in Figures \ref{fig:conf_mat_male} and \ref{fig:conf_mat_female} respectively. They reveal the models’ challenges at recognizing positive emotions (1), resulting in them being misclassified as negative emotions (0). \begin{figure}[t] \centering \includegraphics[width=0.6\linewidth]{rbf_acous_ling_acous_male_val.png} \caption{Confusion matrix for best performing model for male partners (Multimodal + Dyadic Fusion with partner’s linguistic features only)} \label{fig:conf_mat_male} \end{figure} \begin{figure}[t] \centering \includegraphics[width=0.6\linewidth]{linear_svc_acous_ling_ling_female_val.png} \caption{Confusion matrix for best performing model for female partners (Multimodal + Dyadic Fusion with partner’s paralinguistic features only) } \label{fig:conf_mat_female} \end{figure} \section{Limitations and Future Work} Further work is needed to investigate if these results are the same for couples in a different cultural context and also explore the effect of the interacting partners’ behavior at a more granular level such as on a talk-turn basis. More fine-grained emotion ratings may be needed to investigate that. Other fusion approaches like late fusion can be explored. We used BERT as a feature extractor in this work. Generating domain-specific sentence embeddings via fine-tuning the BERT model and exploring deep transfer learning models for the paralinguistic features may improve the results. BERT models have been shown to encode gender and racial bias because of the models they are trained on. Further investigations are needed in the future of potential biases in prediction \cite{bender2021}. Finally, we used manual annotations and transcripts. To accomplish true automatic emotion prediction, speaker annotations need to be done automatically and our approach needs to use and work for automated transcriptions. Current speech recognition systems do not work for this unique dataset given that couples speak Swiss German, which is (1) a spoken dialect and not written, and (2) varies across different parts of the German-speaking regions of Switzerland. Further work is needed to develop automatic speech recognition systems for Swiss German. \section{Conclusion} In this work, we investigated one’s own and the partner’s behavior in predicting end-of-conversation emotions in the context of conflict interactions in German-speaking Swiss couples. We extracted linguistic features using BERT and paralinguistic features using openSMILE. We fused both features in a multimodal approach for each partner. We also fused the features of both partners to predict the emotions of each partner. Our results show that including the behavior of the other partner improves the prediction performance. Furthermore, for men, considering \textit{how} their female partners spoke is most important, and for women considering \textit{what} their male partners said is most important in getting better prediction performance. These insights have implications for the behavioral information to (not) include to better predict each partner’s end-of-conversation emotions which will enable a better understanding of couples relations in research, therapy, and the real world. \begin{acks} Funding was provided by the Swiss National Science Foundation: CR12I1\_166348/1; CRSI11\_133004/1; P3P3P1\_174466; P300P1\_164582 \end{acks} \balance{} \bibliographystyle{ACM-Reference-Format}
{'timestamp': '2021-09-21T02:16:06', 'yymm': '2106', 'arxiv_id': '2106.01526', 'language': 'en', 'url': 'https://arxiv.org/abs/2106.01526'}
arxiv
\section{Introduction} The \textbf{SIR model} \cite{Kermack_McKendrick, Murray:1993, Daley_Gani, Brauer:2017, Martcheva2015a, Brauer_Castillo-Chavez_Feng}, developed by Kermack and McKendrick \cite{Kermack_McKendrick} in 1927, is the well known very simple model of infectious diseases that considers {\em three-compartments}, recalled here to state terminology and notations: \newline the compartment \textbf{S} of susceptible individuals; \newline the compartment \textbf{I} of the {\em infectious} (or {\em currently positive}) individuals, who have been infected and are capable of infecting susceptible individuals during the {\em infectious period}; \newline the compartment \textbf{R} of the {\em removed} individuals, who recovered from the disease or died from the disease, the former assumed to remain immune afterwards. \newline Births and non-epidemic-related deaths are neglected. \newline The cardinality of each of the compartments are indicated with the corresponding non bold letters, while $N$ denotes the involved total population at an initial time $t_0$: \begin{equation} S(t_0) + I(t_0) + R(t_0) = N\,. \label{N const} \end{equation} The disease {\it incidence rate} $\beta$ is defined so that $\beta\,S\,I$ gives the number of new infections per unit time \cite{Martcheva2015a}; the {\it removal rate} $\gamma$ is defined so that $\gamma\,I$ gives the rate at which infectious individuals “deactivate” (heal or die). Typically, experts adopt $\beta$ constant over time, which is not the general case, due to possible mutations of the decease carrier or social measures to counter the spread of the infection; also, to simplify mathematics, they adopt equations with null {\it generation time} $\mathfrak{g}$, that is the infector-infected pairing time lapse, as well as null {\it removal period} $\mathfrak{r}$, which is the average time between infection and recovery or death, despite the relation \begin{equation} \mathfrak{r} \,=\, \frac{1}{\gamma}\,. \label{removal pariod/rate} \end{equation} Within the removal period $\mathfrak{r}$, a typical infectious individual is expected to cause $\mathfrak{r}\,\beta\,S$ new infections, so defining a function of time that, normalized, is called {\em effective reproduction number} $\mathcal{R}_t $ (see for instance\cite{Hethcote2000}); namely: \begin{equation} \mathcal{R}_t \,=\, \mathfrak{r}\;\,\beta(t)\,\frac{S(t)}{N} \,=\, \frac{\beta(t)}{\gamma}\,\frac{S(t)}{N}\,. \label{reproduction number} \end{equation} \begin{comment} The {\em basic} reproduction number $\mathcal{R}_0$ \cite{Heesterbeek} is also defined, as the effective reproduction number at an initial time, when one infectious subject appears among an all-susceptible population (\cite{Edelstein-Keshet}, \cite{Hethcote2000}). \end{comment} \newline So, the SIR equations as used here become: \begin{subequations} \label{fond.eqs.} \begin{align} &\frac{dS}{dt}(t+\mathfrak{g}) = -\,\gamma\,\mathcal{R}_t\; I(t)\,, \label{fond.eqs.1}\\ &\frac{dI}{dt}(t+\mathfrak{g}) = \gamma\,\mathcal{R}_t\; I(t)\,-\,\gamma\; I(t+\mathfrak{g}-\mathfrak{r})\,, \label{fond.eqs.2}\\ &\frac{dR}{dt}(t+\mathfrak{r}) = \gamma\,I(t)\,. \label{fond.eqs.3} \end{align} \end{subequations} As well known, they imply that the sum \,$S+I+R$\, is conserved, so that \,$S(t)+I(t)+R(t) = N$\, at any time $t$. \section{Outlines of the work} Purpose of this work is to check whether the relations established in system \ref{fond.eqs.} are actually found in the data or, at least, whether ``corrections'', accounting for incomplete data or systematic errors, may or should be introduced, with the implication that consequently the relationships are satisfied. Crucial is the fact that the model is scale-invariant, thus allowing to conveniently choose as a reference one sub-compartmental curve whose real data can be considered reliable, such as the swab-confirmed infectious individuals. This choice is done indeed here: swab-confirmed infectious are mostly individuals who have developed symptoms and are actually found to cover a nearly constant fraction of all the infectious people, given the circumstances that symptomatic and a-symptomatic individuals roughly are respectively fractions of the age groups of over sixty and younger people (\cite{HiddenChall}\,, \cite{age1}\,, \cite{age2}\,, and \cite{age3}). \newline The case of the second through the third pandemic wave of Covid-19 in Italy is studied. First, it will be shown that the relation established through eq.~\ref{fond.eqs.3} holds true if $R(t)$ is scaled by a factor that is obtained together with the {\it removal period} $\mathfrak{r}$\, by a least-square procedure of matching over data. Arguments will be given for how a scaling-up could be due indeed over the official data. \newline Once $\mathfrak{r}$, and thus $\gamma$, are given, the {\em effective reproduction number} is obtained through eq.~\ref{fond.eqs.2}\,, reliably, despite using the swab-confirmed infection cases only, for that equation is scale-invariant on its own.\newline The transition to {\em ``true''} numbers is finally done, correcting the swab-confirmed infectious cases for the proportion factor of transmissions that likely occur from asymptomatic subjects. The results are compared with those obtained at the MRC Centre for Global Infectious Disease Analysis, Imperial College London (ICL,\, \cite{IC}), where a completely independent approach is used. \section{The data set} The data set is from Italy's Department of Protezione Civile \cite{DPCdata}, lasting from 1 June 2020 to 31 May 2021. Since every weekend there was a postponement in cases recording to a few days later, according to common practice the data is smoothed via a multi-day moving average; the choice is 9 days, to systematically include a couple of days after each weekend. \section{Swab-confirmed infectious towards daily removed curves} \label{h2h} Verifying that the relationship given by eq.~\ref{fond.eqs.3} is indeed found in the data is not so trivial. For example, there is evidence that the monthly deaths from Covid-19 in 2020, as given by Italy's Department of Protezione Civile, are largely underestimated: this is shown by an ISTAT study on the monthly excess of deaths in 2020, compared to the corresponding averages over the previous five years (see \cite{ISTATdeaths2020} and \cite{BLMMOPSZ}). ISTAT is Italy's Istituto Nazionale di Statistica. The matter is illustrated in fig.~\ref{deaths2020}. \begin{figure}[ht] \centering \includegraphics[width=0.90\textwidth]{death_2020.pdf} \caption{\footnotesize Monthly deaths from Covid-19 in Italy during 2020, according Italy's Department of Protezione Civile (blue histogram); monthly excess of deaths the same year compared to the averages over the previous five years, according Italy's ISTAT (Istituto Nazionale di Statistica) .} \label{deaths2020} \end{figure} In addition to this, it is to be expected that $R(t)$ does not include most of the cases that had an asymptomatic or mild course. Also, asymptomatic infected people are probably not reported among the infectious, whereas by far most of the reported infectious are those who had swabs confirmation, whose number will be called $I_{sc}$. Let's indicate with $\bcheck{R}$ the curve of the actually registered healed and deaths: it is found that its derivative, the daily variation, shifted forward in time, is indeed proportional to $I\sub{sc}(t)$. To methodically verify eq.~\ref{fond.eqs.2}\,, the correction factor $k\subs{rel}$ is introduced so as to give maximum generality to a least-square search over the positive definite form \begin{equation} \label{square form} \chi^2(k\subs{rel},\,\mathfrak{r}) \;=\; \sum_b\,\left[ I\sub{sc}(b)- k\subs{rel}\,\mathfrak{r}\, \frac{d\bcheck{R}}{dt}(b +\mathfrak{r})\right]^2\,, \end{equation} with varying $k\subs{rel}$ and the {\em removal period} $\mathfrak{r}$. It is worth remarking the notation $k\subs{rel}$, intended to emphasize that any correction on $\bcheck{R}(t)$, possibly {\em required} by the SIR model at this stage, is relative to the swab-confirmed infectious population only. The sum is over the days of the pandemic period considered, with the choice of weighing equally all daily data. The minimisation is performed using a C++ object of the class {\em Minimizer} of the CERN package ROOT, typically used by high energy physicist in their data analysis (\cite{ROOT}, \cite{Minimiser}): its statistical methodology is described in \cite{statsROOT}. Since the surface defined from the data through eq.~\ref{square form} is rather rough, the minimization algorithm is run 150,000 times to maximize the chance of hitting an optimal minimum: the initial values of $k\subs{rel}$ and $\mathfrak{r}$ are drawn at random in the intervals $[1.0,\,5.0 ]$ and $[5.0,\,18.0 ]$ respectively. Execution on raw and smoothed data takes about one minute time altogether. The final issue for $k\subs{rel}$ and $\mathfrak{r}$ and their uncertainties $\delta k\subs{rel}$ and $\delta \mathfrak{r}$ are taken as the mean and the standard deviation of the distributions of the respective outcomes at each iterated minimization, weighted with the normalized inverse of the $\chi^2$. \newline The results are shown on the first and the second lines of Table \ref{tab:table1}, for the raw and the smoothed data respectively. \begin{table}[ht!] \begin{center} \begin{tabular}{l|c|c|c|c|c} \hline \, & $k\subs{rel}$ & $\mathfrak{r}$ & $\chi^2$ & ndf & red.$\chi^2$ \\ \hline & & & & & \\ likelihood on raw data & $2.99 \pm 0.82$ & $10.31 \pm 2.74$ & $93185$ & $360$ & $266$ \\ likelihood on smoothed & $3.14 \pm 0.82$ & $10.32 \pm 2.68$ & $32823$ & $360$ & $91$ \\ Gaussian fit & & $ 9.78 \pm 2.28$ & $1.15$ & $32$ & $0.04$ \\ skew sigm. derivative & & $10.14 \pm 2.37$ & $2.48$ & $66$ & $0.04$ \\ \hline \end{tabular} \caption{k-factor and $\mathfrak{r}$} \label{tab:table1} \end{center} \end{table} \newline Since the value of the {\em removal period} $\mathfrak{r}$ is critical in determining $k\subs{rel}$, it is sought from the data in two further independent ways, as explained in the next two sub-sections. \subsection{The removal period from a Gaussian fit} At any new ``wave'' of epidemic, the rise in number of the infectious individuals follows with good \begin{figure}[ht!] \centering \includegraphics[width=0.90\textwidth]{GaussianFit.pdf} \caption{\footnotesize The two fitting Gaussian functions in cyan and green.} \label{GaussianFit} \end{figure} approximation a sigmoidal shape, i.e. it is roughly exponential at the very beginning, up to an inflection point, after which it bends towards a plateau; consequently, its daily variation (the time derivative) exhibits a maximum at the inflection point, around which it is approximately Gaussian. If eq.~\ref{fond.eqs.3} correctly described the data, an analogous shape should be had in the second derivative of the {\em removal curve}. Very remarkably, this is in fact the case, as shown in fig.~\ref{GaussianFit}\,, where fitting Gaussians are plotted over the first derivative of the {\em infectious curve} and the second derivative of the {\em removal curve}: the distance in time between the vertexes of the two Gaussians gives a new independent {\em measurement} of the {\em removal period} $\mathfrak{r}$, reported in the third line of Table \ref{tab:table1} with associated uncertainty and fit $\chi^2$. The uncertainty is the sum in quadrature of the uncertainty on the position in time of the vertexes of the two fitting Gaussians; the $\chi^2$, with its reduced, is their worse. The fit algorithm is from the already mentioned ROOT package (CERN, \cite{TFit}). \subsection{The removal period from the ``asymmetric sigmoid derivative'' fit} Given the almost sigmoidal initial growth of an epidemic wave, as already mentioned in the last sub-section, an alternative fit function turns to be an asymmetric modification of the derivative of a sigmoid, which will be called {\em skew sigmoid derivative}, namely: \begin{equation} \left\{ \begin{aligned} s(x;\,\mu,\,\sigma,\,\epsilon) \,&=\, \frac{1}{\epsilon + (1-\epsilon)\, e^{-(x - \mu)/\sigma}}\,, \qquad \text{with}\quad 0 \le \epsilon < 1 \,,\\ \mathscr{A}(x;\,\mu,\,\sigma,\,\epsilon) \, &= \, A\, s(x;\,\mu,\,\sigma,\,\epsilon)\, \left[ 2 - s(x;\,\mu,\,\sigma,\,\epsilon) \right] \,. \end{aligned} \right. \end{equation} \begin{figure}[ht!] \centering \includegraphics[width=0.60\textwidth]{SigSkDer.pdf} \caption{\footnotesize The {\em skew sigmoid derivative} for $\mu = 1.$,\, $\sigma = 1.$, $A = 1.$\,; $\epsilon = 0.45,\, 0.47,\, 0.49,\, 0.50,\, 0.53$.} \label{SigSkDer} \end{figure} This function has absolute maximum in $x = \mu$, with $\mathscr{A}(\mu;\,\mu,\,\sigma,\,\epsilon) = 1$. It is plotted in fig.~\ref{SigSkDer} for $\mu = 1$,\, $\sigma = 1$ and $A = 1$, and various values of the {\em skewness} parameter $\epsilon$\,: for $\epsilon = 0.5$ one has the derivative of a very sigmoid. The fits of the skew sigmoid derivative to the first derivative of the swab-confirmed {\em infectious curve} and to the the second derivative of the {\em removal curve} respectively are shown in fig.~\ref{asysigder}\,: again, the distance in time between the vertexes of the fitting functions gives a new {\em measurement} of the removal period $\mathfrak{r}$, reported in the fourth line of Table \ref{tab:table1}. \begin{figure}[ht!] \centering \includegraphics[width=1.00\textwidth]{asysigderFit.pdf} \caption {\footnotesize The two fitting ``asymmetric sigmoid derivative'' functions in cyan and green.} \label{asysigder} \end{figure} \subsection{The removal curve corrected relatively to the swab-confirmed infectious only} From Table \ref{tab:table1} the {\em removal period} $\mathfrak{r}$ is assumed to be $10 \pm 2$ days, bearing in mind that the data has just one day resolution; also, comparing the $\chi^2$ on the first and second lines of the table, the correction factor $k\subs{rel}$ is taken equal to $3.14 \pm 0.82$. So we have the the curve of the {\em removed} individuals, corrected relatively to the swab-confirmed infectious only, given by: \begin{equation} R\subs{rel}(t) \,=\, k\subs{rel} \, \bcheck{R}(t) \qquad \mathlarger{\backepsilon}\,' \qquad \frac{d R\subs{rel}}{dt}(t +\mathfrak{r}) \,=\, \gamma\, I\sub{sc}(t)\,. \label{rel corr} \end{equation} Fig.~\ref{scaledRemoved} does illustrate this: the cyan error bars are generated by the propagation of three times the $\pm 0.82$ uncertainty over $k\subs{rel}$\,. \begin{figure}[ht!] \centering. \includegraphics[width=1.0\textwidth]{scaledRemoved.pdf} \caption {\footnotesize Relation \ref{rel corr}\, in the data. The derivative of $R\subs{rel}(t)$ (blue marks) is time-shifted by the removal period $\mathfrak{r}$\,. The cyan error bars are given by propagation from three times $\pm 0.82$ uncertainty over $k\subs{rel}$.} \label{scaledRemoved} \end{figure} \section{The Effective Reproduction Number} There are several algorithms to estimate the {\em effective reproduction number} from the data: a simplified one is given in \cite{infn1}, where also an extensive bibliography on the subject can be found. The simplest yet effective estimate, that very directly interprets the meaning of the the function (see for instance \cite{Koch}), is given by \begin{equation} \mathcal{R}_t \,=\, \frac{I(t+\mathfrak{g})}{I(t)}\,. \label{simple Rt} \end{equation} As far as the SIR model is concerned, from eq.~\ref{fond.eqs.2}\, one has \begin{equation} \label{Rt discrete} \mathcal{R}_{t} \,=\, \frac{\mathfrak{r}}{I(t)}\, \frac{I(t+\mathfrak{g} +1)-I(t+\mathfrak{g}-1)}{2} \,+\, \frac{I(t+\mathfrak{g}-\mathfrak{r})}{I(t)}\,. \end{equation} So, the derivative is implemented by the symmetric difference quotient, to have the cancellation of the first-order error in the numerical discretization. \newline While only the {\em generation time} $\mathfrak{g}$ appears in eq.~\ref{simple Rt}, both $\mathfrak{g}$ and the {\em removal period} $\mathfrak{r}$ are present in eq.~\ref{Rt discrete}\,; consequently, the validity test of the SIR model through the {\em effective reproduction number} $\mathcal{R}_t$\,, it manages to provide, is to be considered quite stringent. \newline In the previous section the {\em removal period} $\mathfrak{r}$ was obtained from the data using the SIR model; the question is how to get the {\em generation time} as well. \begin{figure}[ht!] \centering. \includegraphics[width=1.0\textwidth]{Rt.pdf} \caption {\footnotesize $\mathcal{R}_t$ according to the SIR model, compared with the used simplest formula, eq.~\ref{simple Rt}\,. In cyan are the error bars for eq.~\ref{Rt discrete}\,; the other are in black. $\mathfrak{g} = 6 \pm 2$\,; $\mathfrak{r} = 10 \pm\,2$.} \label{Fig:Rt} \end{figure} \newline In our conventions, $I(t)$ denotes the total of all the infectious people, swab-confirmed or not. If $t\sub{M}$ is a day when $I(t)$ presents a maximum, then correspondingly, but $\mathfrak{g}$ days earlier, i.e. at day $t\sub{M} - \mathfrak{g}$\,, the {\em effective reproduction number} $\mathcal{R}_{t} $ should be equal to $1$, because an increase in the number of the people becoming infectious requires $\mathcal{R}_t > 1$ and a decrease requires $\mathcal{R}_t < 1$\,. Of course, every variation of $\mathcal{R}_t$ has impact on $I(t)$ with a delay of $\mathfrak{g}$ days, so also for $I\subs{sc}(t)$, assuming this to be proportional to $I(t)$\,. With $\mathfrak{r}$ fixed at $9.71 \pm 2$ days, as set out in the previous section, let's say $t\msub{\mathfrak{g}}$ a day when, for any given choice of $\mathfrak{g}$, $\mathcal{R}_t$ is equal to $1$: in general, checking over the data, it doesn't happen that the nearest next day $t\sub{M}$, on which $I\subs{sc}(t)$ has a maximum, is such that $t\sub{M} - t\msub{\mathfrak{g}} = \mathfrak{g}$, as it should; indeed it happens only for a specific choice of $\mathfrak{g}$, namely, for the case being studied, with $\mathfrak{g} = 6$, an integer value just in view of the one-day resolution of the data. A convenient double check is done on the maximum of $I\subs{sc}(t)$ falling on December 2, 2020 (see fig.~\ref{scaledRemoved}). Very remarkable is the fact that the height of the peaks of $\mathcal{R}_t$ does depend on the value one wants to give to $\mathfrak{g}$, the same way as the days when $\mathcal{R}_{t}$ is equal to $1$ do: so, all of these things are bounded by the SIR model, a fact that must be considered truly important in evaluating the validity of the model. \newline The estimate $\mathfrak{g} = 6$ days is in total agreement with the average $6.7 \pm 1.9$ days given for Italy in ref.\cite{Cereda et al}: this is a success of eq.~\ref{Rt discrete}\,, that strengthens the agreement, within the uncertainties, of the resulting $\mathcal{R}_{t}$ with that from other algorithms, as those reported in ref.\cite{infn1}\,, with references therein. Fig.~\ref{Fig:Rt} shows this SIR generated $\mathcal{R}_t$, together with the one from eq.~\ref{simple Rt}\,; for either, error bars corresponding to a $\pm 2$ days uncertainty on both $\mathfrak{g}$ and $\mathfrak{r}$\, are also shown. \section{The ``true'' numbers} \subsection{The ``corrected'' cumulative and daily-new infections relatively to the swab-confirmed infectious people} To avoid confusion, it is worth remarking that {\em infections at day t} is meant as the cumulative number of infections up to and including that day, while the number of {\em infectious people} at some day t refers to those people who were infected possibly earlier and are still able to transmit infection at that day. Thus, the daily new {\em infections curve} is different from the {\em infectious curve}. \newline Since $N$ in eq.~\ref{N const} is conserved, eq.~\ref{fond.eqs.1} can be written as \begin{equation} \frac{d (N - S)}{dt}(t+\mathfrak{g}) \;=\; \gamma\,\mathcal{R}_t\; I(t)\,, \label{total new infections} \end{equation} expressing the daily new infections, gross of {\em removed} people (while the {\em infectious} numbers are {\em net} of {\em removals}). Indeed \begin{equation} \mathcal{T}(t) \,=\, N - S(t) \,=\, I(t) + R(t) \label{total cases} \end{equation} is nothing but the total cases of infections at time $t$\,. \begin{figure}[ht!] \centering. \includegraphics[width=0.90\textwidth]{relTot.pdf} \caption {\footnotesize Italy, Covid-19 second through the third waves, estimates of {\em removal} (dark blue curve) and total (green curve) cases as from correction relative to the swab-confirmed infectious (red) curve. Also shown data in dark green (total cases) and blue ({\em removals})} \label{Fig:totalNewSIR} \end{figure} For what has been done so far, eq.~\ref{total new infections} must be replaced by \begin{subequations} \label{final relative} \begin{align} &\frac{d\,\mathcal{T}\sub{rel}}{d t}(t) \;=\; \gamma\,\mathcal{R}_t\; I\sub{sc}(t)\,, \label{rel new infections}\\ &\mathcal{T}\sub{rel}(t) \,=\, I\sub{sc}(t) + R\sub{rel}(t)\,, \label{rel total cases} \end{align} \end{subequations} giving the {\em corrected} cumulative number of infections relatively to the swab-confirmed infectious people only. Fig.~\ref{Fig:totalNewSIR} illustrates eq.s~\ref{final relative}\,. \subsection{Infections from a-symptomatic and symptomatic infectious people: estimate of the ``true'' numbers} There are several studies on the relevance of SARS-CoV-2 transmission from asymptomatic people, like \cite{AsymptInfected}, \cite{HiddenChall}, \cite{MagnAsympt}, \cite{infectiousness} and references therein. Quite recent and complete is ref. \cite{infectiousness}, where a decision analytical model is used to assess the proportion of SARS-CoV-2 transmissions in the community, likely occurring from subjects who did not develop any symptom. In that work data from a meta-analysis was used to set the {\em generation time} at a median of 5 days and {\em infectious period} at 10 days, in good agreement respectively with the 6 and 10 days stated in the present work. The reported conclusion is that, across a range of plausible scenarios, a $59\%$ of infection transmission occurs from persons without symptoms: no clear uncertainty is given, but the statement that the figure should be {\em at least} $50\%$, suggests an uncertainty of $\pm 10\,\%$. Also it is stated that the infected individuals who never develop symptoms are $75\%$ as infectious as those who do develop symptoms. \begin{figure}[ht!] \centering. \includegraphics[width=0.95\textwidth]{dailyNewSIR_absolute.pdf} \caption {\footnotesize Italy, Covid-19 second through the third waves. Estimates of daily new infections this work in blue and uncertainty belt in yellow; ICL's in dark red.} \label{Fig:dailyNewSIR} \end{figure} \newline Let's call $f\sub{(asy)}$ the percentage fraction of the asymptomatic infectious subjects over all the infectious people and $i\sub{(asy)}$ their relative infectiousness, that is the percentage fraction of the infectiousness of those who had developed symptoms: then, according to the best available figures, it would be $f\sub{(asy)} = 59 \pm 10\,\%$ and $i\sub{(asy)} = 75\%$, the latter with a trial, very conservative, uncertainty of $\pm 20\%$. \newline Denoting by $I\sub{(asy)}(t)$ the number of the asymptomatic infectious individuals and recalling that $I\sub{sc}(t)$ indicates the number of the the swab-confirmed infectious subjects, it should be \begin{equation} I(t) - I\sub{(sc)}(t) \quad=\quad I\sub{(asy)}(t) \quad=\quad \frac{f\sub{(asy)}}{100}\,\frac{i\sub{(asy)}}{100}\,I(t)\,, \nonumber \end{equation} whence \begin{subequations} \begin{align} &I(t) \,=\, \left(1 \,+\,\frac{f\sub{(asy)}}{100}\,\frac{i\sub{(asy)}}{100}\right)\,I\sub{(sc)}(t) \;=\vcentcolon\; k\sub{(ai)}\,I\sub{(sc)}(t) \,, \label{to_abs} \\ &R(t) \;=\; k\sub{(ai)}\,R\sub{rel}(t)\,, \label{Rtrue} \\ &k\sub{(ai)} \;\simeq\; 1 \,+\,\frac{f\sub{(asy)}}{100}\,\frac{i\sub{(asy)}}{100} \;\simeq\; 1.44 \,\pm\, 0.22 \,. \label{kai} \end{align} \end{subequations} Then, in view of eq.~\ref{total cases},\, eq.~\ref{total new infections} becomes \begin{equation} \frac{d\,\mathcal{T}}{dt}(t+\mathfrak{g}) \;=\; \gamma\;\mathcal{R}_t\; k\sub{ai}\, I\sub{sc}(t)\,, \label{totalNewInf} \end{equation} with $\mathcal{T}(t)$ the ``true'' cumulative number of infections at day $t$, while its derivative represents the ``true'' daily new infections.\newline Fig.~\ref{Fig:dailyNewSIR} shows the daily new infections curve, compared with the Imperial College's (ICL) model estimate, as published in \cite{ourworldindataICL}. The model in question is a stochastic SEIR variant, that adopts multiple infectious states, which in turn reflect different COVID-19 severities. It uses an estimate of the {\em infectious fatality rate} (IFR), assuming that the number of confirmed deaths from Covid-19 is equal to the {\em true} Covid-19 deaths number; it also uses an estimate of the {\em effective reproduction number}, based on the changes of the virus transmission rate caused by the average mobility trends. \newline So, the ICL model's approach is totally different from the one followed in the present work; nevertheless the respective ``true'' daily new infections estimates appear to be in quite good agreement, except on a time interval around 1 January 2021 (day 220 in plots of this paper), where the ICL curve shows a deep local minimum instead of a local maximum as in the data of Italy's Department of Protezione Civile. The uncertainty belt of the ICL estimates are surprisingly narrow. \begin{figure}[ht!] \centering. \includegraphics[width=0.90\textwidth]{total_true.pdf} \caption {\footnotesize This work estimates of the ``true'' total cases (light green) and correspondent data form Italy's Department of Protezione Civile (dark green) with scale on the left; this work ``true'' daily new infections (blue) and corresponding official data (dark blue) with scale on the right.} \label{Fig:total_true} \end{figure} In fig.~\ref{Fig:total_true} the present work's estimates of the ``true'' total cases of infections are shown, together with the estimated ``true'' daily new infections, the latter with their own scale on the right; also, the data as from Italy's Department of Protezione Civile are plotted. \newline Incidentally, the ripple visible in fig.~\ref{Fig:dailyNewSIR} and fig.~\ref{Fig:total_true} on the the data from Italy's Department of Civil Protection, has the typical 7-days periodicity that arises from the weekend reduced data recording. \section{Conclusions} Taking as case study the second to the third waves of SARS-CoV-2 in Italy, the SIR model is confronted with data, after reformulating its equations by the explicit introduction of the important {\em effective reproduction number} $\mathcal{R}_t$, as well as the {\em generation time} and the {\em infectious period}, usually, erroneously, neglected. The relationships it sets among the main observables are actually found in the data, in particular between the curve of the swab-confirmed infectious individuals and the curve of the {\em removed} (healed or deceased) subjects. Indeed, taking advantage of its scale invariance and choosing the curve of the swab-confirmed infectious people as a reference, the model suggests a correction on the number of {\em removed} individuals for just a factor which would take into account: a) infected people who have not developed relevant symptoms and, therefore, were not detected; b) deaths erroneously not attributed to Covid-19. {\em Generation time}, {\em infectious period} and {\em effective reproduction number} have been sought from the data through the model. At the very end, the curve of the swab-confirmed infectious individuals has been completed for the proportion of infection transmissions likely occurred from individuals with no symptoms, using figures published in important works ( \cite{AsymptInfected}, \cite{HiddenChall}, \cite{MagnAsympt}, \cite{infectiousness} ). Thus an estimate of the {\em ``true numbers''} of the pandemic in Italy is obtained for the considered period of time. All the results are in good agreement with those of other studies, in particular of the ICL group (\cite{IC}), whose approach is totally different from the present. The vision on and use of the SIR model of this work are new. \clearpage
{'timestamp': '2021-07-27T02:18:10', 'yymm': '2106', 'arxiv_id': '2106.01602', 'language': 'en', 'url': 'https://arxiv.org/abs/2106.01602'}
arxiv
\section{Introduction} Large-scare pre-trained language models (PLMs) such as BERT \citep{BERT}, GPT \citep{GPT} have significantly improved the performance of NLP tasks \citep{GPT2}. There is increasing evidence showing that PLMs contain world knowledge \citep{LMasKB, zhou2020evaluating, olmpics}. As a result, recent research considers generative PLMs such as T5 \citep{t5} and BART \citep{bart} for \textbf{Closed-book QA}, which has only question-answer pairs without external knowledge source. For example, after being finetuned on a few QA pairs, a generative LM can directly output \textit{``Florence''} after being given the question \textit{``Where was Dante born?''}. \citet{how-much} find that generative PLMs can store and use knowledge as they can achieve relatively high performance in closed-book QA task on three datasets. However, \citet{overlap} find that the excellent results are mainly due to high question/answer overlap rates between training and testing data. \begin{figure}[t] \center{ \includegraphics [width=7.7cm] {intro.png}} \caption{Process of generative PLMs for closed-book QA. (1) BART performs poorly on closed-book QA after QA finetuning; (2) We LM-finetune BART with related passages to feed knowledge and use a reciting task to evaluate how much knowledge the LM-finetuned model memorizes; (3) Though memorizing most needed knowledge, BART still faces challenge on closed-book QA after QA finetuning.} \label{intro_figure} \vspace{-2mm} \end{figure} Existing research leaves many open questions on the potential of generative pre-trained LMs on closed-book QA. For example, the used datasets consist of question-answer pairs only, and there is no mechanism to control what factual knowledge is already used to train a generative PLM before taking the closed-book questions. In addition, the high overlapping rates between training and testing questions and answers make it difficult to understand whether the answer that a model gives comes from its inherent knowledge or superficial cues in training data. To address these issues, we make a new benchmark of question-answer pairs from SQuAD \cite{SQuAD2}, where each question has a corresponding Wikipedia passage as a traceable knowledge source for pre-training. We find that despite giving around 25\% accuracy on existing test sets (i.e., WebQuestions and TriviaQA), BART gives only 1.5\% accuracy on the SQuAD dataset This result shows that there is still much challenge in using BART for closed-book QA directly. We further investigate the reason by separately examining whether BART can remember factual knowledge accurately, and whether it can make use of remembered knowledge to answer questions. The general process of investigating these two issues is presented in Figure~\ref{intro_figure}. For the first issue, we use related passages in SQuAD to further extra pre-train BART, which we call as \textbf{LM-finetuning}, and test the ratio of retained factual knowledge using a language modeling task, which we call as \textbf{reciting}. Results show that as the number of training passages grows, BART demonstrates severe issues of forgetting, losing track of exact facts in the LM task. For example, when the number of passage is around 500, BART can memorize 66\% needed knowledge. But when the number of passage increases to about 5000, the ratio becomes 4\%. For the second issue, we use versions of LM-finetuned BART that can retain the majority of factual knowledge for further QA finetuning, by constraining the number of passages. Although all the training and testing questions concern the passages in LM-finetuning, BART still fails to answer the majority of questions. This demonstrates difficulties in making use of internal knowledge for QA. In addition, further experiments show that QA finetuning can negatively influence the retained factual knowledge as measured using the original LM task. While reporting such challenges, we also find some promising directions by using simple data augmentation tricks. For example, simply adding related passages to test outputs can help BART retrieve relevant factual knowledge and give the correct answer. In addition, rather than treating QA finetuning in the same way as LM pre-training \cite{how-much}, decoupling the LM pre-training task and the QA finetuning tasks can also allow a model to better retain factual knowledge through the QA-finetuning task. \footnote{For future study, we have released the code and dataset at \url{https://github.com/wangcunxiang/Can-PLM-Serve-as-KB-for-CBQA}} \begin{table}[t] \centering \small \setlength{\tabcolsep}{1mm} \begin{tabular}{|c|c|c|c|} \hline & \makecell[c]{\textbf{Train Set}} & \makecell[c]{\textbf{Dev Set}} & \makecell[c]{\textbf{Test Set}} \\ \hline WebQuestions & 3778 & 1016 & 1016\\ \hline TriviaQA & 961091 & 4975 & 4976\\ \hline NaturalQuestions & 107369 & 900 & 900\\ \hline \multicolumn{4}{c}{\makecell{(a) The QA pairs of three datasets.}}\vspace{1mm}\\ \hline & \makecell[c]{\textbf{Train Set}} & \makecell[c]{\textbf{Dev Set}} & \makecell[c]{\textbf{Test Set}} \\ \hline SQuAD & 86396(19035) & 2968(602) & 2930(602)\\ \hline \multicolumn{4}{c}{\makecell{(b) The QA pairs and passages statistics of SQuAD. \\The numbers in () are the passage amounts.}}\\ \end{tabular} \caption{Details of each dataset after our processing. } \label{dataset_details} \end{table} \begin{table}[t] \centering \small \setlength{\tabcolsep}{1mm} \begin{tabular}{c|c|c|c|c} \hline \hline \textbf{Models $\backslash$ Dataset} & \makecell[c]{\textbf{SQuAD}} & \textbf{WB} & \textbf{TQ} & \textbf{NQ}\\ \hline \makecell[c]{original BART-Large \\$\rightarrow$ QA-finetune} & 1.5\% & 30.0\% & 24.9\% & 23.0\%\\ \hline \makecell[c]{original BART-Large \\$\rightarrow$ pre-trained with \\ all passages \\ $\rightarrow$ QA-finetune} & 1.8\% & - & - & -\\ \hline \end{tabular} \caption{ Closed-book QA performance of BART on four datasets. For SQuAD, only QA pairs are used in this experiments. WB, TQ and NQ means WebQuestions, TriviaQA and NaturalQuestions, respectively. } \vspace{-2mm} \label{closed-bookQA_on_4_datasets} \end{table} \begin{table}[t] \centering \small \setlength{\tabcolsep}{1mm} \begin{tabular}{c|c|c} \hline \hline \textbf{Dataset}$\backslash$\makecell{\textbf{Overlap Type}} & \makecell{\textbf{Answer} \textbf{Overlap}} & \textbf{Question Overlap} \\ \hline NaturalQuestions & 61.5\% & 32.5\%\\ \hline TriviaQA & 78.7\% & 33.6\%\\ \hline WebQuestions & 59.3\% & 27.5\%\\ \hline SQuAD & 24.0\% & 1.0\% \\ \hline \end{tabular} \caption{Question and Answer Overlaps on four datasets. Question overlaps data of NaturalQuestions, TriviaQA and WebQuestions are from \citet{overlap}; Answer overlaps on the three datasets are a bit different from \citet{overlap} because of our dataset pre-processing.} \vspace{-2mm} \label{dataset_overlap} \end{table} \begin{table}[t] \centering \small \setlength{\tabcolsep}{1mm} \begin{tabular}{c|c|c} \hline \hline \textbf{Dataset} $\backslash$ \textbf{Overlap Type} & \makecell[c]{\textbf{\bm{$O^{test}$} Overlap} \\ \textbf{with} \bm{$G^{train}$}} & \makecell[c]{\textbf{\bm{$G^{test}$} Overlap} \\ \textbf{with \bm{$G^{train}$}}} \\ \hline WebQuestions & 88.5\% & 59.3\%\\ \hline SQuAD & 39.8\% & 24.0\%\\ \hline \end{tabular} \caption{Overlap analysis between test outputs/golden answers and training answers. We select the top-performing results to analyze. } \vspace{-2mm} \label{output_overlap1} \end{table} \begin{table}[t] \centering \small \setlength{\tabcolsep}{1mm} \begin{tabular}{|c|c|c|} \hline & \makecell[c]{\ \ \textbf{Overlap}\ \ } & \makecell[c]{\textbf{Non-Overlap}} \\ \hline Correct & 29.8\% (604) & 0.2\% (5) \\ \hline Incorrect & 58.7\% (1189) & 11.3\% (228) \\ \hline \multicolumn{3}{c}{(a) On WebQuestions}\\ \hline & \makecell[c]{\ \ \textbf{Overlap}\ \ } & \makecell[c]{\textbf{Non-Overlap}} \\ \hline Correct & 1.3\% (77) & 0.1\% (6) \\ \hline Incorrect & 38.5\% (2272) & 60.1\% (3530) \\ \hline \multicolumn{3}{c}{(a) On SQuAD}\\ \end{tabular} \caption{Overlap analysis of test outputs on WebQuestions and SQuAD by BART. In the result cells, we present both percentages and case numbers. We select the top performing result to analyze. } \vspace{-2mm} \label{output_overlap2} \end{table} \section{Using SQuAD for Closed-book QA} \label{Closed-bookQA} In the closed-book QA task \citep{how-much}, a model needs to answer questions without external resources. Formally, the input is a question $q$, and the output is a sequence of tokens $o$. For evaluation, the correct golden answer $g$ will be compared with $o$. Previous work \citep{how-much} uses the Exact Match (EM) metric to score $o$ against $g$. We conduct closed-book QA by using the \textbf{BART} model \citep{bart} on four datasets-WebQuestions \citep{WebQuestions}, TriviaQA \citep{triviaqa}, NaturalQuestions \citep{NQ} and SQuAD2 \citep{SQuAD2}. BART is a transformer-based \citep{transformer} sequence-to-sequence generative PLM, which we choose because it has achieved several state-of-the-art results on generative tasks. We use the publicly released checkpoint BART-Large in this work.\footnote{\url{https://huggingface.co/facebook/bart-large/tree/main}} To use a generative PLM on each dataset, the model is first finetuned using the training question-answer pairs. We call this process as {\bf QA-finetuning}. While the other three datasets are used by following previous work \cite{how-much}, we make a novel adaptation of the SQuAD dataset for closed-book QA. SQuAD \citep{SQuAD2} is a wildly-adopted QA dataset typically for extractive QA, where the input is a question together with a passage containing the answer fact, and the answer is a span from the passage. However, no previous work has used SQuAD for closed-book QA yet. Compared to other QA datasets, SQuAD is the most suitable for our setting, containing corresponding passages, lower test-train overlap, and receiving more research attention. To apply SQuAD on closed-book QA, we only use QA pairs for input and output when QA-finetuning. For TriviaQA and WebQuestions, many questions have multiple answers. In order to align with the other two data sets, we split one question with several answers into several same questions with one answer when training, and take one test output as correct if it appears in the answer list when testing. As the test sets of SQuAD, NaturalQuestions and TriviaQA are not fully publicly released yet and WebQuestions does not have a development set, we split the development set of the three datasets and the test set of WebQuestions into two subsets to serve as a new development set and a new test set. We report performance on the new test sets in Table~\ref{closed-bookQA_on_4_datasets} while analyzing the overlaps on the two subsets together in Table~\ref{output_overlap1} and Table~\ref{output_overlap2}. The details of four datasets after our pre-processing are shown in Table~\ref{dataset_details}. Previous work shows that T5 and BART can achieve promising results \citep{how-much, overlap} on WebQuestions, TriviaQA and NaturalQuestions. However, recently, \citet{overlap} find that the high performance is mainly because the three datasets have severe \textbf{test-train overlap} problems. In particular, we use \textbf{answer overlap} to denote the situation where the answer $a$ in a test $(q, a)$ pair exists in training answers, and the term \textbf{question overlap} to denote the fact that a training question with similar meaning can be found for $q$. To analyze whether SQuAD has the same problem, we also compute the overlap of it. Answer overlap can be easily calculated. For question overlap, following \citet{overlap}, we first randomly sample 1,000 $(q, a)$ pairs from the SQuAD test set. Then for each test question, we automatically select SQuAD training questions whose answer is a sub-sequence of the test answer. Then we ask three human experts to find whether the test $q$ overlaps with any training question. The breakdown statistics are given in Table~\ref{dataset_overlap}. SQuAD has much fewer test-train overlapped cases than the other three datasets. For example, only around 1\% of SQuAD test questions overlap with training questions while the number is around 30\% in the other three datasets. \subsection{Results} The overall QA results on the four datasets are shown in the first row of Table~\ref{closed-bookQA_on_4_datasets}. BART achieves relatively high results on the three datasets WebQuestions, TriviaQA, and NaturalQuestions. However, it performs poorly on SQuAD in closed-book QA, with only 1.5\% accuracy. We also use SQuAD passages to further pre-train BART and then conduct QA-finetuning. The result is shown in the second row of Table~\ref{closed-bookQA_on_4_datasets}, the performance is 1.8\% a bit better than 1.5\% but still extremely low. According to \citet{overlap}, the results are influenced by test-train overlap rates. For simplicity, we define the set of gold standard answers in the train set as $G^{train}$, the set of gold standard answers in the test set as $G^{test}$. We define the set of output answers of BART on the test set as $O^{test}$, the set of output answers which are correct as $O^{correct}$ To further investigate how overlap influences BART's outputs, we choose WebQuestions as the high-overlap dataset representative to compare with the low-overlap dataset SQuAD. Results are shown in Table~\ref{output_overlap1}. The $O^{test}$ of BART on WebQuestions have an 88.5\% overlap with $G^{train}$, which is a decisive proportion. However, the $G^{test}$ have only 59.3\% overlap with $G^{train}$. For BART on SQuAD, the ratios are 39.8\% to 24.9\%, which is relatively less severe. This indicates that if testing questions have a large overlap with training questions, the model tends to generate the targets and words in the train set. We further measure the relationship between how correct/incorrect outputs and overlap/non-overlap with $G^{train}$. The results are shown in Table~\ref{output_overlap2}, 604 of $O^{correct}$ of BART on WebQuestions overlap with $G^{train}$, and only 5 instances of $O^{correct}$ do not exist in $G^{train}$. However, all the five non-overlapping $O^{test}$ on WebQuestions are combinations of words of $G^{train}$ and question words, which can be viewed as a mild type of overlap. The situation is similar but sightly better on SQuAD. These results indicate that it is much easier for BART to answer correctly by superficial cues than by using its internal knowledge. \section{Task Design} The original purpose of previous research \citep{LMasKB, how-much} is to use pre-trained language models (PLMs) as knowledge bases (KBs) and answer questions according to internal knowledge the model contains. However, if the model tends to match test questions with training questions for retrieving answers, then the source of knowledge is restricted to training questions. This deviates from the ultimate goal. We are interested in quantitatively measuring the capability of pre-trained model in closed-book QA using its own internal knowledge from pre-training. This capability can be broken down into two components. First, the capability of a memorizing knowledge from pre-training. Second, the ability of retrieving memorized knowledge for question answering. We show investigations and report the results in the two sections below. \begin{figure}[t] \center{ \includegraphics [width=7.5cm] {procedure.png}} \caption{The main task design. The lower right bold context of each process are names of this process. The bold context in the upper middle of each process is the corresponding process in the classroom teaching. The middle context is the purpose of this process. The left icon represent the state of the model.} \vspace{-2mm} \label{procedure} \end{figure} \begin{figure}[t] \center{ \includegraphics [width=7.5cm] {MASK_Policy1.png}} \caption{Examples of two types of MASK policies in training and testing periods of LM-finetuning. The passage masked randomly is for training and the passage masked with answer spans is for testing (reciting). } \vspace{-2mm} \label{Mask_Policy} \end{figure} \begin{table}[t] \centering \small \setlength{\tabcolsep}{1mm} \begin{tabular}{c|c} \hline \hline \textbf{Models $\backslash$ Dataset} & \makecell[c]{\textbf{ALL SQuAD} \\ \textbf{(20279)}} \\ \hline \makecell[c]{random-initialized BART} & 0.0\% \\ \hline \makecell[c]{original BART} & 2.2\% \\ \hline \makecell[c]{BART $\rightarrow$ LM-finetuning} & 2.7\% \\ \hline \end{tabular} \caption{The reciting performance on all SQuAD passages. We use the BART-Large checkpoint. LM-finetuning and reciting are both conducted on the same 20279 passages. } \vspace{-2mm} \label{recite0} \end{table} \begin{table*}[t] \centering \small \setlength{\tabcolsep}{1mm} \begin{tabular}{c|c|c|c|c|c|c} \hline \hline \textbf{Models $\backslash$ Dataset} & \makecell[c]{\textbf{20}} & \makecell[c]{\textbf{160}} & \makecell[c]{\textbf{547}} & \makecell[c]{\textbf{1094}} & \makecell[c]{\textbf{1641}} & \makecell[c]{\textbf{6020}}\\ \hline \makecell[c]{original BART} & 1.5\% & 5.2\% & 3.6\% & 3.2\% & 2.9\% & 2.2\%\\ \hline \makecell[c]{BART $\rightarrow$ LM-finetuning} & 87.3\% & 72.6\% & 66.3\% & 34.3\% & 14.0\% & 3.9\%\\ \hline \makecell[c]{BART $\rightarrow$ LM-finetuning \\ (Added Prefix/Suffix)} & 85.5\% & 79.6\% & 59.5\% & 40.4\% & 15.8\% & 4.0\%\\ \hline \end{tabular} \caption{Performance of reciting. We use the BART-Large checkpoint. For the header of each column, the numbers stand for passage amounts of the subset. Note that LM-finetuning and reciting are both conducted on the same passages. The last row of this table will be discussed in Section~\ref{decouple-results} } \vspace{-2mm} \label{recite} \end{table*} \subsection{Procedure} As shown in Figure~\ref{procedure}, our design is motivated by classroom teaching. A teacher first teaches the content of a textbook and then asks the student to recite the important points of the book in order to test how well they know the book. Next, the teacher gives the student some exercise questions for practice. Finally, the teacher gives a different set of exam questions to test the student. Note that the whole book is taught and recited, rather than a split of the book, and the exercise questions and exam questions are all related to the book. Section 4 (\textbf{Knowledge Memory}) corresponds the teaching and reciting processes in the classroom teaching. Section 5 (\textbf{Question Answering}) corresponds the practice and exam processes. \section{Knowledge Memory} To investigate whether BART can acquire and store knowledge from raw corpus, we use passages from SQuAD to finetune the BART model, which we call \textbf{LM-finetuning}. This period can be seen as feeding knowledge into BART. Then we test the model to examine how much knowledge BART can memorize. We also call this testing process as \textbf{reciting}. \textbf{Training of LM-finetuning.} We follow the original training objective of BART for the MLM-finetune step, which is a denoising auto-encoding process. The original BART training objective involves five operations, namely token masking, sentence permutation, document rotation, token deletion and text infilling \citep{bart}. We only adopt token infilling in this work because it shows benefits on all downstream tasks \citep{bart}. In addition, the sentence permutation task is shown harmful for tasks despite only being useful for text summarization \cite{bart}. For each input passage, we randomly mask 30\% tokens following \citet{bart}. An example is shown in the third row of Figure~\ref{Mask_Policy}. We ask the model to recover the passage as the output, and use the output and the original passage to compute loss. \textbf{Testing of LM-finetuning (Reciting).} In testing period of LM-finetuning, we develop a task called \textbf{`Reciting'} to probe how much (specific) knowledge the model has. Inspired by \citet{LMasKB} and \citet{olmpics}, who ask discriminative PLMs to fill masks of given masked passages/sentences, our reciting task is to give a generative PLM several masked passages and ask it to recover them. For each passage, we mask the token spans which are answers of related questions. An example is shown in the last row of Figure~\ref{Mask_Policy}. In this way, we can assume that if the BART can recover the specific-masked passages, it must have the knowledge needed for further QA. Note that doing training for LM-finetuning, the masked tokens are randomly chosen, following BART \citep{bart}. Besides, because the answer spans are mostly entities or independent knowledge segments, it is relatively less likely for models to recover them by heuristics or superficial cues. It is natural to do reciting to probe the model's internal knowledge since it is most related to the Masked Language Model process (LM-finetuning and BART's pre-training task). \textbf{Evaluation Metrics}. We use the accuracy of masked spans recovery to measure how much knowledge the model memorizes. Because many answer spans appear several times in passages, we cannot simply treat the presence of the span as correct. In addition, even when the masked token is generated correctly, if its contextual words change, the meaning of the sentence may be different. Considering these, we choose a more strict evaluation metric for the reciting accuracy. We treat a span as correctly predicted only if subsequent words after the current mask and before the next mask (or the subsequent 10 tokens if the span between masked tokens is more than 10) are also correctly predicted. \subsection{Results} We first conduct reciting experiments on all SQuAD passages using the original BART, a random-initialized BART and a LM-finetuned BART. The results are shown in Table~\ref{recite0}. The random-initialized BART gives zero accuracy, demonstrating that the task is difficult and there is no possibility of guessing. The original BART scores 2.2\%, showing that it contains certain but limited knowledge. The LM-finetuned BART gives 2.7\% accuracy. This result shows that LM-finetuning is useful to a certain extent. However, despite that 100\% knowledge is given, LM-finetuning only increases the result by 0.5\%, demonstrating that BART faces significant challenges in memorizing important knowledge contained in pre-training SQuAD texts. Given above observations, we try to reduce the challenge by producing smaller datasets by extracting subsets from SQuAD. The subsets include 20, 160, 547, 1094, 1641, 6020 passages, respectively, where the three numbers indicate the passage amounts. For these reciting experiments, we consider only the original and LM-finetuned BART. The results are shown in the first two rows of Table~\ref{recite}. We can find that (1) using LM-finetuning, BART can memorize some knowledge. For example, when passage subset is 547, the original BART can only recover 3.6\% masked spans correctly while the LM-finetuned BART can recover 66.3\% masked spans; (2) The memorization ability quickly decreases when the passage amount increases. For example, when passage subset are 20, BART can recover 87.3\% masks correctly; when it is 1094, the accuracy falls to 34.3\%; when it is 6020, the accuracy is only 3.9\% We conclude that BART has a certain ability to store (factual) knowledge, but the capacity is rather weak. If we control the number of passages for LM-finetuning, we can make sure that BART can memorize most needed knowledge. The LM-finetuned model trained on smaller subsets gives a more useful setting for testing QA abilities of BART when we are confident that relevant knowledge is retained. \begin{table*}[t] \centering \small \setlength{\tabcolsep}{0.5mm} \begin{tabular}{c|c|c|c|c|c|c|c|c|c|c|c|c} \hline \hline \multirow{2}{*}{\textbf{Models $\backslash$ Dataset} } & \multicolumn{4}{c|}{\makecell[c]{\textbf{20 (16/2/2;125/8/10)}}} & \multicolumn{4}{c|}{\makecell[c]{\textbf{160 (128/16/16;653/107/93)}}} & \multicolumn{4}{c}{\makecell[c]{\textbf{547 (442/53/52;2334/314/306)}}}\\ \cline{2-13} & \makecell[c]{RA(\%)}& \makecell[c]{EM(\%)} & \makecell[c]{HE(\%)}& \makecell[c]{F1(\%)} & \makecell[c]{RA(\%)}& \makecell[c]{EM(\%)} & \makecell[c]{HE(\%)}& \makecell[c]{F1(\%)} & \makecell[c]{RA(\%)}& \makecell[c]{EM(\%)} & \makecell[c]{HE(\%)}& \makecell[c]{F1(\%)} \\ \hline \makecell[c]{BART $\rightarrow$ QA-finetuning} & 1.5 & 0.0 & 0.0 & 11.0 & 5.2 & 2.2 & 4.3 & 6.4 & 3.6 & 1.9 & 4.9 & 7.0\\ \hline \makecell[c]{BART $\rightarrow$ LM-finetuning \\ $\rightarrow$ QA-finetuning} & 87.3 & 10.0 & 30.0 & 15.4 & 72.6 & 3.2 & 6.5 & 9.0 & 66.3 & 2.3 & 6.9 & 6.7\\ \hline \makecell[c]{BART $\rightarrow$ LM-finetuning \\ $\rightarrow$ QA-finetuning\\\textbf{(Added Prefix/Suffix)}} & 85.5 & 10.0 & 30.0 & 21.0 & 79.6 & 3.2 & 10.8 & 10.1 & 59.5 & 2.9 & 7.8 & 8.2\\ \hline \makecell[c]{BART $\rightarrow$ LM-finetuning \\ $\rightarrow$ \textbf{QA-bridge-tuning}}& 87.3 & 20.0 & 40.0 & 27.8 &72.6 & 9.7 & 20.4 & 15.3 & 66.3 & 4.6 & 11.8 & 9.3\\ \hline \makecell[c]{BART $\rightarrow$ LM-finetuning \\ $\rightarrow$ \textbf{QA-bridge-tuning}\\\textbf{(Added Prefix/Suffix)}} & 85.5 & 20.0 & 40.0 & 31.7 & 79.6 & 11.8 & 22.6 & 16.3 & 59.5 & 5.6 & 12.7 & 10.3\\ \hline \end{tabular} \caption{QA performance on three subsets of SQuAD. The numbers in headers are the passage and QA pair amounts, for example, `160 (128/16/16;653/107/93)' indicates this subset has overall 160 passages and 128/16/16 passages, 653/107/93 QA pairs in train/dev/test set, respectively. The number in RA column stands for reciting accuracy, which is the same with Table~\ref{recite}. The RAs in the table can show how much knowledge BART memorizes before QA-finetuning, of which values the model should achieve in QA accuracy if it can fully use internal knowledge to answer questions. The cells with bold text are our methods. EM, HE indicate Exact Match, Human Evaluation, respectively. `BART' denotes the `BART-Large' checkpoint. } \label{qa} \end{table*} \begin{table}[t] \centering \small \setlength{\tabcolsep}{0.5mm} \begin{tabular}{|p{2.75cm}<{\centering}|p{1.3cm}|p{3.4cm}|} \hline \hline \multirow{2}{*}{\textbf{Question\&Answer}} & \multicolumn{2}{c|}{\makecell[c]{\textbf{Model Output}}}\\ \cline{2-3} & \makecell[c]{QA-finetune}& \makecell[c]{QA-bridge-tune} \\ \hline \makecell[c]{Q: What is Southern\\ California often\\ abbreviated as? \\A: SoCal } & \makecell{Southern\\ California} & \makecell{Southern California, often\\ abbreviated \textbf{SoCal}, is...\\ $<$ANSWER$>$ SoCal}\\ \hline \makecell[c]{Q: What century \\did the Normans\\ first gain their\\ separate identity? \\ A:10th century } & \makecell{20th\\ century} & \makecell{... distinct cultural and \\ethnic identity of the\\ Normans emerged initially\\ in the first half of the \\ \textbf{10th century} ...\\ $<$ANSWER$>$ 10th}\\ \hline \makecell[c]{Q: What is the\\ largest stadium\\ in Australia? \\A: Melbourne\\ Cricket ground} & \makecell{Australia\\ Stadium} & \makecell{... $<$ANSWER$>$\\ Melbourne Cricket\\ ground}\\ \hline \makecell[c]{Q: When did the\\1973 oil crisis begin?\\A: October 1973} & \makecell{1973} & \makecell{... $<$ANSWER$>$ October\\ 1973}\\ \hline \end{tabular} \caption{Four real output examples on QA-finetuning and QA-bridge-tuning by BART. } \label{qa-examples} \vspace{-2mm} \end{table} \begin{table}[t] \centering \small \setlength{\tabcolsep}{1mm} \begin{tabular}{c|c|c|c|} \hline \hline & \makecell[c]{\textbf{A $>$ B}} & \textbf{A $=$ B} & \textbf{A $<$ B}\\ \hline \makecell[c]{Relevance } & 30.2\% & 53.3\% & 16.6\% \\ \hline \end{tabular} \caption{ Human-evaluated relevance between the results using and not using QA-bridge-tune with correct answers. A $>$ B means that A's outputs are more related to correct answers than B's, etc. A = QA-bridge-tune, B = QA-finetune in this Table. } \vspace{-2mm} \label{relevance} \end{table} \begin{table}[t] \centering \small \setlength{\tabcolsep}{1mm} \begin{tabular}{c|c|c|c} \hline \hline \textbf{Models $\backslash$ Dataset} & \makecell[c]{\textbf{16/2/2}} & \makecell[c]{\textbf{128/16/16}} & \makecell[c]{\textbf{442/53/52}}\\ \hline \makecell[c]{BART $\rightarrow$ LM-finetuning} & 87.3\% & 72.6\% & 66.3\% \\ \hline \makecell[c]{BART $\rightarrow$ LM-finetuning \\ (Added Prefix/Suffix)} & 85.5\% & 79.6\% & 59.5\%\\ \hline \makecell[c]{BART $\rightarrow$ LM-finetuning \\ $\rightarrow$ QA-finetuning} & \makecell[c]{2.8\%} & \makecell[c]{10.9\%} & \makecell[c]{2.4\%}\\ \hline \makecell[c]{BART $\rightarrow$ LM-finetuning \\ $\rightarrow$ QA-finetuning \\ (Added Prefix/Suffix)} & \makecell[c]{5.7\%} & \makecell[c]{51.4\%} & \makecell[c]{16.2\%}\\ \hline \end{tabular} \caption{ Performance of reciting after QA. The numbers in the header is the passage amount of this subset. `BART' denotes the `BART-Large' checkpoint. } \label{recite_after_qa} \vspace{-2mm} \end{table} \begin{figure}[t] \center{ \includegraphics [width=7.5cm] {bridge-tune1.png}} \vspace{-2mm} \caption{An intuitive approach to QA-bridge-tuning. To make the model more dependent on the internal knowledge to answer the question, the model is required to generate not only answer but also the corresponding passage. The outputs should be `P $<$ANSWER$>$ A', where `P' stands for the corresponding passage, $<$ANSWER$>$ is a special marker and the A stands for the answer. } \vspace{-2mm} \label{bridge_tune} \end{figure} \section{Question Answering} We employ the settings in the first three columns in Table~\ref{recite}, where models can memorize at least 50\% of needed knowledge, for further analyzing the relationship between memory and QA ability. For these experiments, all QA pairs come from passages that BART has been LM-finetuned on. \subsection{Overall Results} Besides Exact Match (EM) which is commonly used in previous closed-book QA work \citep{how-much, overlap}, we also consider Human Evaluation (HE) and F1 for two reasons. First, we observe that EM cannot fully indicate correctness. For example, a question is \textit{``What century did ... ?"} and the golden answer is \textit{``10th century"}. The model outputs ``10th" which is actually correct in but taken incorrect by EM. Second, F1 can help indicate the similarity between the outputs and golden answers. The overall results are presented in the first two rows of Table~\ref{qa}. According to the result of `original BART-Large→LM-finetuning→QA-finetuning', compared to Reciting Accuracy (RA) of each model, the QA accuracy is much lower (87.3\% vs 30\%, 72.6\% vs 6.5\%, 66.3\% vs 6.7\% in HE). This result shows that BART's ability to use its internal knowledge to answer questions is weak. In addition, comparison between the first row and the second row shows that memorized knowledge helps the models better answer questions, though the help is not much (30\% vs 0.0\%, 6.5\% vs 4.3\%, 6.9\% vs 4.9\% in HE). For the reciting-QA-accuracy gap, we propose two possible explanations, the first is that the model cannot activate related memory for question answering; the second is that the memorized knowledge is somehow corrupted during QA-finetuning. \subsection{Strengthening Memory Retrieval} \label{QA-bridge-tune} Qualitative cases show that, even the model contains needed knowledge, the model does not necessarily refer to the most relevant memory for question answering after QA-finetuning. We list several this kind of examples in the `QA-finetune' column of Table~\ref{qa-examples}. For example, in the first row of Table~\ref{qa-examples}, for the question \textit{``What is Southern California often abbreviated as?"}, despite of the model is trained with \textit{``Southern Californi, often abbreviated \textbf{SoCal}"}, it still answers `Southern California', which indicates that the model cannot retrieve related memory for answering questions. We propose a simple way to strength knowledge retrieval, namely \textbf{QA-bridge-tune}, which is a extended QA-finetuning process. The process is illustrated in Figure~\ref{bridge_tune}, for each question input, the output concatenates the related passage with the answer. Thus, the model can explicitly recall the memorized passages when answering questions, by which QA-bridge-tune builds a bridge between QA and memorized knowledge so that the model can answer questions with learned knowledge. In addition, this method can help improve interpretability. The results are shown in Table~\ref{qa}. We can see that QA-bridge-tune can help the model wake up the related memorize knowledge when QA, thus improving EM accuracy and by two or three times on baselines. In addition to answer correctness, we also consider the relevance between model outputs and golden answers regardless whether the answer is correct. For example, the question is \textit{``The Amazon rainforest makes up what amount of Earth's rainforests?"} and the golden answer is \textit{``over half"}, and two generated answers are ``60\%" and ``the Amazon rainforest". They are both incorrect but the former is more relevant and therefore a better answer. We ask human experts to manually compare the results between using and not using QA-bridge-tuning, selecting results by using `BART→LM-finetuning→QA-finetuning' and `oBJ→LM-finetuning→QA-bridge-tuning' strategies on the `128/16/16' subset. The results are shown as Table~\ref{relevance}. According to human experts, in 30.2\% cases, the outputs of QA-bridge-tuning are more relevant to the golden answer than those of QA-finetuning while only in 16.6\% cases, QA-finetuning is more relevant. This result shows that QA-bridge-tuning can help BART find more relevant knowledge. We also list several examples showing in Figure~\ref{qa-examples}. As the example in the first paragraph of this subsection, for question \textit{``What is Southern California often abbreviated as?"}, BART can output the corresponding passage along with the correct answer \textit{``SoCal"} after QA-bridge-tuning. These results suggests that QA-bridge-tuning can effectively help the model recall the remembered knowledge. \subsection{Influence of QA on Memory} \label{decouple-results} To explore whether QA-finetune interferes with the memory of LM-finetuned models, we use QA-finetuned models for the reciting task. The results are given in Table~\ref{recite_after_qa}. After QA-finetuning, the models' reciting accuracy declines. We have two possible explanations for this phenomenon. First, QA-finetune process disrupts the models' internal memory with regard to representation; Second, the tasks are different, so model output space is disturbed, but the model still retains knowledge. Though we cannot qualitatively understand the influence of each reason above, isolating the QA functionality from pre-trained denoising auto-encoding can potentially address interference issues. We experiment with a simple intuitive solution to this issue, namely to decouple the QA-finetune process and the LM-finetune process, so that the two task input/output spaces are differentiated to some extent. This is done simply in the input and output level. We add $<$PASSAGE$>$/$<$QUESTION$>$ prefix tokens and $<$/PASSAGE$>$/$<$/QUESTION$>$ suffix tokens to each input passage/question when LM-finetuning and Reciting/QA-finetuning, respectively, and also add $<$/PASSAGE$>$/$<$/ANSWER$>$ suffix tokens to each output passage/answer. The results are shown in the rows with (Added Prefix/Suffix) in Table~\ref{recite_after_qa}. The reciting accuracy with prefix/suffix after LM-finetuning is not much different compared without prefix/suffix. However, the QA accuracy significantly improves when adding prefix/suffix (2.8\% to 5.7\%, 10.9\% to 51.4\%, 2.4\% to 16.2\% in HE). The results show that our decoupled methods can help the model distinguish the input type to find the appropriate semantic space, thus alleviating this problem. Besides, according to the comparison between the second row and the third row in Table~\ref{qa}, adding prefix/suffix can help models better answer questions. We suppose it is also because this method can help models distinguish the input/output space. \begin{table}[t] \centering \small \setlength{\tabcolsep}{1mm} \begin{tabular}{c|c|c|c} \hline \hline \textbf{Models $\backslash$ Dataset} & \makecell[c]{\textbf{16/2/2}} & \makecell[c]{\textbf{128/16/16}} & \makecell[c]{\textbf{442/53/52}}\\ \hline \makecell[c]{original GPT-2 \\ $\rightarrow$ LM-finetuning \\ $\rightarrow$ QA-finetuning} & \makecell[c]{0\%} & \makecell[c]{1.1\%} & \makecell[c]{1.0\%}\\ \hline \end{tabular} \caption{ Performance of GPT2 in the same setting as the second row of \ref{qa}. The numbers in the header is the passage amount of this subset. The score is evaluated with Exact Match (EM). } \label{qa_gpt2} \vspace{-2mm} \end{table} \subsection{GPT-3} GPT3 has also been shown to have certain capabilities to answer factual closed-book questions. As shown in Table 3.3 of \citet{GPT3}, it can achieve relatively high performance on TriviaQA in closed-book task even in zero-shot learning setting. However, it underperforms T5 \citep{how-much} in the other two datasets WebQuestions and NaturalQuestions, which indicates that super large scale pre-training is not the ultimate solution to the issue we discussed. There is also a possibility that GPT-3 has seen most test QA pairs of TriviaQA in the pre-training stage as it crawls extremely large documents from the internet. We also apply GPT-2 to LM-finetuning and QA-finetuning, which has similar architecture, pre-training and finetune process with GPT-3. Thus we believe that they can have the same fundamental problem. The results are shown in Table~\ref{qa_gpt2}. LM-finetuned GPT-2 has worse performance compared to LM-finetuned BART. This confirms that the architecture and the training process of GPT3/GPT-2 do not solve the problems we find using BART. \section{Related Work} There are two types of pre-trained language models (PLMs), discriminative PLMs such as BERT \citep{BERT}, ELMo \citep{ELMo} and generative PLMs such as GPT \citep{GPT}, BART \citep{bart}. The key difference is that generative PLMs are of encoder-decoder architectures so they can generate text sequences of any length or token. An increasing number of works have shown that PLMs contains world knowledge. \citet{LMasKB} first solves that discriminative PLMs such as BERT \citep{BERT} can be used for Cloze-style QA using a mask language modeling task without external resources, such as \textit{``Dante was born in [MASK]." }$\rightarrow$ \textit{``Florence"}. Their results show that PLMs have certain factual knowledge. \citet{olmpics} set eight types of Cloze-style QA, such as `ALWAYS-NEVER' and `AGE COMPARISON', to test different types of knowledge in several discriminative PLMs, including BERT and RoBERTa \citep{RoBERTa}. They also use the mask language modeling task to do QA without finetuning, and results show that the evaluated PLMs indeed contain those kinds of knowledge. \citet{wang-etal-2019-make, zhou2020evaluating} adopt some discriminative PLMs on commonsense reasoning QA tasks such as ComVE \citep{Wang2020SemEval2020T4} and Swag \citep{SWAG} without finetuning, indicating the PLMs have commonsense knowledge. \citet{COMET} show that pretrained transformer models can be used to help construct commonsense knowledge graphs, such as ConceptNet \citep{ConceptNet5}. However, \citet{Poerner2019BERTIN} argue that BERT uses some superficial cues such as stereotypical characters to solve factual questions. GPT-3 \citep{GPT3} seems to have ability to answer factual questions in zero-shot setting, but there exists some evidence that GPT-3 is limited in storing and using knowledge \citep{NoGPT3}. \citet{how-much} firstly use closed-book QA to detect how much knowledge is in pre-trained language models' parameters. They perform experiments on three datasets WebQuestions \citep{WebQuestions}, TriviaQA \citep{triviaqa} and NaturalQuestions \citep{NQ} by T5 model \citep{t5}. The results are relatively pleasant. However, \citet{overlap} find that the high performance of \citet{how-much} is mainly due to the high test-train overlap of the three datasets rather than the model's internal knowledge. Our findings confirm the conclusions of \citet{overlap}, and we further experiment with a more controlled SQuAD dataset, and discussed the weakness of BART in both memorization and knowledge retrieval. Because T5 \citep{t5} is more resource demanding, considering the balance of effectiveness and experimental feasibility, we choose BART rather than the T5 model. Different from closed-book QA, where no additional resource is available when answering questions, open-domain QA requires models to generate a sequence of tokens as the answer to each question by looking up related text from unstructured documents \citep{DrQA}. \citet{DrQA} first try to retrieve related passages from Wikipedia for each question and encode both the question and passages into the model, then output the answer. \citet{REALM} integrate the retrieval process into pre-training process, helping the PLMs better retrieve information from external knowledge source when needed, and finding benefits on open-domain QA task. Retriever-based models have the advantage of relieving the burden of pre-trained language models to remember every factual detail. The retrieval QA setting is slightly reminiscent to our data augmentation setting in Figure~\ref{bridge_tune}, but with the related passage being the input, rather than the output. In contrast, the settings we consider fully rely on a neural model for all knowledge. SQuAD \citep{SQuAD, SQuAD2} is a widely-used dataset for machine reading comprehension, which is also a type of QA task. It asks models to use a text span from a given referential passage to answer questions. It is also used in other type of QA task, for example, \citet{DrQA} adopt it in the open-domain QA task. We first apply it on closed-book QA and analyze why it is superior than other three commonly used datasets. \section{Conclusion} We investigated by using SQuAD, finding that closed-book QA is still challenging for generative pre-trained language models such as BART. The challenge lies both in remembering the knowledge details and in answering the questions after remembering the knowledge. Potential solutions include explicitly asking models to recall relevant knowledge when answering questions and decoupling LM-finetuning process and QA-finetuning process. \section{*Acknowledgement} The work was supported by NSFC 61976180. We thank Yongjing Yin, Chuang Fan, Yuchen Niu, Sara Gong, Tony Ou, Libo Qin and all reviewers for their generous help and advice during this research. \bibliographystyle{acl_natbib}
{'timestamp': '2021-06-04T02:09:12', 'yymm': '2106', 'arxiv_id': '2106.01561', 'language': 'en', 'url': 'https://arxiv.org/abs/2106.01561'}
arxiv
\section{Background} \subsection{Docker and Docker Swarm} Docker Containers are best suited for Microservices. Docker provides lightweight encapsulation of each application enabling independent deployment and scaling of each microservice. Docker is a composing Engine for Linux containers, an OS-level virtualization technique, which uses namespace and cgroups to isolate applications in the same linux kernel. Control group (abbreviated as cgroup) is a collection of processes that are associated with a set of parameters. cgroup ensures that the specified resources are actually available for a container. Namespace isolation is another such feature where groups of processes are separated such that each group cannot see the resources used by other groups. The kernel resources are partitioned such that a set of processes sees a set of resources while another set of processes see a different set of resources~\cite{docker_article}. Docker uses copy on write (COW) and layered storage within images and containers. A Docker image is a read-only template, which references a list of read-only storage layers, used to build a linux container. Docker container is a standard software unit that packages up code and dependencies so that the application runs quickly and can be shipped reliably from one computing environment to another. Docker images become Docker containers at run time when they run on Docker Engine. The layered storage allows fast packaging and shipping of an application as a lightweight container by sharing common layers between images and container. By using Docker, there is potential for faster deployment time and faster model updates~\cite{docker_article}. When you have a lot of containerized applications running, there should be a mechanism to make them all work towards a common goal. One method to achieve this is using Docker Swarm. Docker Swarm is a group of machines that are joined together as a cluster and commands are executed by swarm manager to control the group of machines. Each machine in swarm is called a node which can be physical or virtual Machine. Applications can be defined using a manifest file and easily deployed using Docker commands~\cite{swarm_docker}. \subsection{Worker and Manager Nodes} Manager Nodes control the cluster with tasks such as maintaining the state of the cluster, dispatching tasks to worker and providing fault tolerance to the system. Currently, Docker supports using multiple Manager nodes where only one manager would be elected as leader and it performs all the responsibilities of a manager. The other manager nodes are standby managers which receive updated information about state of the system and may be chosen as leader when leader node goes down. Using multiple managers is fairly new experimental feature in Docker which would be explored in this research. Worker Nodes are instances which accept tasks from Manager Nodes and execute them as containers. Worker Nodes will not share their state information with other worker nodes and do not make scheduling decisions~\cite{swarm_docker}. \subsection{Scale-in and Scale-out of applications} When a Microservice application is deployed, we might need to increase the number of microservice components (scale-out) or decrease the number of microservice components (scale-in) based on the user demand and progress towards end goal. This calculation should happen automatically and applications need to be re-scaled based on workload and progress towards end goal~\cite{Venugopal_2017}. \begin{figure} \centering \includegraphics[width=8.5cm]{figures/Design2.pdf} \caption{System Architecture diagram} \label{Design2} \end{figure} \section{Coalescer and Stratagem Functionality} \section{Conclusion and future work} Autonomous systems are evolving at a very fast pace and moving towards achieving full autonomy~\cite{transportresearch}. The industry and research community need to focus on coordinating multiple applications that work closely together towards achieving an end goal. Containers are increasing in popularity for building and shipping applications efficiently~\cite{docker_article}. This paper is an early work which focuses on building an orchestrator component using Docker Swarm mode to coordinate multiple applications that are working together towards an end goal. The orchestrator component is responsible for tracking and choosing the model updates leading to performance improvement. The updates would be prioritized considering system performance and individual application performance. Currently, we have a framework and infrastructure setup to deploy, track and update an application. The future plan is to build several different applications using different Machine Learning techniques. We plan to build applications such as intruder detection, simple face recognition, obstacle detection, mission planner which can work collectively towards safely reaching the destination from a source point. During the mission, we try to run different workload by constraining the mission to measure performance of system and record how DSOC efficiently reaches the end goal. {\small \noindent {\bf Acknowledgments:} This work was funded in part by NSF Grants 1749501 and 1350941 with support from NSF CENTRA collaborations (grant 1550126). This was an IDEA and Early work paper submitted to ICAC 2019 (now known as ASCOS).} \section{Implementation} \begin{figure} \centering \includegraphics[width=8cm]{figures/algo1.png} \caption{Greedy Algorithm} \label{fig:greedy} \end{figure} \begin{figure} \centering \includegraphics[width=8cm]{figures/algo2.png} \caption{DSOC Algorithm} \label{fig:dsoc} \end{figure} We can leverage the existing Docker swarm functionality for our implementation. Swarm managers control all the nodes and they can use several strategies to run containers efficiently. It can be 1. "emptiest node" technique - which fills the least utilized machine with containers 2. "global"- which ensures each machines gets exactly one instance of the specified machines. These strategies help in load balancing, scaling and fault management~\cite{swarm_docker}. There are two methods to implement coordination among groups of applications working towards a specific goal. Greedy approach is one method where every application is eager to increase it's accuracy and performance. Whenever there's a newer model or updated code available which improves accuracy and performance, the application tries to perform an update. Figure~\ref{fig:greedy} explains how a greedy approach for patching works. We maintain an update Queue which stores all the model and code updates of applications. M$_{ij}$ is a code/model update for application-j running on node-i. Calculate 'K' updates which can be performed such that overall system performance doesn't degrade. Till the update Queue is non-empty, choose an update M$_{ij}$ and check if the node-i is unconstrained. If it's unconstrained, assign a worker to update the application-j on node-i with M${ij}$. If the node-i was constrained, delay the M$_{ij}$ update and proceed by choosing the next model in update Queue. The second approach is the DSOC approach (Figure~\ref{fig:dsoc}) where the "Coalescer" handles all the updates, evaluating the priority of update requests. The system specific parameters like throughput, memory, cpu utilization, bandwidth and application specific parameters like accuracy improvement, execution time, latency are carefully considered before updating an existing model/code fragment. Refer to Figure~\ref{fig:assprior} to understand how priority is assigned to model/code update. The updates are prioritized after considering all system specific and application specific parameters. c1, c2 are the parameters used to indicate the weight to be given to SP(system specific parameters) and AP(Application specific parameters) such that $0\le{c1} \le {c2} \le {1}$ and c1 + c2 = 1. System specific weights for CPU utilization, memory, storage and throughput are stored in sWeight. Application specific weights for accuracy, progress, latency and execution time are stored in aWeight. Using these, the system performance and application performance of running application\-j on node\-i would be calculated. Using these metrics, we would be able to calculate pVal which combines both application and system performance into single metric. The applications which need their updates immediately would be classified as green(priority one), next prioritized updates would be yellow (priority two), updates with least priority would be blue (priority three) and classifiers which need not be updated are red. Green, yellow, blue and red are the coloring scheme maintained by coalescer in order to assign priority to an application's model update (refer to Figure~\ref{fig:assprior}). In the DSOC approach, if individual applications are consistent and make efficient progress towards end goal by carefully considering model updates, we can state that the overall system performance and progress would be prolific. \begin{figure} \centering \includegraphics[width=8.5cm]{figures/assig1.png} \caption{assign\_priority calculation} \label{fig:assprior} \end{figure} \begin{figure} \centering \includegraphics[width=8cm]{figures/implement1.pdf} \caption{Accuracy improvement against task completion} \label{fig:implement2pred} \end{figure} In Figure~\ref{fig:implement2pred}, we try to carefully predict the trade-off between accuracy improvement and closeness towards end-goal. Closeness towards end-goal is percentage of task completed like 20\%, 40\%, 60\% and so on. In Greedy approach, the accuracy constantly increases and we reach faster towards the ends goal. We reach the end goal with slightly better accuracy using greedy approach using a lot of resources and performing many updates. On the other hand if we choose DSOC approach, there would be slight improvement in overall accuracy as we progress towards end-goal and there would be slower progress towards the end goal, but it uses less resources and performs fewer updates. In DSOC approach, we reach the end goal with lesser updates and slightly lesser accuracy compared to greedy model. \section{INTRODUCTION} Autonomous systems like Self-driving cars, autonomous aerial systems, smart restaurants and smart traffic lights have attracted a lot of interest from both academia and Industry~\cite{transportresearch}~\cite{boubin2019managingdeprecated}. Many top companies like Google, Uber, Intel, Apple, Tesla, Amazon have significantly invested in researching and building Autonomous Systems~\cite{selfdriving}. An autonomous system is a critical decision making system which makes decisions without human intervention. An autonomous system is comprised of complex technologies which learns the environment, makes decision and accomplishes the goal~\cite{transportresearch}. In this paper, we focus on "Microservices Orchestration" for coordinating multiple autonomous applications that are working towards a common objective. Microservices is an architectural style which structures an application as a collection of different services that are loosely coupled, independently deployable and highly maintainable. Large, complex applications can be deployed using Microservices where each service will have different logical function and contribute to the bigger application~\cite{micro_article}. When working towards a particular goal, we might need to deploy multiple applications which need to take up a sub task and coordinate with other applications in order to efficiently complete the task at hand. Efficient coordination of multiple different applications is really crucial for building fully autonomous systems Configuring, controlling and keeping track of each microservice would be really hard~\cite{orchestrate}. An efficient way to track and manage multiple applications would be using an orchestrator. Orchestration is a process which involves automated configuration, management and coordination of multiple computer systems and application software~\cite{it_orchestrate}. There are various orchestration tools for Microservices like ansible~\cite{ansible}, Kubernetes~\cite{kubernetes}, Docker Swarm~\cite{swarm_docker}. \begin{figure} \centering \includegraphics[width=8cm]{figures/intro_graph.pdf} \caption{Why Coordination and Patching?} \label{fig:introduc} \end{figure} When working with Artificial Intelligence based applications, the performance of each microservice may degrade over time and there needs to be an updated code or Machine Learning model in order to restore the performance~\cite{naveeniotonline}. When multiple applications seek an update, allowing all updates would degrade bandwidth, increase throughput and may not yield much performance gain~\cite{naveeniotonline}. If any microservice application need an update, it would be a tedious task to identify individual application and perform the update. While performing such updates we need to consider individual application performance, progress towards end goal and system performance~\cite{7886112}. It is practically impossible to consider every application's performance parameters and pick the model to be updated at run-time~\cite{poster_Aiiot}. A Patch could be a code update that fixes a bug or yields performance improvement, Machine Learning model update and would be referred as "Classifier". The term Classifier is used in rest of this paper. Figure~\ref{fig:introduc} approximates the usage of Classifiers in AI-based applications and patching in real world Autonomous Systems such as Self Driving cars, Smart Traffic Systems, Aerial vehicles and Smart surveillance. These autonomous applications make use of nearly 40-140 total classifiers out of which at least 40 percent have frequent classifier update to improve performance~\cite{naveeniotonline}. The frequency of update in individual application is calculated by performing a literature survey of updates using incremental software releases~\cite{autopilot}~\cite{dji}~\cite{trlights}. Out of the total updates, at least 50 percent of them are correlated updates. For example, an update to an application's model would impact the performance of another interdependent model or code fragment. If multiple applications are coordinating with one another towards a common objective, the choice of update significantly impacts the performance of the system and rate of completion towards the end goal. This paper proposes Docker Swarm Orchestration Component called "DSOC" which is responsible for orchestrating multiple applications and efficiently prioritizing classifier updates. To the best of our knowledge, this is the first work to propose an efficient method of using Docker Swarm for multiple AI based application coordination involving classifier updates. \section{Related Work} To the best of our knowledge, so far no approaches with focus of this paper (Efficient Patching for coordinating Edge Applications) have been published. In this section, we discuss related work which are closely related to the research problem of this paper. Lele Ma et al.~\cite{service_handoff} proposed efficient service hand-off across edge servers using Docker containers migration. Researchers give an in-depth explanation of leveraging Docker features to the full extent. The paper incorporates migration algorithm for service hand-off which gives insights on the process of patching an application. Taherizadeh et al.~\cite{dml_scaling} proposed an auto-scaling method for time-critical cloud applications considering system performance and application level monitoring. The researchers built a Dynamic Multi-level autoscaling system using Kubernetes as an orchestrator. Kaewkasi et al.~\cite{7886112} worked on building Ant colony optimization based scheduling algorithm which outperforms the built-in scheduling provided by Docker Swarm. This research gave hints on carefully considering resource utilization and available resources for coordinating applications. \section{System Architecture} As depicted in Figure~\ref{Design2}, the System architecture consists of 3 main components: Application, Coalescer and Stratagem. Applications are lightweight and containerized units which are deployed to achieve a particular sub-task. The main focus in this research is to choose updates efficiently when a group of different applications coordinate to achieve a common objective. Such a group of applications working towards a common objective is called "Swarm"~\cite{swarm_docker}. The single point of contact for multiple applications is the "Coalescer". Coalescer is the orchestrator unit in our design which helps in coordinating multiple applications to achieve a particular goal. A Coalescer has multiple functionalities: It tracks application changes, it processes migration request, it tracks progress and performance per application. If there is performance degradation in any of the application(s), Coalescer makes sure the expected performance of application would be restored. Coalescer handles coordination of multiple applications, updates to application and makes sure overall performance of the system is preserved. Stratagem is a component which records application changes and updates the application with suitable code/model in order to satisfy performance criteria. Stratagem prioritizes updates considering different performance metrics and migrates the required difference, between source code/model and updated code/model, to the appropriate application. \begin{figure} \centering \includegraphics[width=8.5cm]{figures/Microservice.pdf} \caption{Interaction of different nodes in DSOC} \label{figX} \end{figure} Figure~\ref{figX} explains the logical components that are used to build Coalescer and Stratagem. "Manager" is a logical component present in Coalescer. A Manager node tracks one or more applications and makes sure the performance of those applications are optimum. "Worker" is a logical component present in Stratagem. A Manager node creates multiple worker nodes to track the deployed applications. A manager creates a worker node per application to track changes and makes sure the performance, progress expectation of that application is being met over time. As Autonomous systems such as Self driving cars, Aerial Vehicles, Smart traffic system, smart restaurants are becoming increasingly popular~\cite{swarm_docker}, they have not focused on building DSOC type application which efficiently progresses towards the goal, using a strategy which is easy to deploy and maintain. An autonomous application which is deployed in production will comprise of several smaller applications coordinating together to achieve an end goal~\cite{IOT_growth}. This is a Microservices based architecture where each independent component would have a logical function and contributes towards the end goal~\cite{micro_article}. Building such an efficient system which tracks and makes timely progress towards end goal is really crucial. During deployment, there might be updates to individual applications which improves their performance. If all the update hungry applications are allowed to update their model, it would lead to increased throughput and bandwidth degradation. There should be an effective method of prioritizing updates taking several factors such as latency, progress, cpu utilization, memory, accuracy when multiple applications are seeking an update. The implementation section discusses details about prioritizing updates and using the framework from ~\cite{SoftwarePilot}. Using a DSOC approach would give greater control over applications and ensure performance of the system is maintained. Using DSOC, critical concerns like code update, Machine learning model update, performance based progress towards end goal are carefully considered.
{'timestamp': '2021-01-05T02:14:22', 'yymm': '2101', 'arxiv_id': '2101.00397', 'language': 'en', 'url': 'https://arxiv.org/abs/2101.00397'}
arxiv
\section{Introduction} Since the advent of transformers in the computational linguistics field in 2017 \cite{vaswani2017attention}, they have received great attention for a wide variety of tasks, ranging from constituency parsing \cite{kitaev2018constituency} to coherence modelling \cite{patil2020towards} and sentiment analysis \cite{tang2020dependency}. However, until recently the transformers have been limited to the discrete signal domain. Speech, being in the continuous domain, lags behind. As one of the first models for transformer based speech representation, vq-wav2vec \cite{baevski2019vq} proposed a two-stage pipeline. It discretizes an input speech to a $K$-way quantized embedding space (similar to word tokens for NLP tasks). The embeddings are then extracted from a BERT-based transfomer model. Mockingjay \cite{liu2020Mockingjay} and AudioALBERT \cite{chi2020audio} are other such transformer models taking mel and fbank features as input, respectively. Mel-scale spectrogram as input are a more compendious acoustic feature compared to linear-scale spectrogram and fbank features are Mel filter bank coefficients which give better resolution at low frequencies and less at high frequencies, much like the human ear. Wav2vec2.0 \cite{baevski2020wav2vec} is a recent transformer based speech representation model that converts an input audio to latent space embeddings via a contrastive task. These audio transformers have been applied over many diverse downstream speech language processing tasks with state-of-the-art results, such as speech translation \cite{wu2020self}, speaker recognition \cite{tian2020synchronous}, automatic scoring \cite{grover2020multi}, and sentiment classification \cite{tang2020dependency}. This also begs the question as to what these transformer models are able to learn during the pretraining phase that helps them for various evaluation tasks\footnote{The sentiment of the above inquiry is also conveyed by Prof. Ray Mooney's quip that the meaning of a whole sentence cannot be captured by a \$\&!\#* vector \cite{conneau2018you,mooneyQuip}.}. Besides, as more and more applications start relying on such models, it is important to explain what these embeddings capture to check for potential flaws and biases, which can affect a large number of applications. \begin{figure*} \includegraphics[scale=0.75]{wv.pdf} \caption{\label{fig:wv arch}wav2vec2.0 Architecture} \end{figure*} To this end, different research studies started probing language model embeddings for particular linguistic properties of interest. In \cite{belinkov2017neural}, Belinkov et al. probed for part-of-speech language understanding, \cite{hewitt2019structural} probed for syntax, \cite{peters2018deep} on morphology, \cite{zhang2020language} for scales and numbers, \emph{etc.} However, progress in the audio domain has been very limited with only a few works \cite{raj2019probing,alishahi2017encoding,belinkov2017analyzing,prasad2020accents}. Most of these works treat the audio encoders as automatic speech recognition (ASR) systems. Because of this restrictive treatment, they probe on a limited set of features important for ASR, such as phones, accent and style (spontaneous and non-spontaneous). However, the analysis does not explain the state-of-the-art performance that audio encoders achieve on a wide variety of tasks. Our contributions are summarized as: (1)~We introduce here (47) probing tasks to capture simple linguistic features of speech audios, and we use them to study embeddings generated by two different audio transformers on three types of speeches, uncovering intriguing properties of encoders. (2)~We propose a detailed analysis of what is learned by the recent transformer-based semisupervised audio encoder models, {wav2vec2.0\xspace} and {Mockingjay\xspace}. We implement post hoc probing on the embeddings extracted from each intermediate unit of the two models. We probe these embeddings using an extensive diversity (4 high-level categories) and number of features (46 in total), each categorized by the linguistic property they probe. We extract the results on all the features relevant to speech covering both \textit{what} was spoken and \textit{how} it was spoken. These results help us lay out a map of what particular features are learned in each layer while also providing a metric of comparison between the two models. These features are crucial for downstream applications such as automatic scoring, readability evaluation, automatic speech generation quality, text to speech quality, accent detection, ASR models, \textit{etc.} \cite{yan2018complexity,barth2014effects,rasinski2004assessing,zhang2019learning,kyriakopoulos2020automatic,jyothi2015improved}. As a proof of concept, we also show the effect of our analysis on two such downstream applications (speaker identification and phone classification) (\S\ref{sec:Effect on Downstream Tasks}). (2)~We test the models for their representative effectiveness on different types of speech settings: native-read, native-spontaneous, and non-native-read. We find that, for the most part, native-spontaneous and non-native speech settings follow the result patterns for native-read dataset albeit with a worse performance. In general, type of speakers matter less than the type of speech. (3)~We identify the role of the feature extractor module in wav2vec2.0, which enables it to process raw input audio of $16 KHz$ without any preprocessing. We find that the subsequent layers of the feature encoder can encode all features into increasingly dense and informative representation vectors without any ``intelligent processing'' on them. (4)~We compare the performance of the representations from audio models and BERT on text features. This is the first work to check the representative capacity of audio representations for the text captured by audio. We find that despite of having no text-specific error metrics, the audio models are able to encode text well and are comparable to BERT on several parameters. We find that the dataset used to pre-train audio models has a significant effect on downstream performance. To the best of our knowledge, this is the first attempt towards interpreting audio transformer models\footnote{We will release our code, datasets and tools used to perform the experiments and inferences upon acceptance.}. The conclusion points out that the transformers are able to learn a holistic range of features, which enable them to perform with great accuracy on various downstream tasks even training solely on unlabeled speech. \section{Brief Overview Of The Probed Models} \label{sec:Brief Overview Of The Probed Models} We probe three recent transformer based models: wav2vec2.0\xspace, Mockingjay\xspace and BERT. Below, we give a brief overview of the three models and their high-level architectures. \subsection{wav2vec2.0} \label{sec:wav2vec2.0} \begin{figure*} \includegraphics[scale=0.75]{mockingjay.pdf} \caption{Mockingjay Architecture} \end{figure*} {wav2vec2.0\xspace} is a recent transformer based speech encoding model. It is composed of 3 major components - the feature encoder, the transformer, and the quantization module. The feature encoder consists of a multi-layer convolutional network which converts the raw input audio input $X$ to latent representation ${Z_{1}, Z_{2},..,Z_{t}}$. These latent vectors are fed into the transformer to build the representations $C_{1},C_{2},...C_{n}$. The training is done by masking certain time-steps in the latent feature representation and learning a contrastive task over it. The contrastive task requires finding the correct quantized representation corresponding to the masked latent audio representation amongst a set of distractors. The contrastive task targets ($q_t$) are built by passing the output of feature encoder to the quantizater at various time steps. The model is pretrained on unlabeled Librispeech data \cite{panayotov2015librispeech} and then finetuned on TIMIT \cite{garofolo1993darpa} dataset for phoneme recognition. It achieves a 1.8/3.3 WER on the clean/noisy test sets on experiments using all labeled data of Librispeech and 5.2/8.6 WER on the noisy/clean test sets of Librispeech using just ten minutes of labeled data. The authors claim that even while lowering the amount of labeled data to one hour, wav2vec2.0\xspace outperforms the previous state of the art on the 100 hour subset while using 100 times less labeled data. All our experiments are based on the wav2vec2.0\xspace-base model in which the feature encoder contains $7$ blocks having a temporal convolution of 512 channels with strides $(5,2,2,2,2,2,2)$ and kernel widths $(10,3,3,3,3,2,2)$ respectively and the there are $12$ transformer blocks with a model dimension of $768$, inner dimension (FFN) $3,072$ and $8$ attention heads. A point to note is that the output of each of the transformer block depends on the duration of the audio file. For a moderate size audio ($\sim$5 seconds), the embedding obtained is huge in size. It is of the form $768 * T$ where T is dependent on the duration of the audio. Hence, to probe the different features, we time-average the embeddings. \subsection{Mockingjay} \label{sec:mockingjay} {Mockingjay\xspace} is a bidirectional transformer model which allows representation learning by joint conditioning on past and future frames. It accepts input as 160 dimension log-Mel spectral features\footnote{For a primer on log-Mel and other audio feature extraction, refer to \cite{choi2017tutorial}} and has outperformed it for phoneme classification, speaker recognition and sentiment discrimination accuracy on a spoken content dataset by 35.2\%, 28.0\% and 6.4\% respectively. The authors claim the model is capable of improving supervised training in real world scenarios with low resource transcribed speech by presenting that the model outperformes other exisiting methods while training on 0.1\% of transcribed speech as opposed to their 100\%. For our experiments, we use the MelBase-libri model. The architecture comprises of $12$ encoder layers and each unit has 0he same output dimension of $768$ and comprises of sub-layers which include a feed-forward layer of size $3072$ and $12$ self-attention heads. We probe each of the $12$ transformer blocks of both models and the feature encoder of wav2vec2.0 to check if they learn the features of audio, fluency, suprasegmental pronunciation and text. Similar to {wav2vec2.0\xspace}, {Mockingjay\xspace} also has huge embeddings of size $768*T$ with T dependent on the size of audio. \subsection{BERT} \label{sec:BERT} BERT stands for Bidirectional Encoder Representations and proved to be a major breakthrough for NLP. The architecture basically comprises encoder layers stacked upon eachother. BERT-Base has $12$ such layers while BERT-Large has $24$. We have probed the uncased Base model. The input format to the transformer has $3$ parts - a classification token(CLS), sequence of words and a separate sentence(SEP) token. The feed-froward network has $768$ hidden units and $12$ attention heads. BERT achieves effective performance on various NLP tasks. Similar to audio models, we probe BERT extracting embeddings from each of the $12$ encoder blocks. Since, text has no time component, the embeddings are of size $768*1$. \section{Probing - Problem Definition And Setup} \label{sec:Probing - Problem Definition And Setup} Here we specify the probing model and explain how we compare the audio and text transformer models. We also give an overview of all the features and models we probe in the paper along with the datasets used. \begin{figure*} \includegraphics[scale=0.6]{probing-diagram.pdf} \caption{\label{fig:Procedure for probing audio transformers}Procedure for probing audio transformers} \end{figure*} \subsection{Probing Model} \label{sec:Probing Model} We define the problem of probing a model $M$ for a feature $f$ as a regression task using a probing model $P$. $P$ is a 3-layer feed forward neural network trained on $M$'s emebddings to predict the feature $f$. For instance, in text-transformers, a probing model ($P$) might map BERT embeddings ($M$) to syntactic features such as parts of speech ($f$) \cite{jawahar-etal-2019-bert}. Post model training, the representational capacity of embeddings is judged based on the ease with which the 3-layer feed-forward probe network is able to learn the said feature. Metrics like accuracy and MSE loss are used for measuring and comparing the representational capacities \cite{alishahi2017encoding,belinkov2017analyzing,prasad2020accents,belinkov2017neural,jawahar-etal-2019-bert}. Our probe model consists of a $3$-layer fully connected neural network with the hidden layer having a ReLU activation and dropout to avoid over-fitting\footnote{Model dimensions are $(768,128,1)$ for all the intermediate layers of Transformers and $(512,128,1)$ for the feature extractor. Adam with a learning rate of $0.0001$ is used.}. We compare the representative capacity of different audio and text transformers on the basis of the loss values reported by the prober. Furthermore, we take a randomly initialized vector as a baseline to compare against all the `intelligent' models. This approach is in line with some of the previous works in the model interpretability domain \cite{alishahi2017encoding,belinkov2017analyzing,prasad2020accents,belinkov2017neural,jawahar-etal-2019-bert}. A diagram explaining the overall process is given in the Figure~\ref{fig:Procedure for probing audio transformers}. \subsection{Feature Overview} \label{sec:Feature Overview} We test the audio transformer models on the following speech features: audio features (\S\ref{subsec:Audio Features}), fluency features (\S\ref{subsec:Fluency Features}), and pronunciation features (\S\ref{subsec:Pronunciation Features}). Since spoken language can be considered as a combination of words (\textit{what} was spoken), and language delivery (\textit{how} it was spoken), we probe audio transformer models for both speech and text knowledge. For comparing on textual representational capacity, we extract text features from the original transcripts of all the audio datasets considered (\S\ref{sec:Can Audio Models Read Too?}). A detailed description of all features extracted and their methodology of extraction is given in Section~\ref{sec:What Do Audio Transformers Hear?} (audio features) and Section~\ref{sec:Can Audio Models Read Too?} (text features). \subsection{Types of Speech Explored} \label{sec:Types of Speech Explored} Unlike text, speech varies drastically across speech types. For instance, a model developed for American (native) English speakers produces unintelligible results for Chinese (non-native) English speakers \cite{mulholland2016comparison}. Since transformer models tend to be used across multiple speech types \cite{grover2020multi,doumbouya2021using}, it is important to assess and compare their performance and bias across each of the speech types. Therefore, we test them on native read, native spontaneous, and non-native read speech corpora. For probing on native read speech, we use the LibriSpeech dataset \cite{panayotov2015librispeech}. We take the default `train-clean-100' set from LibriSpeech for training the probing model and the `test-clean' set for testing it. For native spontaneous English speech, we use the Mozilla Common Voice dataset \cite{ardila2019common}. We use a subset of $2000$ random audios for training and $200$ audios for testing. For interpreting audio transformers on non-native speech, we use L2-Arctic dataset \cite{zhao2018l2arctic}. We take $500$ audios of $4$ speakers each for training the prober and $50$ audios each for testing. The $4$ speakers are selected in such a way that there is $1$ male and $1$ female speaker each with Hindi and Spanish as their first languages. \subsection{Models Probed} \label{sec:models probed} We probe two recent audio transformers, wav2vec2.0\xspace and Mockingjay\xspace for their speech and language representational capacities. For text-based linguistic features particularly, we also compare them with BERT embeddings \cite{devlinetal2019bert}. See Section~\ref{sec:Brief Overview Of The Probed Models} for an overview of the three transformer models. Self-attention is the powerhouse which drives these transformers \cite{vaswani2017attention}. It is the main reason behind their state-of-the-art performance on diverse tasks. While Mockingjay\xspace is exclusively built of self-attention and feed-forward layers, wav2vec2.0\xspace also has several CNN layers. They are presented as ``feature extractor'' layers in the original paper (Figure~\ref{fig:wv arch}). Therefore, we also investigate the role of the feature extractor in wav2vec2.0. In particular, we investigate that whether similar to computer vision \cite{erhan2010understanding,krizhevsky2012imagenet,girshick2014rich}, do the CNN layers in speech transformers also learn low-level to high-level features in the subsequent layers. Very few studies in the speech domain have tried to answer this question \cite{zhang2018visualization}. We probe the representational capacity of embeddings from all layers of the three transformer models. This helps us understand the transformer models at four levels, \textit{i.e.}, across models, speech types, input representations (log Mel and raw audio), and layers. This analysis gives us results on a much finer level than just comparing the word error rates of the two models. It helps us to know the linguistic strengths and weaknesses of the models and how they are structuring and extracting information from audio. We also use our interpretability results to improve the performance on some downstream tasks (\S\ref{sec:Effect on Downstream Tasks}). \begin{figure*}[htbp] \centering \includegraphics[scale=0.5]{stacked_graphs.png} \caption{ \label{figure:Comparison of w2v and MJ on native read speech} \small Performance of wav2vec2.0\xspace and Mockingjay\xspace on fluency features (a1,b1), pronunciation features (a2,b2), surface level text features (a3,b3), audio features (a4,b4) (`W' denotes wav2vec2.0\xspace and `M' denotes Mockingjay\xspace). The graphs represent stacked area charts with the x-axis being the layers of the model and y-axis shows the relative performance of each layer with respect to the maximum loss for each feature \emph{((loss - min\_loss)*100\%/min\_loss)}. Hence, higher the value, higher the loss, lower the performance. \newline The feature numbers according to category are given below: \newline \textbf{Audio features:}~ \emph{1. total duration, 2. stdev energy, 3. mean pitch, 4. voiced to unvoiced ratio, 5. zero crossing rate, 6. energy entropy, 7. spectral centroid, 8. localJitter, 9. localShimmer}, \newline \textbf{Fluency features:}~\emph{1. filled pause rate, 2. general silence, 3. mean silence, 4. silence abs deviation, 5. SilenceRate1, 6. SilenceRate2, 7. speaking rate, 8. articulation rate, 9. longpfreq, 10. average syllables in words, 11. wordsyll2, 12. repetition freq}, \newline \textbf{Pronunciation features:}~\emph{1. StressedSyllPercent, 2. StressDistanceSyllMean, 3. StressDistanceMean, 4. vowelPercentage, 5. consonantPercentage, 6. vowelDurationSD, 7. consonantDurationSD, 8. syllableDurationSD, 9. vowelSDNorm, 10. consonantSDNorm, 11. syllableSDNorm, 12. vowelPVINorm, 13. consonantPVINorm, 14. syllablePVINorm}, and \newline \textbf{Semantic level text features:}~\emph{1. Total adjectives, 2. Total adverbs, 3. Total nouns, 4. Total verbs, 5. Total pronoun, 6. Total conjunction, 7. Total determiners, 8. Number of subjects, 9. Number of objects} } \end{figure*} \section{What Do Audio Transformers Hear?} \label{sec:What Do Audio Transformers Hear?} In this section, we probe audio (\S\ref{subsec:Audio Features}), fluency (\S\ref{subsec:Fluency Features}), and pronunciation (\S\ref{subsec:Pronunciation Features}) features. These features are extracted directly from the audio waveform. Amongst them, the audio features measure the knowledge of the core features of audio including energy, jitter, shimmer and duration. Fluency features measure the smoothness, rate, and effort required in speech production \cite{de2009praat,yan2018complexity}. Pronunciation features measure the intelligibility, accentedness and stress features of the audio. Tasks such as automatic scoring, readability evaluation, automatic speech generation quality, text to speech quality, accent detection, ASR models, \textit{etc.} are impacted by the fluency and pronunciation features \cite{yan2018complexity,barth2014effects,rasinski2004assessing,zhang2019learning,lee2019robust,kyriakopoulos2020automatic,jyothi2015improved}. A typical embedding of the transformers at any layer is of the size $768*T$ where T depends on the duration of the speech segment. We average it to get $768*1$ dimension embedding which serves as the representation of the speech segment for which we have extracted the features. This is then fed as the input to our probing model. Figure~\ref{fig:Procedure for probing audio transformers} depicts the process. \subsection{Audio knowledge} \label{subsec:Audio Features} \begin{table*}[] \begin{tabular}{@{}|l|l|l|@{}} \toprule \textbf{Audio feature} & \textbf{Description} & \textbf{Extracted Using}\\ \midrule \midrule Total duration & Duration of audio & Librosa \cite{mcfee2015librosa}\\ \midrule zero-crossing rate & Rate of sign changes & PyAudioAnalysis \cite{giannakopoulos2015pyaudioanalysis}\\ \midrule energy entropy & Entropy of sub-frame normalized energies & PyAudioAnalysis \cite{giannakopoulos2015pyaudioanalysis} \\\midrule spectral centroid & Center of gravity of spectrum & PyAudioAnalysis \cite{giannakopoulos2015pyaudioanalysis} \\\midrule mean pitch & Mean of the pitch of the audio & Parselmouth \cite{parselmouth,praat}\\ \midrule local jitter & Avg. absolute difference between consecutive\\ & periods divided by the avg period & Parselmouth \cite{parselmouth,praat}\\ \midrule local shimmer & Avg absolute derence been\\ & the amplitudes of consecutive periods, & Parselmouth \cite{parselmouth,praat}\\ & divided by the average amplitude & \\ \midrule voiced to unvoiced ratio & Number of voiced frames upon\\ & number of unvoiced frames & Parselmouth \cite{parselmouth,praat}\\ \bottomrule \end{tabular} \caption{ \label{table: audio feature extraction}Audio feature extraction algorithms and libraries used} \end{table*} We measure the following audio features: \emph{Total duration, zero-crossing rate, energy entropy, spectral centroid, mean pitch, local jitter, local shimmer, and voiced to unvoiced ratio}. \emph{Total duration} is a characteristic feature of the audio length that tells us about the temporal shape of the audio. The temporal feature \emph{zero crossing rate} measures the rate at which a signal moves from positive to a negative value or vice-versa. It is widely used as a key feature in speech recognition and music information retrieval \cite{neumayer2007integration,simonetta2019multimodal}. Energy features of audio are an important component that characterizes audio signals. We use \emph{energy entropy} and the standard deviation of energy (\emph{std\_dev energy}) to evaluate the energy profile of audio. \emph{Spectral centroid} is used to characterise the spectrum by its centre of mass. To estimate the quality of speech as perceived by the ear, we measure the \emph{mean pitch}. We also probe for frequency instability (\emph{localJitter}), amplitude instability (\emph{localShimmer}), and \emph{voiced to unvoiced ratio}. Table~\ref{table: audio feature extraction} mentions the libraries and algorithms used for extracting the above features. Next we present the results of our probing experiments on the two transformers for three different speech types. \textbf{Native Read Speech:} Figures~\ref{figure:Comparison of w2v and MJ on native read speech}(a4,b4)\footnote{Refer Tables~\ref{Audio_W} and \ref{Audio_M} of Appendix for loss values} shows the results obtained for audio features probed on wav2vec2.0 and Mockingjay on the Librispeech dataset. It can be seen that the lowest loss is obtained in the initial two layers for wav2vec2.0, whereas it is the final layer for Mockingjay. These results also indicate that unlike computer vision there is no uniform conception of ``high-level'' or ``low-level'' in audio transformers \cite{erhan2010understanding,krizhevsky2012imagenet,girshick2014rich}. We can see a clear ascent in the losses as we traverse the graph for wav2vec2.0 from left to right, \emph{i.e.}, from lower layers to the higher layers. This suggests that as we go deeper into the $12$ block transformer model the audio features are diluted by wav2vec2.0\xspace. Mockingjay\xspace, on the other hand, follows a negative slope for its losses from the first to the last layers. Hence, the audio features are best captured in the final layers of the Mockingjay model. When comparing the minimum losses across both models, the average learning of these features for wav2vec2.0\xspace is better than that of Mockingjay\xspace by $28.59\%$. Even with the final layer embedding, wav2vec2.0 performs better than Mockingjay by $24.53\%$. This is interesting given that the final layer of wav2vec2.0 contains the most diluted version of the learned features and Mockingjay has its best version (in the final layers). Therefore, wav2vec2.0\xspace has richer audio representations compared to Mockingjay\xspace. \begin{figure*} \includegraphics[scale=0.5]{Audio.png} \caption{Performance of each audio feature (on the y-axis) relative to the performance of random embeddings on the three speech types (native read, native spontaneous, and non native speech). X-axis represent the MSE loss values relative to random embeddings loss \emph{(loss*100/l2\_random\_loss)}.} \label{figure: w2v and mj on audio features compared with random embeddings} \end{figure*} \textbf{Native Spontaneous Speech:} For native spontaneous speech, as shown in Figure~\ref{figure: w2v and mj on audio features compared with random embeddings}\footnote{Refer Tables~\ref{nsAudio_W} and \ref{nsAudio_M} of Appendix for loss values}, wav2vec2.0\xspace is observed to perform better than Mockingjay\xspace. Wav2vec2.0, on an average performs better by $41.69\%$ when compared across the best performing layers and $51.12\%$ when end layer losses are compared. The pattern of the best performing layer also remains the same as the case of native read speech for Mockingjay\xspace. For wav2vec2.0, native read speech was best captured in the initial $2$ layers, but for spontaneous speech, the layers are a bit more spread out across the initial half of the transformer model. We also observe that the loss values on native spontaneous speech are higher than the ones for native read and non-native read corpora. \textbf{Non-native Speech:} When tested on L2 speakers (Figure~\ref{figure: w2v and mj on audio features compared with random embeddings}\footnote{Refer Tables~\ref{nAudio_W},~\ref{nAudio_M} of Appendix for loss values}), wav2vec2.0 outperforms Mockingjay by $9.53\%$ and $12.51\%$ on minimum and end layer losses, respectively. Additionally, similar to the case of native read speech, Mockingjay learns the audio features best in the final layers. As for wav2vec2.0, the layers learning the audio features are spread out with the initial half of the model learning them more accurately than the later half. \subsection{Fluency knowledge} \label{subsec:Fluency Features} To the best of our knowledge, we use the features that measure fluency for the first time in this paper. The key features of fluency are: rate of speech, pauses, and length of runs between pauses \cite{yan2018complexity}. To measure the rate of speech, we measure the speech rate (number of words per second in the total response duration) (\emph{speaking\_rate}) and articulation rate (number of words per second in the total articulation time, \emph{i.e.,} the resulting duration after subtracting the time of silences and filled pauses from the total response duration) (\emph{articulation\_rate}) \cite{wood2001search}. Apart from these rates, pauses in speech are the second most observable feature to indicate disfluency \cite{igras2016structure}. Therefore, we measure the duration, location and frequency of pauses as prototypical features. For this, we measure the number of filled pauses per second - (\emph{filled\_pause\_rate}), \emph{silence deviation} (absolute difference from the mean of silence durations), which along with the total duration of the audio helps to indicate the length of runs between the pauses \cite{mohle1984comparison}. This also serves an important indicator for fluency. Other features include total number of silences (\emph{general silence}), mean duration of silences (\emph{mean\_silence}), average silence per word (\emph{SilenceRate1}), average silence per second (\emph{SilenceRate2}) and number of long silence per word (\emph{longpfreq}). \begin{table*}[] \begin{tabular}{@{}|l|l|@{}} \toprule \textbf{Fluency feature} & \textbf{Description}\\ \midrule \midrule Filled pause rate & Number of filled pauses (uh, um) per second \cite{parselmouth,praat}\\ \midrule General silence & Number of silences where silent duration between two words \\ & is greater than 0.145 seconds \\ \midrule Mean silence & Mean duration of silence in seconds \\ \midrule Silence abs deviation & Mean absolute difference of silence durations \\ \midrule Silence rate 1 & Number of silences divided by total number of words\\ \midrule Silence rate 2 & Number of silences divided by total response duration in seconds \\ \midrule Speaking rate & Number of words per second in total response duration\\ \midrule Articulation rate & Number of words per second in total articulation time (i.e. the resulting \\ & length of subtracting the time of silences and filled pauses from the \\ & total response duration).\\ \midrule Long pfreq & Number of long silences per word\\ \midrule Avg syllables in words & Get average count of syllables in words after removing all stop words\\ & and pause words.\\ \midrule Word syll2 & Number of words with syllables greater than two\\ \midrule Repetition freq & Frequency of repetition by calculating number of repetition\\ & divided by total number of words.\\ \bottomrule \end{tabular} \caption{ \label{table: fluency feature extraction}Fluency feature extraction algorithms and libraries used for extracting them are numpy, textgrids. } \end{table*} Furthermore, conversational fillers are a major source of disfluency. Sounds like \emph{uh, um, okay, you know, etc} are used to bring naturalness and fluency to their speech. The extent of fillers is an important feature to check for speech fluency. We use the average number of syllables in a word (\emph{average\_syllables\_in\_word}), the number of words with syllables greater than 2 (\emph{wordsyll2}) and the repetition frequency (\emph{repetition\_freq}), to measure this. \begin{figure*} \includegraphics[scale=0.5]{Fluency.png} \caption{\label{Fluency}Performance of each fluency feature (on the y-axis) relative to the the performance of random embeddings on L2 Arctic data features \emph{(loss*100/l2\_random\_loss)} on the x-axis where loss values are that of MSE} \end{figure*} \textbf{Native Read Speech:} For fluency based features on native read speech, similar to audio features, wav2vec2.0 performs better than Mockingjay (Figures~\ref{figure:Comparison of w2v and MJ on native read speech} (a1) and (b1)\footnote{Refer Tables \ref{Fluency_W} and \ref{Fluency_M} of Appendix for loss values}). While the fluency features are not layer specific but are spread across the model for Mockingjay, they tend to show the best performance in the middle layers for wav2vec2.0. With the final layer embeddings of both models, wav2vec2.0 performs better than Mockingjay by $12.23\%$. The performance gap increases by four folds to $42.37\%$ when compared on the minimum losses (among all observed for the intermediate layers) learnt by both models. \textbf{Non-native Speech:} For the L2 Arctic dataset (\footnote{Refer Tables \ref{nFluency_W} and \ref{nFluency_M} of Appendix for loss values}), the learning of fluency features is concentrated in the middle layers for wav2vec2.0. Moreover, here we see a definite pattern that Mockingjay is learning better in the final layers compared to the no pattern observed in the case of Librispeech. Overall, wav2vec2.0 outperforms Mockingjay by $5.06\%$ on the minimum loss layers but by $105.62\%$ for the final layers. Thus, {wav2vec2.0\xspace} heavily outperforms {Mockingjay\xspace} on non-native speech settings. \subsection{Pronunciation Features} \label{subsec:Pronunciation Features} \begin{table*}[ht] \begin{tabular}{@{}|l|l|@{}} \toprule \textbf{Pronunciation feature} & \textbf{Description} \\ \midrule \midrule StressedSyllPercent & Relative frequency of stressed syllables in percent\\ \midrule StressDistanceSyllMean & Mean distance between stressed syllables in syllables\\ \midrule StressDistanceMean & Mean distance between stressed syllables in seconds\\ \midrule vowelPercentage & Percentage of speech that consists of vowels\\ \midrule consonantPercentage & Percentage of speech that consists of consonants\\ \midrule vowelDurationSD & Standard Deviation of vocalic segments\\ \midrule consonantDurationSD & Standard Deviation of consonantal segments\\ \midrule syllableDurationSD & Standard Deviation of syllable segments\\ \midrule vowelSDNorm & Standard Deviation of vowel segments divided by mean\\ & length of vowel segments\\ \midrule consonantSDNorm & Standard Deviation of consonantal segments divided by\\ & mean length of consonant segments\\ \midrule syllableSDNorm & Standard Deviation of syllable segments divided by mean\\ & length of syllable segments\\ \midrule vowelPVINorm & Raw Pairwise Variability Index for vocalic segments\\ \midrule consonantPVINorm & Raw Pairwise Variability Index for consonantic segments\\ \midrule syllablePVINorm & Raw Pairwise Variability Index for syllable segments\\ \midrule \bottomrule \end{tabular} \caption{ \label{table: pronunciation feature extraction}Pronunciation feature extraction algorithms and these can extracted easily using the libraries- numpy, textgrids, operator, re, itertools and counter. } \end{table*} Similar to fluency features, we are the first to probe pronunciation features in speech. The intelligibility, perceived comprehensibility, and accentedness of speech are impacted by phonemic errors \cite{derwing1997accent}. Segmental pronunciation is judged based on the amount of listener effort with lower being the better. Hence, we probe the models for the following pronunciation characteristic features - the percentage, standard deviation, duration and Normalized Pairwise Variability Index (PVI) for vowels (\emph{vowelPercentage, vowelDurationSD, vowelSDNorm, vowelIPVINorm}), consonants (\emph{consontantPercentage, consontantDurationSD, consonantSDNorm, consonantIPVINorm}), and syllables (\emph{syllableDurationSD, syllableSDNorm, syllablePVINorm}). We also study the presence of stress with the characteristic features of stress syllables distance mean (\emph{stressDistanceMean}), and stress distance mean (\emph{stressDistanceSyllMean}). \begin{figure*} \includegraphics[scale=0.5]{Pronunciation.png} \caption{\label{Pronunciation}Performance of each pronunciation feature (on the y-axis) relative to the the performance of random embeddings on L2 Arctic data features \emph{(loss*100/l2\_random\_loss)} on the x-axis where loss values are that of MSE.} \end{figure*} \textbf{Native Read Speech:} Figures~\ref{figure:Comparison of w2v and MJ on native read speech}(a2) and (b2)\footnote{Refer Tables \ref{Pron_W} and \ref{Pron_M} of Appendix for the loss values} show the results for probing pronunciation features on wav2vec2.0 and Mockingjay with the Librispeech data. These features are learnt best by the last layers in Mockingjay. Wav2vec2.0 learns these features the most in the 6\textsuperscript{th} to 8\textsuperscript{th} layers amongst its $12$ layers. Mockingjay performs better for pronunciation-based features than wav2vec2.0 by $30.4\%$ in the final layer embeddings. Comparing the minimum loss layers for both models, the difference is $16.19\%$ in favor of Mockingjay. \textbf{Non-native Speech:} Mockingjay follows the same pattern for L2 Arctic dataset as for the Librispeech dataset. It learns these features better in the last layers. However, for wav2vec2.0, the layers learning each of these pronunciation features are more spread out across the initial layers of the second half of the model. Wav2vec2.0 outperforms Mockingjay but the differences here are reduced to $8.9\%$ in the end layer and $2.20\%$ in the best performing layer. This pattern follows the non-native speech performance of {wav2vec2.0\xspace} and {Mockingjay\xspace} seen with audio and fluency features. Here too, the performance difference between {wav2vec2.0\xspace} and {Mockingjay\xspace} widens when compared to the native speech scenario. \subsection{Feature Extractor Module of {wav2vec2.0\xspace}} As shown in Figure~\ref{fig:wv arch}, {wav2vec2.0\xspace} has 7 convolutional layers before the transformer encoder block. The authors call it the ``feature extractor'' of wav2vec2.0\xspace. While in the computer vision community, it has been shown that subsequent layers of a CNN architecture look for higher level features, in the speech community this question has largely been left unaddressed \cite{erhan2010understanding,gong2018deep}. We find that there is a uniform increase in performance of the subsequent CNN layers for all feature types (audio, fluency, and pronunciation) and there is no difference between any features with respect to ``high-level'' or ``low-level''. Figure~\ref{feature_extractor} shows this behavior for audio features(which are supposed to be best learnt by feature extractor of audio transformer). The CNN layers faithfully extract all the features and show minimum loss at the seventh layer or the post-projection layers. \begin{figure*} \includegraphics[scale=0.5]{fe_ext.png} \caption{\label{feature_extractor}Performance of audio features on the various layers of Feature Extractor} \end{figure*} \section{Can Audio Models Read Too?} \label{sec:Can Audio Models Read Too?} Speech combines the text and the audio parts of the language. Conventionally, the audio community (which also deals with speech) has been more involved with signal sciences while the NLP community has dealt with the text part of speech while ignoring audio. This approach is suboptimal. However, due to the impressive performance of self-supervised transformers in every domain, there is a newfound interest in learning task-independent representations. Concurrently, there is also an interest in learning how these representations are working. Therefore, we probe to check whether the self-supervised audio transformers on account of their self-supervision tasks have accumulated some knowledge present in the text as well. With this motivation, we probe the audio transformer representations for surface (\S\ref{sec:surface level features}), syntax (\S\ref{sec:syntax level features}) and semantic (\S\ref{sec:semantic level features}) knowledge. For reference, we compare them with BERT based text-only embeddings. We use random embeddings as baseline. We do the experiments for four speech types (native read, native spontaneous, non-native, and artificial speech). While the surface features measure the non-linguistic surface knowledge of the encoders, syntax features measure the syntax based linguistic properties. Conneau \textit{et al.} \cite{conneau2018you} include features such as sentence length and word content in surface features and syntax tree depth in syntax feature. The other category of features we measure are semantics features in which we include number of objects and subjects \cite{conneau2018you}. \begin{table*}[ht] \begin{tabular}{@{}|l|l|@{}} \toprule \textbf{Text feature} & \textbf{Description}\\ \midrule \midrule \textbf{Surface Features} \\ \midrule Unique word count & Total count of unique words(Ignore words of length 3 or smaller)\\ \midrule Word Complexity & Sum of word complexities for all words in text given by annotators\\ \midrule \textbf{Semantic Features} \\ \midrule Total adjectives & Total count of adjectives \\ \midrule Total adverbs & Total count of adverbs\\ \midrule Total nouns & Total count of nouns\\ \midrule Total verbs & Total count of verbs\\ \midrule Total pronouns & Total count of pronouns\\ \midrule Total conjunction & Total count of conjunction\\ \midrule Total conjunction & Total count of conjunction\\ \midrule Number of subject & Total count of subject\\ \midrule Number of Object & Total count of direct objects\\ \midrule Tense & Classification of main clause verb into present or past tense\\ \midrule \textbf{Syntax Feature} \\ \midrule Depth of syntax tree & Depth of syntax tree of the text\\ \bottomrule \end{tabular} \caption{ \label{table: Text feature extraction}Text feature extraction algorithms extracted using nltk and numpy libraries } \end{table*} \subsection{Surface Level Features} \label{sec:surface level features} Surface level features measure the surface properties of sentences. No linguistic knowledge is required for these features. They can be measured by just looking at the tokens \cite{conneau2018you}. We include the following features - \emph{unique word count} and the average word complexity (\emph{Word Complexity}) since the lexical diversity of spoken speech is an important metric to evaluate its quality \cite{read2006investigation}. \textbf{Native Read Speech}: When compared on LibriSpeech, surface-based features are learnt better by Mockingjay than wav2vec2.0 by $9.99\%$ and (b3)\footnote{Refer Tables~\ref{Vocab_W} and \ref{Vocab_M} of Appendix for the loss values}. These features are learnt best in the intermediate layers in wav2vec2.0 and initial layers in Mockingjay. From the results, we observe that the text understanding of both models becomes increasingly diffused as we go towards the later layers. However, wav2vec2.0 outperforms Mockingjay by $3.01\%$ in the final layer. A contributing factor to these observations is the learning of surface features by Mockingjay in the initial layers while, {wav2vec2.0\xspace} learns it best in the middle layers. \textbf{Non-native Speech}: For L2 arctic data, again {wav2vec2.0\xspace} best learns the surface features in the middle layers but for mockingjay, no particular pattern is observed. The difference widens to $38.41\%$ on the end layers and $18.96\%$ on the minimum loss layer in favour of {wav2vec2.0\xspace}. \textbf{Native Spontaneous Speech}:{Mockingjay\xspace} learns best in the initial layers like in the case with native read speech meanwhile, {wav2vec2.0\xspace} performs best in the lower middle(7-11) layers. The difference increases to $141.42\%$ for native spontaneous speech on the final layer and $132.44\%$ on the best performing layer. \subsection{Semantic Level Features} \label{sec:semantic level features} The relationship between the words spoken and our comprehension of that spoken content falls into the domain of semantics. To produce meaning in a sentence, it is almost necessary for it to have a subject and a direct object that the subject addresses. The \emph{number of subjects, number of direct objects and total nouns, pronouns, adverbs, adjectives, verbs, conjunction, and determiners} are hence in our set of features to evaluate the spoken content. \cite{conneau2018you,jawahar-etal-2019-bert}. We also probe for the tense(past or present) and it is framed as a classification task unlike the rest which are regression tasks so the result for tense are separately mentioned. \begin{figure*} \includegraphics[scale=0.5]{semantic.png} \caption{\label{Vocabulary}Performance of each semantic level feature (on the y-axis) relative to the the performance of random embeddings on L2 Arctic data features \emph{(loss*100/l2\_random\_loss)} on the x-axis where loss values are that of MSE.} \end{figure*} \textbf{Native Read Speech}: wav2vec2.0 performs better in this setting by $4.173\%$ and $5.29\%$ on the minimum loss layer. Like the surface features, the pattern followed by the layers in learning is same for semantic features. Mockingjay learns them best in initial layers while wav2vec2.0 in the intermediate layers. For tense too, {wav2vec2.0\xspace} best performs with $75.04\%$ accuracy in the seventh layer where {Mockingjay\xspace} performs with $56.99\%$ in the last layer. \textbf{Non-native Speech}:The same pattern as surface features in the non-native setting is followed by both the transformers. {Mockingjay\xspace} does not follow a clear pattern but {wav2vec2.0\xspace} performs best in the middle layers. While wav2vec2.0 outperforms Mockingjay be $7.36\%$ on minimum layer loss for L2 speech, the margin decreases to $3.26\%$ on the end layer. Accuracy for tense is $57.95\%$ for {wav2vec2.0\xspace} and $52.27\%$ for {Mockingjay\xspace} on 5th and 9th layer respectively. \textbf{Native Spontaneous Speech}:{Mockingjay\xspace} does not concentrate its learning in any particular layer but {wav2vec2.0\xspace} performs best in the second half of the transformer layers. {wav2vec2.0\xspace} performs better by $9.83\%$ for native spontaneous speech on the best performing layer and $8.06\%$ on the final layer. Again for tense, the accuracy is $65.79\%$ on {wav2vec2.0\xspace} and $57.89\%$ on {Mockingjay\xspace}. \subsection{Syntax Level Features} \label{sec:syntax level features} Syntax is the key component of the grammatical structure of a sentence, which in turn is a key component of the communicative competence \cite{canale1980theoretical}. We use the \emph{depth of the syntax tree} constructed from the sentences spoken in each sound clip as a feature to evaluate the syntax content \cite{conneau2018you,jawahar-etal-2019-bert,kumar2019get}. \textbf{Native Read Speech}:In this setting as well, Mockingjay performs better than wav2vec2.0 by $38.64\%$ on the best performing layer and by $21.5\%$ on the final layer. The final layer captures this feature best for {wav2vec2.0\xspace} and the initial for {Mockingjay\xspace}, which explains the decrease in percentage difference for the final layer. \textbf{Non-native Speech}: {wav2vec2.0\xspace} performs better on minimum layer loss by $15.89\%$ and $30.92\%$ on the final layer. {wav2vec2.0\xspace} learns best on eight layer and {Mockingjay\xspace} learns best on fourth layer. \textbf{Native Spontaneous Speech}: \subsection{Feature Extractor Module of {wav2vec2.0\xspace}} \label{Feature Extractor Module of wav2vec2.0 text features} The pattern observed in the feature extractor module for these surface level features is the same as that of audio features with minimum losses seen in the post projection layer. However, the value of the minimum loss in this layer is less than that of the transformer module in wav2vec2.0. This gives some intuition for the better performance of Mockingjay since the Transformer is unable to capture the features or unlearns the presented vocabulary features. \subsection{Comparison with BERT} \begin{table*}[!htbp] \small \centering \begin{tabular}{|l|l|l|l|l|} \hline \textbf{Dataset} & \textbf{Model} & \textbf{Semantic} & \textbf{Syntax} & \textbf{Surface} \\\hline Native Read Speech & wav2vec2.0 & -43.62\%, -40.23\% & -56.90\%, -67.15\% & -59.53\%, -51.31\%\\ & Mockingjay & -41.78\%, -39.55\% & -73.57\%, -74.21\% & -52.20\%, -47.99\%\\ \hline Non-native Read Speech & wav2vec2.0 & 15.88\%, 7.35\% & 59.05\%, 30.33\% & 78.27\%, -3.94\%\\ & Mockingjay & 24.30\%, 11.14\% & 79.72\%, 33.97\% & 121.71\%, 21.30\% \\ \hline Wikipedia TTS & wav2vec2.0 & 10.22\%, -2.29\%& -34.55\%, 3.83\% & 17.70\%, -7.58\%\\ & Mockingjay & 13.87\%, -0.49\% & -47.70\%, 7.68\% & 4.04\%, 21.90\% \\ \hline \end{tabular} \vspace{1 mm} \caption{\label{table:text-feature-compared-with-bert} \small Table for comparison of the performance of BERT with wav2vec2.0 and Mockingjay on text features. The two values mentioned per cell indicate the relative minimum loss across all the model layers and the relative end layer losses when compared with the corresponding values for BERT. The values shown are an average across all features of a particular category with the relative performance calculated as $(model\_loss - bert\_loss)*100\%/bert\_loss$. } \vspace{-4 mm} \end{table*} When we compare the performance of audio-transformer models with BERT (Table~\ref{table:text-feature-compared-with-bert}) on the native read speech, we observe that on an average, both wav2vec2.0 and Mockingjay perform better than BERT by 43.62\% and 41.78\% on semantic features, 56.90\% and 73.57\% on syntactic features and 59.53\% and 52.20\% on semantic features respectively. These results are surprising since none of the speech transformer models was trained with text objective functions. We hypothesize that this could be due to differences in the train set of the three models. LibriSpeech is the train-set for both the speech-transformer models where as Wikipedia is the train-set for BERT. To confirm this, we test the performance of the three models on text features extracted from Wikipedia and native spontaneous speech datasets. These datasets provide us with a comprehensive comparison. While on one hand, Wikipedia is the train-set for BERT, and the text features from Wikipedia articles are very different from LibriSpeech, on the other, non-native read speech dataset can be considered out-of-domain for both the speech transformer models and BERT. For the first part, we convert 2000 random sentences from Wikipedia articles to speech by using Google's text-to-speech API \cite{gtts}. We made sure that the audios constructed had similar lengths as those of LibriSpeech. The audios obtained were then passed through both the speech Transformer models and the layers were then probed. On this synthetic dataset, for the semantic features, BERT outperforms both the models by more than 10\% when compared on minimum loss across all the layers. However, by the end layers, both the models learn the features well and the performance difference between BERT and audio-transformer models reduces greatly ($2.29\%$ and $0.49\%$ difference for semantic features, $3.83\%$ and $7.68\%$ for syntax and $7.58\%$ and $21.90\%$ for surface features). These results are motivating since this means that embeddings of audio Transformer captures not only audio, fluency and pronunciation features, but also textual features to a large extent. Next, we use the CMU L2 Arctic dataset. Table~\ref{table:text-feature-compared-with-bert} presents the results for all the experiments. Here the results are the most different from the previous ones. For the semantic, syntax and surface features, BERT outperforms both the models by more than $15\%$. This result when compared with Wikipedia TTS and native read speech implies that the audio models capture text features for native speakers in `cleaner settings' but they are not able to work in not-so controlled environments. Therefore, in a general setting, BERT text embeddings combined with audio embeddings can capture all the speech features adequately. \section{Effect on Downstream Tasks} \label{sec:Effect on Downstream Tasks} We wanted to evaluate our findings which show that different layers of the models capture different features and see its impact on downstream tasks. To this end, we perform two representative tasks: speaker recognition on Voxceleb \cite{nagrani2017voxceleb} (which uses audio features primarily), and phone classification on LibriSpeech (which uses pronunciation features). For speaker recognition, we randomly pick $10$ speakers with $50$ audios each in the train-set and $10$ in the test-set. For phone classification, we use the libri-clean-100 and libri-cleanTest splits. We build a 4-layer linear classifier with dimensions $756, 512, 256, 10$ with Adam optimizer and a learning rate of $0.01$. Hidden layers have ReLU activation function and the third layer also has dropout. We perform the tasks using the best performing, final, and weighted average of all layer embeddings of the transformer models as input. \begin{table}[!htbp] \small \centering \begin{tabular}{|l|l|l|l|} \hline & \textbf{Best} & \textbf{Last} & \textbf{Wtd Avg} \\\hline {wav2vec2.0\xspace} & 91\%/81\% & 31\%/70\% & 87\%/77\% \\\hline {Mockingjay\xspace} & 10\%/83\% & 32\%/83\% & 26\%/79\% \\\hline \end{tabular} \caption{\label{table:perf-downstream-tasks-wv-mj} \small Comparison of the performance of {wav2vec2.0\xspace} and {Mockingjay\xspace} on (speaker recognition/phone classification) tasks. Here \textit{best} denotes best performing layer, \textit{i.e.}, first for audio features and sixth for pronunciation for {wav2vec2.0\xspace}. } \end{table} Results for both the tasks are given in Table~\ref{table:perf-downstream-tasks-wv-mj}. The results are consistent with those found for audio (\S\ref{subsec:Audio Features}) and pronunciation features (\S\ref{subsec:Pronunciation Features}). \section{Other Related Work} \label{sec:related work} We already covered closely related work on attribution in Sections~1 and \ref{sec:Brief Overview Of The Probed Models}. We mention other related work. \textbf{Audio Probing:} In the domain of speech processing, probes have been carried out on feature vectors, neural networks like RNN or DNN, end-to-end ASR systems or Audio-visual models. In \cite{raj2019probing}, probing on x-vectors which are trained solely to predict the speaker label revealed they also contain incidental information about the transcription, channel, or meta-information about the utterance. Probing the Music Information Retrieval(MIR) prediction through Local Interpretable Model-Agnostic Explanations (LIME) by using AudioLIME \cite{haunschmid2020audiolime} helped interpret MIR for the first time. \cite{nagamine2015exploring} analyses a DNN for phoneme recognition, both at single node and poplation level. Further research on interpretation of the role of non-linear activation of the nodes of a sigmoid DNN built for phoneme recognition task is done in \cite{nagamine2016role}. Research has also been done to address why LSTMs work well as a sequence model for statistical parametric speech synthesis \cite{wu2016investigating}. Several other studies have been conducted to interpret the correlation between audio and image structures for audio-visual tasks \cite{alishahi2017encoding,drexler2017analysis,harwath2017learning}. Even for Deep ASR models, efforts have been made to comprehend the hidden and learned representations \cite{belinkov2017analyzing,elloumi2018analyzing}. However, probing of representation learning audio transformers is yet unexplored. \textbf{Text Probing:} The field of natural language processing has seen numerous efforts in understanding the inner working of large-scale transformers, especially BERT \cite{jawahar-etal-2019-bert,cui2020does,ramnath2020towards}. \citet{jawahar-etal-2019-bert} probe each of the different layers of BERT to find which layers best learn the phrase-level information, linguistic information and the long-distance dependencies. The results showed what role each layer played and the study concluded that the middle layers learnt the syntactic features and the higher levels learnt the semantic features and that the deeper layers are needed for long-distance dependencies while the initial layers capture the phrase-level information. \section{Conclusion} Speech transformer models, while still being new, have shown state-of-the-art performance on various downstream tasks. We probe two such models, wav2vec2.0 and Mockingjay, to understand what they learn. We probe the models on a wide range of features including audio, fluency, suprasegmental pronunciation, and text-based characteristics. For each category of features, we identify a learning pattern over each model and its layers. We find that {wav2vec2.0\xspace} outperforms {Mockingjay\xspace} on audio and fluency features but underperforms on pronunciation features. Furthermore, we compare BERT with the audio models with text features and find that the audio models surprisingly outperform BERT in cleaner, controlled settings of native speech, but are not able to perform in an uncontrolled environment such as of spontaneous speech and non-native speech. \begin{acks} To Robert, for the bagels and explaining CMYK and color spaces. \end{acks} \bibliographystyle{ACM-Reference-Format}
{'timestamp': '2021-07-14T02:06:19', 'yymm': '2101', 'arxiv_id': '2101.00387', 'language': 'en', 'url': 'https://arxiv.org/abs/2101.00387'}
arxiv
\section{Introduction} Early work on Vision-Language models has been largely focused on pure understanding tasks~\cite{lxmert, vilbert}. These models, although improving model performance on understanding tasks such as Visual Question Answering~\cite{vqa}, are not capable of multimodal generation tasks~\cite{caption}. To ease this problem, researchers have proposed various models~\cite{vlp, oscar} for generating texts based on visual inputs. These models are mainly pretrained on general visual and language understanding tasks such as masked language modeling and masked region modeling, which enable the models to build an alignment between visual and language features. However, only feature alignments are inadequate to enhance the model's ability in conducting complex multimodal commonsense reasoning, which requires the model to understand the underlying relations and effects between objects. Commonsense reasoning was traditionally studied on natural language~\cite{commonsense0, commonsense1}, while recent works have paid attention to commonsense reasoning with joint visual and language inputs. For instance, \citet{vcr} proposes the task of Visual Commonsense Reasoning (VCR). However, the task focuses on understanding instead of generating as it asks the model to answer multiple-choice questions. A newly introduced dataset, Visual Commonsense Generation (VCG)~\cite{vcg}, provides a more challenging task by requiring the model to generate commonsense inferences about what might happen \textit{before}/\textit{after}, and the present \textit{intents} of characters (see Table~\ref{tab:cases} for an example). In this work, we propose to tackle the task of VCG by leveraging our \textbf{K}nowledge Enhanced \textbf{M}ultimodal \textbf{BART}~\cite{bart}, which we call \textbf{KM-BART}. KM-BART is a Transformer-based model consisting of an encoder and a decoder and is pretrained on carefully designed tasks for VCG. Figure~\ref{fig:model} presents our model architecture\footnote{\url{https://github.com/FomalhautB/KM-BART-ACL}}. Our contributions in this work are three-folded: \begin{itemize} \item[1.] We extend the BART model to process multimodal data of images and texts, and enable multimodal reasoning by introducing task-relevant tokens. \item[2.] To improve the model performance on Visual Commonsense Generation (VCG), we implicitly incorporate commonsense knowledge from external knowledge graphs to our KM-BART by designing a novel pretraining task, which we call Knowledge-based Commonsense Generation (KCG). \item[3.] Besides KCG, we further equip our KM-BART with standard pretraining tasks including Masked Language Modeling (MLM), Masked Region Modeling (MRM), as well as Attribution Prediction (AP) and Relation Prediction (RP). Experimental results show that all pretraining tasks are effective, and combining these pretraining tasks enable our KM-BART to achieve state-of-the-art performance on the VCG task. \end{itemize} \section{Related Work} \subsection{Vision-Language Models}\label{sec:vl} Visual-Language (VL) tasks such as Visual Question Answering (VQA)~\cite{vqa} and Image-Text Matching~\cite{it} require the models to process multimodal inputs and comprehend visual and textual information simultaneously. Inspired by successful pretrained language models like BERT~\cite{bert} and GPT-2~\cite{gpt-2}, numerous multimodal image-text pretraining and representation learning models~\cite{lxmert, vilbert, uniter, ernie-vil} have been proposed. These multimodal pretrained models use Transformers as backbone and are denoising autoencoders trained to predict the alignment of image-text pairs and the semantics of masked words and image regions. The models mentioned above typically focus more on understanding tasks. To further bridge the gap between visual and textual clues in multimodal data, in addition to cross-modal understanding, a model should also acquire abilities to complete generation tasks, for example, the image-to-text task of Image Captioning~\cite{caption}. However, directly transferring a model pretrained on VL understanding tasks to generation tasks is infeasible, as these models are merely Transformer-based encoders and are thus not suitable for generation tasks. ~\citet{vlp} ease this problem by using a Transformer-based network as both an encoder and a decoder, making the model capable of generating texts based on visual and textual inputs. While~\citet{oscar} propose OSCAR, which improves the generation ability by introducing object tags as an additional clue during pretraining. These models achieve state-of-the-art performance in downstream multimodal generation tasks such as Image Captioning~\cite{caption}. \subsection{Commonsense Knowledge}\label{sec:common} \begin{figure*}[!t] \centering \includegraphics[width=0.95\linewidth]{images/new_model.pdf} \caption{Model architecture. Our model is based on BART. Conditioned on prompts that indicate the task type, such as \texttt{<caption>} in the figure, our model can generate texts based on visual and textual inputs from the encoder. Our model uses different special tokens to indicate task types and inform the model of different modalities of input.} \label{fig:model} \end{figure*} Commonsense knowledge refers to the necessary level of practical knowledge and reasoning about everyday situations and events common among most people~\cite{commonsense_tutorial}. For example, one should know that ``water is for drinking" and ``sunshine makes people warm". Simple as it looks, enabling artificial intelligence to conduct commonsense reasoning has been difficult for learning-based models~\cite{commonsense_literature0}. Researchers have resorted to knowledge graphs due to their exact graph-structured representation of knowledge to overcome this problem. For example, ConceptNet~\cite{concept} is a knowledge graph with nodes representing general concepts and edges indicating relational knowledge between concepts. Another commonsense knowledge graph, ATOMIC~\cite{atomic}, extends nodes to natural language phrases, and edges to relations such as \textit{intent}, \textit{attribution}, \textit{effect}, etc. Despite improvements in modeling commonsense knowledge, graph-based methods require heavy human engineering, making it challenging to scale robustly. For instance, model performance usually deteriorates dramatically when retrieved contextual knowledge is noisy due to imperfect knowledge matching~\cite{kagnet}. Therefore, we implicitly leverage external knowledge using supervision signals inferred by COMET~\cite{comet}, which is a Transformer-based, generative model pretrained on commonsense knowledge graphs including ConceptNet and Atomic. Given a natural language phrase and a relation type, COMET generates natural language commonsense descriptions. In summary, on the one hand, existing cross-modal architectures not focusing on commonsense interpretation as their pretraining tasks are designed for multimodal understanding, making them unsuitable for the downstream VCG task. On the other hand, Transformer-based generative models such as COMET~\cite{comet} cannot generate commonsense inferences from cross-modal inputs. Therefore, in this work, we propose KM-BART to conduct the task of Visual Commonsense Generation (VCG). Our KM-BART is pretrained on a dedicated pretraining task for VCG as well as other standard pretraining tasks. Experimental results show that our KM-BART achieves state-of-the-art performance on the VCG task. \section{Methodology}\label{sec:method} In this section, we describe our methodology for Visual Commonsense Generation. Section~\ref{sec:model} gives our model architecture. Section~\ref{sec:tasks} introduces our pretraining tasks as well as our self-training based data filtering technique. \begin{table}[!t] \centering \resizebox{0.85\linewidth}{!}{% \begin{tabular}{lll} \toprule & \#\textbf{images} & \#\textbf{sentences} \\ \midrule \midrule Conceptual Captions~\cite{cc} & 2,683,686 & 2,683,686 \\ \midrule SBU~\cite{sbu} & 780,750 & 780,750 \\ \midrule COCO~\cite{coco} & 82,783 & 414,113 \\ \midrule Visual Genome~\cite{vg} & 86,461 & 4,322,358 \\ \midrule Total & 3,633,680 & 8,200,907 \\ \bottomrule \end{tabular} } \caption{Statistics of pretraining datasets.} \label{tab:dataset} \end{table} \subsection{Model Architecture}\label{sec:model} Figure~\ref{fig:model} illustrates the architecture of our KM-BART. The backbone of our model is BART~\cite{bart}, which is a Transformer-based sequence-to-sequence autoencoder. We modify the original BART to adapt the model to cross-modality inputs of images and texts. We add special tokens to adapt the model to different pretraining/evaluation tasks. In the following subsections. We give the details of our visual feature extractor, the encoder, and the decoder. \subsubsection{Visual Feature Extractor} Following previous work on Vision-Language models~\cite{lxmert, vilbert}, we use a convolution neural network pretrained on the COCO dataset to extract visual embeddings, which are subsequently fed to the Transformer-based cross-modal encoder. Specifically, we use the pretrained Masked R-CNN~\cite{rcnn} from detectron2\footnote{\url{https://github.com/facebookresearch/detectron2}}. For each image, the pretrained Masked R-CNN proposes the bounding boxes for detected objects. The area within a bounding box is a \textbf{R}egion \textbf{o}f \textbf{I}nterest (RoI). We leverage the intermediate representations of the RoIs in the Masked R-CNN to obtain fixed-size embeddings for RoIs $V = \{v_1, \dots, v_i, \dots, v_{N}\}$, where $i$ is the index to RoIs, and $N$ is the number of RoIs for an image. The visual embedding of the $i$-th RoI $v_i$ is $\bm v_i \in \mathbb{R}^d$, where $d$ is the embedding dimension. For each of the RoIs, the Masked R-CNN also outputs the class distribution $p(v_i)$, which is later used for Masked Region Modeling. \subsubsection{Cross-Modal Encoder} Following~\citet{bart}, the encoder of our model is based on a multi-layer bidirectional Transformer. We introduce special tokens to adapt it to our pretraining and downstream evaluation tasks. Specifically, each example starts with a special token indicating the task type of the current example. For our pretraining task of Knowledge-Based Commonsense Generation (see Section~\ref{sec:kcg}), we use \texttt{<before>}, \texttt{<after>}, or \texttt{<intent>} as the starting special token. For Attribution Prediction and Relation Prediction (Section~\ref{sec:ap}), we use \texttt{<region\_caption>}. Finally, for Masked Language Modeling and Masked Region Modeling, we use \texttt{<caption>}. Furthermore, to inform the model of different modalities of inputs, we add three sets of different special tokens: For images, we use \texttt{<img>} and \texttt{</img>} to indicate the start and the end of visual embeddings, respectively. For texts, we introduce different special tokens to distinguish between two sets of textual inputs: \textit{events} and \textit{captions}. Events are image descriptions which the model uses for reasoning about future/past events or present intents of characters in the commonsense generation task, while captions are for Masked Language Modeling, where linguistic information plays a more important role. Hence, to inform the model of these two types of textual inputs, we use \texttt{<event>} and \texttt{</event>} for events, and \texttt{<mlm>} and \texttt{</mlm>} for captions. In the following sections, we denote textual inputs of words and specical tokens by $W=\{w_1,..,w_T\}$, where $T$ is the length of textual inputs. For a token $w$, its embedding is $\bm e \in \mathbb{R}^d$, where $d$ is the dimension of the embeddings. \begin{table*}[!ht] \centering \resizebox{0.9\linewidth}{!}{ \begin{tabular}{cccc} \toprule \textbf{Event and image} & \textbf{Task} & \textbf{Model} & \textbf{Generated Sentence} \\ \midrule\midrule 2 is holding an envelope & & without event$^\mathsection$ & \begin{tabular}[c]{@{}c@{}}\textbf{give 1 some bad news} \\ \textbf{reassure 1} \\ \textbf{contemplate what 1 is saying to her} \end{tabular} \\ \cline{3-4} \multirow{8}{*}{\includegraphics[width=10cm]{images/example1.jpg}} & intent & with event$^\dagger$ & \begin{tabular}[c]{@{}c@{}}\textbf{see what the letter said} \\ \textbf{give mail to 1} \\ \textbf{open the envelope} \end{tabular} \\ \cline{3-4} & & ground truth & \begin{tabular}[c]{@{}c@{}}receive the envelope from 1\\ see what's inside the envelope \end{tabular} \\ \cline{2-4} & & without event$^\mathsection$ & \begin{tabular}[c]{@{}c@{}}\textbf{walk up to 1} \\ \textbf{have seen 1 in the distance} \\ \textbf{be interested in what 1 has to say} \end{tabular} \\ \cline{3-4} & before & with event$^\dagger$ & \begin{tabular}[c]{@{}c@{}}\textbf{pick the envelope up} \\ \textbf{call 1 to meet him} \\ \textbf{walk to 1} \end{tabular} \\ \cline{3-4} & & ground truth & \begin{tabular}[c]{@{}c@{}}receive mail\\ be given an envelope\\ bring the envelope with her\end{tabular} \\ \cline{2-4} & & without event$^\mathsection$ & \begin{tabular}[c]{@{}c@{}}\textbf{finish telling 1 she has a difficult time} \\ \textbf{ask 1 what the papers are for} \\ \textbf{let go of 1} \end{tabular} \\ \cline{3-4} & after & with event$^\dagger$ & \begin{tabular}[c]{@{}c@{}}\textbf{open the envelope} \\ \textbf{hand the envelope to 1} \\ \textbf{embrace 1} \end{tabular} \\ \cline{3-4} & & ground truth & \begin{tabular}[c]{@{}c@{}}read the contents of the envelope to 1\\ hand the envelope to 1\\read the love letter\end{tabular} \\ \bottomrule \end{tabular} } \caption{An example from the VCG dataset. We use nucleus sampling with $p=0.9$ during decoding. We show the inference sentences from (1) full model$^\mathsection$ without event descriptions but with images as inputs; (2) full model$^\dagger$ with event descriptions and images as inputs; (3) ground truth. \textbf{Bold} indicates inference sentences from our KM-BART ($^\dagger$ and $\mathsection$ indicate corresponding models in Table~\ref{tab:result}). Note that the bounding boxes are not given in the VCG dataset and are predicted by a pretrained Masked R-CNN. Additional examples are available in the Supplementary Material.} \label{tab:cases} \end{table*} \subsubsection{Decoder} The decoder of our model is also a multi-layer Transformer. Unlike the encoder, which is bidirectional, the decoder is unidirectional as it is supposed to be autoregressive when generating texts. The decoder does not take the visual embeddings as inputs. Instead, we use embeddings of the special token \texttt{<img\_feat>} to replace the actual visual embeddings. For Masked Region Modeling and Masked Language Modeling, we use \texttt{<cls>} to replace the masked regions or words (see Figure~\ref{fig:model}). The model should predict the masked words and the class distribution of the masked regions during pretraining. \subsection{Pretraining Tasks}\label{sec:tasks} To pretrain our model, we use four image-text datasets: Conceptual Captions Dataset~\cite{cc}, SBU Dataset~\cite{sbu}, Microsoft COCO Dataset~\cite{coco} and Visual Genome~\cite{vg}. In the remaining of this section, we use $D$ to denote the individual datasets for each of the pretraining tasks. Statistics of the datasets are given in Table~\ref{tab:dataset}. The above datasets consist of examples of parallel images and texts and are widely used in previous work~\cite{lxmert, vilbert, vlp, ernie-vil}. \subsubsection{Knowledge-Based Commonsense Generation}\label{sec:kcg} The knowledge-based commonsense generation (KCG) task aims to improve the performance of KM-BART on the VCG task. We leverage knowledge induced from COMET~\cite{comet}, which is a large language model pretrained on external commonsense knowledge graphs. Given a natural language phrase and a relation as inputs, COMET generates natural language phrases as commonsense descriptions. Relations of COMET include \texttt{xIntent}, \texttt{xWant}, \texttt{xNeed}, \texttt{xReact} and \texttt{xEffect}. We only use COMET to generate new commonsense descriptions on SBU and COCO datasets due to limits in computational power for pretraining. For each image-text pair, we use COMET to generate commonsense descriptions from the text using all five relations mentioned above. To adapt COMET generated commonsense knowledge to VCG, we consider relations \texttt{xIntent} and \texttt{xWant} from COMET as \textit{intent}, \texttt{xNeed} as \textit{before}, \texttt{xReact} and \texttt{xEffect} as \textit{after}. In this way, we generate additional commonsense knowledge for SBU and COCO datasets. The newly generated dataset has more than 3.6 million examples (Table~\ref{tab:reason_data}). However, the generated commonsense knowledge is not always reasonable as only textual information is used while the visual information is completely ignored. To ease this problem, we further filter the dataset by employing a self-training based data filtering strategy. \noindent\textbf{Self-Training Based Data Filtering} Our strategy aims to filter the generated commonsense knowledge dataset so that the examples in the filtered dataset closely resemble the examples in the VCG dataset. To achieve this goal, we first initialize our KM-BART with BART parameters and finetune KM-BART on the VCG dataset for 30 epochs. The finetuned KM-BART already has a good performance on the VCG dataset with a CIDER score of 39.13 (see Table~\ref{tab:result}). We then leverage this finetuned model to evaluate the quality of commonsense descriptions generated by COMET. We feed the corresponding images, texts, and relations as inputs to the finetuned KM-BART and then compute the cross-entropy (CE) loss of COMET generated commonsense descriptions. We observe that commonsense descriptions with a lower CE loss make more sense than those with a higher CE loss. Notice that when computing the CE loss of the COMET generated commonsense descriptions, our KM-BART leverages both the textual inputs and the visual inputs. We provide examples of our data filtering strategy in Supplementary Material. We compute CE loss for all the commonsense descriptions in the VCG dataset and the new dataset generated by COMET. Figure~\ref{fig:perplexity} shows the distributions of CE loss for the two datasets. We observe that commonsense descriptions generated by COMET result in higher CE losses, which are expected as images are completely ignored when using COMET to generate natural language commonsense descriptions. We only keep the examples of which CE loss is below 3.5. Table~\ref{tab:reason_data} shows the statistics of generated datasets before and after data filtering. By filtering, we keep only 1.46 million examples, roughly accounting for 40\% of the original examples. \begin{table}[!t] \centering \resizebox{0.7\linewidth}{!}{% \begin{tabular}{lll} \toprule & \#\textbf{Original} & \#\textbf{Cleaned} \\ \midrule \midrule SBU~\cite{sbu} & 2,032,385 & 808,425 \\ \midrule COCO~\cite{coco} & 1,653,075 & 660,020 \\ \midrule Total & 3,685,460 & 1,468,445 \\ \bottomrule \end{tabular} } \caption{Statistics of datasets before and after filtering.} \label{tab:reason_data} \end{table} \begin{figure} \center \includegraphics[width=0.75\linewidth]{images/perplexity_distribution-1.png} \caption{The distribution of the average cross-entropy on 10000 samples in the VCG dataset and our enhanced dataset. For the generated dataset, we can keep the examples of which cross entropy loss is below 3.5.} \label{fig:perplexity} \end{figure} Finally, we leverage the newly generated commonsense knowledge dataset by pretraining KM-BART on it. We expect by pretraining, the model reaches higher performance on the VCG dataset. Let ${S}=\{{w}_1,...,{w}_{L}\}$ be a commonsense description of the newly generated dataset \textit{D}, the loss function for KCG is: \begin{equation} \begin{split} & \mathcal{L}_{KCG}(\theta)=\\ & -\mathbb{E}_{({W},{V})\sim D}\sum_{l=1}^{L}\log(P_\theta({w}_l|{w}_{<l},{W},{V})) \end{split} \end{equation} \noindent where $L$ is the length of the generated sequence, $l$ is the index to individual tokens in the target commonsense description $S$, $V$ and $W$ are visual inputs and textual inputs, respectively. $\theta$ represents model parameters to be optimized. \subsubsection{Attribute Prediction and Relation Prediction}\label{sec:ap} The Visual Genome dataset consists of 2.3 million relationships and 2.8 million attributes. To utilize these data, we use the attribute prediction (AP) and the relation prediction (RP) as pretraining tasks, which enable the model to learn intrinsic properties among different objects in an image. In the AP task, we feed the output vectors of the decoder for each image feature into an MLP classifier. In the RP task, we concatenate two output vectors of the decoder for each image feature pair and feed it into another MLP classifier. We use the cross-entropy loss for both tasks. We denote the indices for AP by $1 \leq j \leq A$, the indices for RP by $1 \leq k \leq R$, where $A$ is the number of AP examples, and $R$ is the number of RP examples. We denote the label for the $j$-th AP example by $L_a(v_j)$, and the label for the $k$-th RP example as $L_r(v_{k_1}, v_{k_2})$, where $v_{k_1}$ and $v_{k_1}$ are the two RoIs of the current RP example. The loss function for the AP task is: \begin{equation} \begin{split} & \mathcal{L}_{AP}(\theta)=\\ & -\mathbb{E}_{(W, V)\sim D}\sum_{j=1}^{A} \log(P_\theta(L_{a}(v_j) \mid W, V)) \end{split} \end{equation} \noindent And the loss function for the RP task is: \begin{equation} \begin{split} & \mathcal{L}_{RP}(\theta)=\\ & -\mathbb{E}_{(W, V)\sim D}\sum_{k=1}^{R} \log(P_\theta(L_r(v_{k_1}, v_{k_2})) \mid W, V)) \end{split} \end{equation} \vspace{-0.2cm} \subsubsection{Masked Language Modeling} Following previous works~\cite{bert, roberta}, we randomly mask the input textual tokens with a probability of 15\% in the Masked Language Modeling (MLM) task. Within this 15\% of the tokens, we use \texttt{<mask>} to replace the masked token with a probability of 80\%, use a random token to replace with a probability of 10\%, and keep the masked token unchanged with a probability of 10\%. We denote the mask indices by $1 \leq {m} \leq M$, where $M$ is the number of masked tokens. We denote the masked token by $w_m$, and the remaining tokens that are not masked by ${w}_{\setminus {m}}$, the loss function for MLM is defined as: \begin{equation} \begin{split} & \mathcal{L}_{MLM}(\theta) = \\ & -\mathbb{E}_{(W, V)\sim D} \sum_{m=1}^{M} \log(P_\theta({w}_{m}|{w}_{\setminus {m}}, W, V)) \end{split} \end{equation} \subsubsection{Masked Region Modeling} In the Masked Region Modeling (MRM) task, we sample image regions and mask the corresponding feature vectors with a probability of 15\%. The masked vector will be replaced by a vector filled with zeros. The model needs to predict the distribution over semantic classes for the masked regions. The loss function is to minimize the KL divergence of the output distribution and the distribution predicted by the Masked R-CNN used in visual features extraction. We denote the mask indices by $1 \leq n \leq N$, where $N$ is the number of masked regions. We let $p({v}_n)$ denote the class distribution of the masked region ${v}_n$ detected by Masked R-CNN, $q_\theta(v_n)$ denote the class distribution output by our model, the loss function for MRM is then: \begin{equation} \begin{split} & \mathcal{L}_{MRM}(\theta) = \\ & \mathbb{E}_{(W,V)\sim D} \sum_{n=1}^{N} D_{KL}(p({v}_n)||q_\theta({v}_n))) \end{split} \end{equation} \subsubsection{Combining Losses} To combine all the losses we described above, we weight each of the losses by $W_{KCG}, W_{AP}, W_{RP}, W_{MLM}, W_{MRM} \in \mathbb{R}$. The weights are chosen to roughly balance every term during the training phase. The final loss is: \begin{equation} \begin{split} \mathcal{L} = \ & W_{KCG} \mathcal{L}_{KCG} + W_{AP}\mathcal{L}_{AP} + W_{RP}\mathcal{L}_{RP} + \\ & W_{MLM}\mathcal{L}_{MLM} + W_{MRM}\mathcal{L}_{MRM} \end{split} \end{equation} \begin{table}[!t] \centering \resizebox{1.0\linewidth}{!}{% \begin{tabular}{lcccccc} \toprule \textbf{Pretraining Task(s)} & \textbf{Event} & \textbf{BLEU-2} & \textbf{METEOR} & \textbf{CIDER} & \textbf{Unique} & \textbf{Novel}\\ \midrule \midrule \textit{\textbf{Random init}} & & & & & & \\ \midrule w/o pretraining & Y & 22.28 & 14.55 & 36.49 & 27.81 & 29.71 \\ KCG & Y & 22.16 & 14.52 & 37.06 & {33.01} & 31.20\\ KCG (before filtering)& Y & 22.24 & 14.43 & 37.08 & \textit{33.64} & 31.37\\ AP \& RP & Y & 22.49 & 14.64 & 37.18 & 28.97 & 30.28 \\ MLM \& MRM & Y & 22.44 & 14.70 & 37.44 & 31.16 & \textit{31.64} \\ Full Model & Y & \textbf{-} & \textbf{-} & \textbf{-} & \textbf{-} &\textbf{-}\\ \midrule \textit{\textbf{BART init}} & & & & & &\\ \midrule w/o pretraining & Y & 22.86 & \textbf{15.17} & 39.13 & 27.41 & 28.32\\ {KCG} & Y & \textbf{23.47} & \textit{15.02} & \textbf{39.76}& 27.28 & 27.97 \\ KCG (before filtering)& Y & 22.90 & 14.98 & 39.01 & 26.59 & 27.13\\ AP \& RP & Y & 22.93 & 14.99 & 39.18 & 28.06 & 28.88\\ MLM \& MRM & Y & 23.13 & 14.93 & 38.75 & 28.68 & 28.74\\ \textbf{Full Model}$^\dagger$ & Y & \textit{23.25} & 15.01 & \textit{39.20} & \textbf{35.71} & \textbf{32.85}\\ \midrule\midrule \textit{\textbf{Random init}} & & & & & & \\ \midrule w/o pretraining & N & 13.54 & 10.14 & 14.87 & 12.19 & 24.22 \\ KCG & N & 13.64 & 10.12 & 15.34 & 15.95 & 25.79 \\ KCG (before filtering)& N & 13.67 & 10.13 & 15.22& 16.47 & 24.97 \\ AP \& RP & N & 13.83 & 10.28 & 15.48 & 14.60 & 24.75 \\ MLM \& MRM & N & \textit{14.36} & \textit{10.73} & \textit{16.72} & {15.86} & {26.12} \\ \textbf{Full Model}$^\mathsection$ & N & \textbf{14.49} & \textbf{10.86} & \textbf{17.37} & \textit{16.89} & {25.69}\\ \midrule \textit{\textbf{BART init}} & & & & & & \\ \midrule w/o pretraining & N & 8.108 & 8.673 & 6.335 & 4.850 & 10.55 \\ KCG & N & 13.28 & 10.06 & 14.17 & 13.08 & 25.70\\ KCG (before filtering)& N& 13.29 & 10.12 & 13.93 & 13.51 & 25.59\\ AP \& RP & N & 12.17 & 9.503 & 12.49 & \textbf{20.98} & \textbf{29.01} \\ MLM \& MRM & N & 13.36 & 10.22 & 14.52 & 15.02 & \textit{28.36}\\ Full Model & N & \textbf{-} & \textbf{-} & \textbf{-} & \textbf{-} & \textbf{-}\\ \bottomrule \end{tabular} } \caption{Results of different pretraining tasks on VCG validation set. To speed up comparison between different pretraining tasks, we use greedy decoding to generate one inference sentence per example. \textbf{Bold}: best performance. \textit{Italic}: second best performance. \textbf{Event}: whether or not event descriptions are used during \textbf{training and evaluation}.} \label{tab:result} \end{table} \section{Experiments} We describe our experiments in this section. Section~\ref{sec:settings} is the experimental settings of different pretraining and initialization strategies. Section~\ref{sec:metric} gives the evaluation task and metrics. We show our results in Section~\ref{sec:result}. In Section~\ref{sec:example}, we give example inferences generated by our model. We have the human evaluation results in Section~\ref{sec:human}. \subsection{Settings}\label{sec:settings} In our experiments, following the base model from~\citet{bart}, we fix the model architecture to a 6-layer encoder and a 6-layer decoder. To understand how each pretraining task helps model performance on the downstream task of VCG, we ablate on pretraining tasks. We use the following experimental settings: (1) Without any pretraining; (2) Only with Knowledge-based Commonsense Generation; (3) Only with Attribute Prediction and Relation Prediction; (4) Only with Masked Language Modeling and Masked Region Modeling; (4) With all the pretraining tasks combined. For only with Knowledge-based Commonsense Generation, we further compare the model performance before and after data filtering (see Section~\ref{sec:kcg}). For each of the above settings, we initialize the model from random or from BART weights, respectively. Besides, we are most interested in the model performance under two settings (see the second column of Table~\ref{tab:result}): (1) Only using images as inputs; (2) Using both images and event descriptions as inputs. Note that when only using images as inputs for evaluation, we also do not use textual inputs during pretraining/finetuning. \begin{table*}[!t] \centering \resizebox{0.75\linewidth}{!}{% \begin{tabular}{lccccccc} \toprule & \textbf{Modalities} & \textbf{Event} & \textbf{BLEU-2} & \textbf{METEOR} & \textbf{CIDER} & \textbf{Unique} & \textbf{Novel}\\ \midrule \midrule \multirow{2}{*}{\citet{vcg}$^{a\ast}$} & \multirow{2}{*}{\shortstack[c]{Image+Event+\\Place+Person}} & \multirow{2}{*}{N} & \multirow{2}{*}{\textbf{10.21}} & \multirow{2}{*}{\textbf{10.66}} & \multirow{2}{*}{\textbf{11.86}} & \multirow{2}{*}{\textit{33.90}} & \multirow{2}{*}{\textit{49.84}}\\ & & & & & & & \\ \citet{vcg}$^{b\ast}$ & Image & N & 6.79 & 7.13 & 5.63 & 26.38 & 46.80\\ \textbf{Ours}$^\mathsection$ & Image & N & {\textit{9.04}} & {\textit{8.33}} & {\textit{9.12}} & \textbf{50.75} & \textbf{52.92}\\ \midrule \midrule \multirow{2}{*}{\citet{vcg}$^{c\ast}$} & \multirow{2}{*}{\shortstack[c]{Image+Event+\\Place+Person}} & \multirow{2}{*}{Y} & \multirow{2}{*}{\textit{13.50}} & \multirow{2}{*}{\textbf{11.55}} & \multirow{2}{*}{\textit{18.27}} & \multirow{2}{*}{\textit{44.49}} & \multirow{2}{*}{\textit{49.03}}\\ & & & & & & & \\ \citet{vcg}$^{d\ast}$ & {Image+Event} & {Y} & 12.52 & 10.73 & 16.49 & 42.83 & 47.40\\ \textbf{Ours}$^\dagger$ & Image+Event & Y & \textbf{14.21} & \textit{11.19} & \textbf{21.23} & \textbf{57.64} & \textbf{58.22}\\ \bottomrule \end{tabular} } \caption{Results on VCG validation set with nucleus sampling. Following~\citet{vcg}, we use nucleus sampling with $p = 0.9$ to generate five inference sentences for each example during evaluation. $^{\ast}$: we directly use evaluations from~\citet{vcg}. \textbf{Bold}: best performance. \textit{Italic}: second best performance. \textbf{Modalities}: information used during training. \textbf{Event}: whether or not event descriptions are used during \textbf{evaluation}.} \label{tab:comparison} \end{table*} \subsection{Evaluation Task and Metrics}\label{sec:metric} We evaluate our model on the recently proposed Visual Commonsense Generation (VCG) Dataset~\cite{vcg}. Given an image and a description of the event in the image, the task aims to predict events which might happen \textit{before/after}, and the present \textit{intents} of the characters in the given image. The dataset consists of 1174K training examples and 146K validation examples. Some examples in the dataset share the same images or events, but with different inferences for events before/after or intents at present. Table~\ref{tab:cases} gives an example of the dataset. We report our model performance on the validation set as the test set is not available yet. Besides event descriptions, the VCG dataset also provides Place and Person information for each image. Note that although~\citet{vcg} also leverages the Place and Person information for training and evaluation, we argue that such information is not generally available in normal settings, where only images and event descriptions are given. Hence, we do not use the Place and Person information in our KM-BART. As an additional reference, we nevertheless show in Table~\ref{tab:comparison} the best performed models from~\citet{vcg}, which also use Place and Person information. We use three automatic evaluation metrics, including \textbf{BLEU-2}~\cite{bleu}, \textbf{METEOR}~\cite{meteor}, and \textbf{CIDER}~\cite{cider}. Following~\citet{vcg}, we also report \textbf{Unique} as the number of inference sentences unique in generated sentences divided by the total number of sentences, and \textbf{Novel} as the number of generated sentences not in the training data divided by the total number of sentences. \subsection{Results}\label{sec:result} We first ablate on different pretraining tasks to understand the effect of each task. We then combine all the pretraining tasks together to train our full model. As a last step, we pick the best performed models to compare against previous state-of-the-art system~\cite{vcg}. Table~\ref{tab:result} shows the effect of each pretraining task to our KM-BART on the VCG dataset. We can see that all our pretraining tasks help improve model performance. Most importantly, we observe that although filtering on the commonsense generation pretraining task reduces the dataset size by more than 60\%, pretraining with KCG still reaches comparable or better performance than pretraining with KCG (before filtering). This demonstrates that our self-training based filtering technique is helpful, as it helps the model reach similar or even better performance with less training data. The advantage is most evident when we initialize from BART parameters and use both images and event descriptions as inputs. Under this setting, pretraining with KCG outperforms pretraining with KCG (before filtering) in terms of all the evaluation metrics. For using both images and event descriptions as inputs, the model performs better when initialized from pretrained BART parameters. As pretrained BART can better leverage the information in the event descriptions. Hence, to obtain our full KM-BART model for using images and events as inputs, we adopt the setting of initializing from BART parameters. Experimental results show that our full model$^\dagger$ reaches high performance on BLEU-2, METEOR and CIDER, and that the full model$^\dagger$ generates the most unique and novel inferences. For using only images as inputs, models initializing from random parameters outperforms those initialized from BART parameters. We argue that initializing from BART parameters results in optimization disadvantages where the model has to switch from pure textual inputs to pure visual inputs. This observation becomes evident as the model performs the worst when no pretraining is used, which indicates that the model has to entirely rely on finetuning on the VCG dataset to adapt to visual inputs. Therefore, for using only images as inputs, we obtain our full KM-BART model by initializing from random parameters. Our full model$^\mathsection$ reaches best performance on BLEU-2, METEOR and CIDER, and is the second best in terms of Unique. In Table~\ref{tab:comparison}, we compare our full model to previous state-of-the-art~\cite{vcg}.\footnote{Note that model performance in Table~\ref{tab:comparison} is not directly comparable to that of Table~\ref{tab:result} as we use different decoding strategies to generate different number of inference sentences per example in these two tables.} We observe that although our full model$^\dagger$ taking as inputs images and event descriptions does not use Place and Person information, the model still outperforms previous state-of-the-art (\citet{vcg}$^c$). For using only images as inputs, our model$^\mathsection$ also performs better than previous results~(\citet{vcg}$^b$). Furthermore, our model$^\mathsection$ reaches comparable performance to~\citet{vcg}$^a$ in terms of BLEU-2, METEOR and CIDER, with much higher performance on Uniqueness and Novelty, even though our model$^\mathsection$ uses much less information during training compared to~\citet{vcg}$^a$. \subsection{Case Study}\label{sec:example} In Table~\ref{tab:cases}, we show example inferences and compare the results of our model predictions to the ground truths. The generated sentences from the model without event descriptions as inputs can already capture the most important information of commonsense. We also observe that adding event descriptions to the inputs helps the model generate more details. We gives more examples of our model in the Appendix. \subsection{Human Evaluation}\label{sec:human} \begin{table}[] \centering \resizebox{0.95\linewidth}{!}{% \begin{tabular}{lccccc} \toprule \multicolumn{1}{c}{\textbf{Models}} & \textbf{Event} & \textbf{Before} & \textbf{After} & \textbf{Intent} & \textbf{Total} \\ \midrule \midrule \citet{vcg}$^{c\ast}$ & N & 38.7 & 31.3 & 30.7 & 33.3 \\ \textbf{Ours}$^\mathsection$ & N & \textbf{61.3} & \textbf{68.7} & \textbf{69.3} & \textbf{66.7} \\ \midrule \citet{vcg}$^{c\ast}$ & Y & 48.0 & 48.0 & 38.7 & 44.9 \\ \textbf{Ours}$^\dagger$ & Y & \textbf{52.0} & \textbf{52.0} & \textbf{61.3} & \textbf{55.1} \\ \bottomrule \end{tabular}% } \vspace{-0.1cm} \caption{Human Evaluation results. We compare the inference generated by our best model under the setting of \textit{with event} or \textit{without event}. $^\dagger$ and $\mathsection$ indicate corresponding models in Table~\ref{tab:result}. We use \citet{vcg}$^{c\ast}$ for both \textit{with event} and \textit{without event} as \citet{vcg} only release the weights of this model.} \label{tab:human} \end{table} We conduct human evaluation to further understand how humans perceive the inferences generated by our KM-BART. We employ a comparison approach for a better assessment between our KM-BART and the model from~\citet{vcg}. To be specific, we randomly sample 30 examples from the VCG validation set. For each example, we use our KM-BART or the baseline model to generate 5 sets of inferences, each of which consist of the task type \textit{before}, \textit{after}, and \textit{intent}. We use two settings for our human evaluation: (1) With event: event descriptions are given as input during inference time; (2) Without event: event descriptions are \textbf{not} given during inference time. Under each of the settings we compare our KM-BART model with the mode from~\citet{vcg}. We use the same 30 examples for each model under the two settings. For each example in a task type (\textit{before}, \textit{after}, or \textit{intent}), we generate 5 inferences for one model of each setting. In total, we generate 450 inferences for each model of each setting during the human evaluation. For the same example, we use our KM-BART and the model from~\citet{vcg} to generate an inference under one of the three task types, then the workers choose the more reasonable inference from the two generated inferences. We hire three workers from Amazon Mechanical Turk\footnote{\url{https://www.mturk.com/}} to evaluate each inference. We take the majority of the three workers as the final evaluation for an inference. Among all the inferences, we use the percentage of one model better than another model as the score of that model. For example, in Table~\ref{tab:human}, the score of our model (\textbf{Ours}$^\mathsection$) is 61.3 for the task type \textit{before} when event descriptions are missing. This indicates that our model is better than the baseline model for the task type \textit{before} in 61.3\% of the cases. We also take the average over the three task types as the final score (see \textbf{Total} in Table~\ref{tab:human}). From Table~\ref{tab:human}, we can observe that our model outperforms~\citet{vcg} under both of the settings. To be specific, when event descriptions are not given, among all the inferences, our model is better than~\citet{vcg} in 66.7\% of the cases. Furthermore, our model has a lead of at least 22.6\% over~\citet{vcg} in each individual task. For example, our model generates better inferences in 68.7\% of the cases in task type \textit{after}, while the model from~\citet{vcg} is only better than our model in 31.3\% of the cases. We can obtain similar results when looking at the task type \textit{before} and \textit{intent}. When event descriptions are given, our model is still better than~\citet{vcg} in 55.1\% of all the cases. For each individual task, the advantage of our model is smaller when event descriptions are given than when event descriptions are not given, showing that our model can better capture information from the images. \vspace{-0.1cm} \section{Conclusion and Future Work} \vspace{-0.1cm} In this paper, we propose \textbf{K}nowledge Enhanced \textbf{M}ultimodal \textbf{BART} (\textbf{KM-BART}), which is a Transformer-based model capable of reasoning about and generating commonsense descriptions from cross modality inputs of images and texts. We propose the pretraining task of Knowledge-Based Commonsense Generation, which improves the reasoning ability of KM-BART by leveraging a large language model pretrained on external commonsense knowledge graphs. We use the self-training technique to filter the automatically generated commonsense descriptions. Experimental results on the VCG task show that our KM-BART pretrained on the pretraining tasks reaches state-of-the-art performance. Further human evaluation demonstrates that our KM-BART can generate commonsense inferences of high quality. For future work, we plan to further expand our pretraining dataset for Knowledge-Based Commonsense Generation by including the Conceptual Captions Dataset~\cite{cc}. Furthermore, while we argue that Place and Person information is not generally available in practical scenarios, we still plan to add Place and Person information to our model in the future. \newcommand\tableheight{8pt} \section{Implementation Details} Our KM-BART is based on HuggingFace Transformers\footnote{\url{https://huggingface.co/transformers/}} and PyTorch\footnote{\url{https://pytorch.org/}}. For all our experiments, we use PyTorch built-in automatic mixed precision to speed up training. Our model has about 141 million parameters. \subsection{Pretraining} In pretraining, we use the AdamW optimizer with a learning rate of 1e-5. We use a dropout rate of 0.1 for regularization in fully connected layers. We pretrain our model for 20 epochs under each of the pretraining settings. We conduct our pretraining on 4 Titan RTX GPUs with an effective batch size of 256. Pretraining the model with all four pretraining tasks takes around one week. For our full model, we set the loss weights $W_{KCG}, W_{AP}, W_{RP}, W_{MRM}$ to 1.0 and $W_{MLM}$ to 5.0. \subsection{Finetuning} We use the same optimizer and learning rate during finetuning on the VCG dataset. We use a larger dropout rate of 0.3 as the VCG dataset is much smaller than the entire pretraining dataset. The model converges after 30 epochs. We use a single GPU with a batch size of 64. Finetuning the model takes around 40 hours. \section{Additional Generated Examples} Table~\ref{tab:sampled} and Table~\ref{tab:greedy} show additional examples from our model on the VCG validation set. All the commonsense inferences are generated by the best performed model. \section{KCG Filtering Examples} Table~\ref{tab:filtered} shows the average cross-entropy of our model on the generated COMET sentences. Lower cross-entropy indicates the generated inference sentences are more reasonable. \begin{table}[h] \centering \resizebox{1.0\linewidth}{!}{% \begin{tabular}{ccccc} \hline \textbf{Image} & \textbf{Event} & \textbf{Task} & \textbf{Label} & \textbf{cross-entropy} \\ \hline \hline \multirow{4}{*}{\begin{tabular}[c]{@{}c@{}}\includegraphics[height=3cm]{images/8.png}\end{tabular}} & \multirow{4}{2.5cm}{A lot of people that are at the beach} & \addstackgap[\tableheight]{after} & gets sunburned & 2.755 \\ \cline{3-5} & & \addstackgap[\tableheight]{before} & to drive to the beach & 3.100 \\ \cline{3-5} & & \addstackgap[\tableheight]{intent} & to have fun & 3.398 \\ \cline{3-5} & & \addstackgap[\tableheight]{intent} & to be safe & 4.079 \\ \hline \multirow{4}{*}{\includegraphics[height=3cm]{images/2.png}} & \multirow{4}{3cm}{Children sitting at computer stations on a long table} & \addstackgap[\tableheight]{intent} & to listen to the music & 2.234 \\ \cline{3-5} & & \addstackgap[\tableheight]{before} & to have a computer & 2.847 \\ \cline{3-5} & & \addstackgap[\tableheight]{intent} & to play with the little girl & 3.710 \\ \cline{3-5} & & \addstackgap[\tableheight]{after} & gets yelled at & 4.055 \\ \hline \multirow{4}{*}{\includegraphics[height=3cm]{images/6.png}} & \multirow{4}{3cm}{A woman is wearing a pink helmet and riding her bike through the city} & \addstackgap[\tableheight]{intent} & to get to the city & 2.255 \\ \cline{3-5} & & \addstackgap[\tableheight]{after} & gets hit by a car & 2.761 \\ \cline{3-5} & & \addstackgap[\tableheight]{before} & to buy a bike & 3.052 \\ \cline{3-5} & & \addstackgap[\tableheight]{after} & gets exercise & 4.815 \\ \hline \multirow{4}{*}{\includegraphics[height=3cm]{images/7.png}} & \multirow{4}{3cm}{A baseball player preparing to throw a pitch during a game} & \addstackgap[\tableheight]{intent} & to win the game & 2.241 \\ \cline{3-5} & & \addstackgap[\tableheight]{after} & gets hit by a ball & 2.773 \\ \cline{3-5} & & \addstackgap[\tableheight]{before} & to go to the stadium & 3.222 \\ \cline{3-5} & & \addstackgap[\tableheight]{intent} & to get a tan & 4.405 \\ \hline \multirow{4}{*}{\includegraphics[height=3cm]{images/5.png}} & \multirow{4}{3cm}{An older woman riding a train while sitting under it's window} & \addstackgap[\tableheight]{before} & to go to the train station & 1.797 \\ \cline{3-5} & & \addstackgap[\tableheight]{intent} & to get off the train & 1.922 \\ \cline{3-5} & & \addstackgap[\tableheight]{intent} & to go to the park & 3.232 \\ \cline{3-5} & & \addstackgap[\tableheight]{after} & refreshed & 8.125 \\ \hline \end{tabular} } \caption{Examples of commonsense descriptions generated by COMET. Examples with lower cross entropy are more reasonable. Here ``Event" refers to captions in SBU and COCO dataset. } \label{tab:filtered} \end{table} \begin{table*}[ht] \centering \resizebox{0.9\linewidth}{!}{ \begin{tabular}{ccccc} \multicolumn{5}{c}{Event: 1 is talking to 2 a doctor} \\ \multicolumn{5}{c}{\includegraphics[width=10cm]{images/example2.jpg}} \\ \multicolumn{5}{c}{}\\ \hline Task & Ground Truth & Input & KM-BART & VCG \\ \hline \hline \multirow{4}{*}{intent} & \multirow{4}{*}{\begin{tabular}[c]{@{}c@{}}ask 2 a question\\find out medical information \end{tabular}} & without event & \begin{tabular}[c]{@{}c@{}}\textbf{go home} \\ \textbf{say goodbye to 2} \\ \textbf{hear 2's opinion} \end{tabular} & \begin{tabular}[c]{@{}c@{}}make herself felt better \\ maintain the political demeanor \\ enjoy the company of his girl friend \end{tabular} \\ \cline{3-5} & & with event & \begin{tabular}[c]{@{}c@{}}\textbf{hear the doctor's diagnosis} \\ \textbf{ask the doctor some questions} \\ \textbf{get her opinion on the procedure} \end{tabular} & \begin{tabular}[c]{@{}c@{}}talk about her injuries \\heal his leg \\ do her job as a nurse \end{tabular} \\ \hline \multirow{4}{*}{before} & \multirow{4}{*}{\begin{tabular}[c]{@{}c@{}}feel scared for her sick relative\\follow 2 into an empty room\\see 2 go into another room\end{tabular}} & without event & \begin{tabular}[c]{@{}c@{}}\textbf{take her test results} \\ \textbf{walk up to 2} \\ \textbf{enter the patient's room} \end{tabular} & \begin{tabular}[c]{@{}c@{}} decide on an outfit for the event \\ lose a bet \\ check his schedule to see what time it is \end{tabular} \\ \cline{3-5} & & with event & \begin{tabular}[c]{@{}c@{}}\textbf{meet 2 in the hospital} \\ \textbf{walk into the room} \\ \textbf{read a diagnosis} \end{tabular} & \begin{tabular}[c]{@{}c@{}}call 2 into his office \\ hear of a prescription taking \\ visit 2 in the hospital \end{tabular} \\ \hline \multirow{4}{*}{after} & \multirow{4}{*}{\begin{tabular}[c]{@{}c@{}}ask 2 how bad her condition is\\tell 2 her loved one needs help\\leave the hospital\end{tabular}} & without event & \begin{tabular}[c]{@{}c@{}}\textbf{leave the hospital} \\ \textbf{walk out the door} \\ \textbf{introduce themselves to 2} \end{tabular} & \begin{tabular}[c]{@{}c@{}} talk about something serious with 1 \\ greet the man \\ walk away" \end{tabular}\\ \cline{3-5} & & with event & \begin{tabular}[c]{@{}c@{}}\textbf{tell 2 her symptoms} \\ \textbf{get some medicine for 2} \\ \textbf{ask 2 some questions} \end{tabular} & \begin{tabular}[c]{@{}c@{}}wait patiently \\ hug 2 \\ listen to the response from 2 \end{tabular} \\ \hline \multicolumn{5}{c}{} \\ \multicolumn{5}{c}{Event: 1 is sitting at the table with 2 smoking a cigarette} \\ \multicolumn{5}{c}{\includegraphics[width=10cm]{images/example3.jpg}} \\ \multicolumn{5}{c}{} \\ \hline Task & Ground Truth & Input & KM-BART & VCG \\ \hline \hline \multirow{4}{*}{intent} & \multirow{4}{*}{\begin{tabular}[c]{@{}c@{}}smoke a cigarette\\talk with 2 about something \end{tabular}} & without event & \begin{tabular}[c]{@{}c@{}}\textbf{spend quality time with 2} \\ \textbf{stay at ease} \\ \textbf{speak to 2} \end{tabular} & \begin{tabular}[c]{@{}c@{}}have 1 shake hands \\ nod in agreement \\ do what 1 says \end{tabular} \\ \cline{3-5} & & with event & \begin{tabular}[c]{@{}c@{}}\textbf{have a smoke} \\ \textbf{get to know 2 better} \\ \textbf{get a nicotine fix} \end{tabular} & \begin{tabular}[c]{@{}c@{}}have lunch with 2 \\ satisfy his craving for nicotine \\ light up \end{tabular} \\ \hline \multirow{4}{*}{before} & \multirow{4}{*}{\begin{tabular}[c]{@{}c@{}}order food from the waiter\\take a drink from their water cup\\be seated at a table at the restaurant\end{tabular}} & without event & \begin{tabular}[c]{@{}c@{}}\textbf{order the drink} \\ \textbf{notice 2 sitting alone at the table} \\ \textbf{enter a restaurant} \end{tabular} & \begin{tabular}[c]{@{}c@{}}say bye to 1 \\ sip the drink \\ look up from the food\end{tabular} \\ \cline{3-5} & & with event & \begin{tabular}[c]{@{}c@{}}\textbf{take out a cigarette} \\ \textbf{want a light} \\ \textbf{have a seat at the table} \end{tabular} & \begin{tabular}[c]{@{}c@{}}have 2 meet him for dinner \\ get a cigarette from 2 \\ light the cigarette\end{tabular} \\ \hline \multirow{4}{*}{after} & \multirow{4}{*}{\begin{tabular}[c]{@{}c@{}}offer to help 2 get sugar for his coffee\\discuss business with 2\\watch 2 leave the restaurant\end{tabular}} & without event & \begin{tabular}[c]{@{}c@{}}\textbf{finish their meal} \\ \textbf{tell 2 something important} \\ \textbf{order lunch2} \end{tabular} & \begin{tabular}[c]{@{}c@{}} chat while she waits for her food \\ hug his friend \\ watch his partner 's reaction \end{tabular} \\ \cline{3-5} & & with event & \begin{tabular}[c]{@{}c@{}}\textbf{finish his meal} \\ \textbf{continue his conversation with 2} \\ \textbf{blow out smoke} \end{tabular} & \begin{tabular}[c]{@{}c@{}}finish smoking \\ reminisce \\ hand the cigarette to 2 \end{tabular} \\ \hline \end{tabular} } \caption{Additional examples from the VCG validation set. Generated with nucleus sampling (top $p = 0.9$) .The bold texts are generated by KM-BART. We chose the KM-BART models which have the best performance, with or without event descriptions, respectively.} \label{tab:sampled} \end{table*} \begin{table*}[ht] \centering \resizebox{0.9\linewidth}{!}{ \begin{tabular}{ccccc} \multicolumn{5}{c}{Event: 7 is a bartender serving a customer a drink} \\ \multicolumn{5}{c}{\includegraphics[width=10cm]{images/e1.jpg}} \\ \multicolumn{5}{c}{}\\ \hline Task & Ground Truth & Input & KM-BART & VCG \\ \hline \hline \multirow{2}{*}{intent} & \multirow{2}{*}{\begin{tabular}[c]{@{}c@{}}make the customer happy\\ enjoy serving others \end{tabular}} & without event & \textbf{make sure the customers were happy} & look nice for the photo\\ \cline{3-5} & & with event & \textbf{get a good tip} & earn a good tip \\ \hline \multirow{2}{*}{before} & \multirow{2}{*}{\begin{tabular}[c]{@{}c@{}}take a customers order \\walk out from behind the bar\end{tabular}} & without event & \textbf{get a job as a bartender}& be dressed in a suit \\ \cline{3-5} & & with event & \textbf{get behind the bar} & take the customer 's money \\ \hline \multirow{2}{*}{after} & \multirow{2}{*}{\begin{tabular}[c]{@{}c@{}}bring in the drink\\ask the customer for payment\end{tabular}} & without event & \textbf{take the drink back to the kitchen} & walk away from the table \\ \cline{3-5} & & with event & \textbf{ask the customer if they want another drink} & take money from the customer \\ \hline \multicolumn{5}{c}{} \\ \multicolumn{5}{c}{Event: 2 stand in the front of the plane and faces the passengers} \\ \multicolumn{5}{c}{\includegraphics[width=10cm]{images/e2.jpg}} \\ \multicolumn{5}{c}{} \\ \hline Task & Ground Truth & Input & KM-BART & VCG \\ \hline \hline \multirow{2}{*}{intent} & \multirow{2}{*}{\begin{tabular}[c]{@{}c@{}}make an announcement\\ tell the passengers about emergency exits \end{tabular}} & without event & \textbf{ask 1 a question} & see what was happening\\ \cline{3-5} & & with event & \textbf{give the passengers instructions} & make sure everyone had a ticket \\ \hline \multirow{2}{*}{before} & \multirow{2}{*}{\begin{tabular}[c]{@{}c@{}}wait for the passengers to all take their seats \\walk to the front of the cabin \end{tabular}} & without event & \textbf{board the plane} & walk into the room \\ \cline{3-5} & & with event & \textbf{walk up to the front of the plane} & get on the plane \\ \hline \multirow{2}{*}{after} & \multirow{2}{*}{\begin{tabular}[c]{@{}c@{}}demonstrate how the exits work\\ask the passengers if they have questions\end{tabular}} & without event & \textbf{ask 1 to sit down} & walk away from the table \\ \cline{3-5} & & with event & \textbf{give a speech} & give the passengers a tour \\ \hline \multicolumn{5}{c}{} \\ \multicolumn{5}{c}{Event: 1 holds the gun to his side looking up at the entrance to the building} \\ \multicolumn{5}{c}{\includegraphics[width=10cm]{images/e3.jpg}} \\ \multicolumn{5}{c}{} \\ \hline Task & Ground Truth & Input & KM-BART & VCG \\ \hline \hline \multirow{2}{*}{intent} & \multirow{2}{*}{\begin{tabular}[c]{@{}c@{}}scan the area for a hostile presence\\be armed for a confrontation exits\end{tabular}} & without event & \textbf{get in the car} & get to the car\\ \cline{3-5} & & with event & \textbf{be ready to shoot} & make sure no one got hurt \\ \hline \multirow{2}{*}{before} & \multirow{2}{*}{\begin{tabular}[c]{@{}c@{}}draw his weapon \\drive to building to do crime \end{tabular}} & without event & \textbf{walk up to 2}& walk up to the car \\ \cline{3-5} & & with event & \textbf{pull out his gun} & get out of the car \\ \hline \multirow{2}{*}{after} & \multirow{2}{*}{\begin{tabular}[c]{@{}c@{}}search for the person he wants to shoot\\enter building with gun\end{tabular}} & without event & \textbf{walk away from 2} & walk away \\ \cline{3-5} & & with event & \textbf{walk up to the building} & shoot at the entrance \\ \hline \end{tabular} } \caption{Additional examples from the VCG validation set. Generated with greedy search. The bold text are generated by KM-BART. We chose the KM-BART models which have the best performance, with or without event descriptions, respectively.} \label{tab:greedy} \end{table*} \section{Additional Information on Human Evaluation} Figure~\ref{fig:ui} is the user interface of our human evaluation. We hire workers from Amazon Mechanical Turk. We reject examples with a submission time of less than 30 seconds. The median submission time is 182 seconds. We pay for each example 0.2 USD, which is around 10.4 USD per hour. \begin{figure*}[!t] \centering \includegraphics[width=1.0\linewidth]{images/human_evaluation_interface2.jpg} \caption{User interface for human evaluation.} \label{fig:ui} \end{figure*}
{'timestamp': '2021-07-19T02:04:27', 'yymm': '2101', 'arxiv_id': '2101.00419', 'language': 'en', 'url': 'https://arxiv.org/abs/2101.00419'}
arxiv
\section{Introduction} Computer vision has progressed rapidly with deep learning techniques and more advanced and accurate models for object detection, image classification, image segmentation, pose estimation, and tracking emerging almost every day \cite{ma2020location,zhang2020real,wu2019unsupervised}. Even though computer vision enters a new era with deep learning, there are still plenty of problems unsolved and domain shift is one of them. Albeit CNN models are dominating the computer vision, their performances often become inferior when testing some unseen data or data from a different domain, which is denoted as domain shift. Since most deep learning models are data-driven and the high-accurate performance is mostly guaranteed by the enormous amount of various data, domain shift often exists when there are not enough labeled specific data but we have to test those kinds of data in the testing set. For instance, although we only detect cars on the roads, training the models on day scenes cannot guarantee an effective detection of cars in the night scenes. We might have to utilize enough datasets from night scenes to train the models, nonetheless, sometimes the datasets from some specific scenes are rare or unlabeled, which makes it even more difficult to mitigate the domain shift effect. To mitigate the situation where some kinds of training data are none or rare, The image-to-image translation that could translate images from one domain to another is highly desirable. Fortunately, with the advent of Generative Adversarial Networks (GANs) \cite{goodfellow2014generative}, Some researchers aim to generate some fake datasets in specific scenes using GAN models to overcome the lack of data. With some unpaired image-to-image translation GAN models (i.e., CycleGAN \cite{zhu2017unpaired}), it can not only translate images from the source domain to target domain, but also translate images from target domain to source domain, and the entire process does not require any paired images, which make it ideal for real-world applications. The GAN models for image-to-image translation can generate the corresponding fake images of the target domain from the original images of the source domain in the training dataset, and we can utilize the GAN-generated images to train object detection models and test on images of target domain\cite{arruda2019cross}. Since we expect to solve cross-domain object detection problems, after pre-processing the data and generating the fake images with image-to-image translation models, the generated data has to be fed into the object detection models to train the model and the trained model could demonstrate its effectiveness through testing the data from the target domain. Employing GAN-generated fake images to train the detection models to guarantee the domain of the training data and testing data being the same illustrated the effectiveness of the approach and the detection performance was boosted for the scenario where the training data for the detection models is from one domain while the testing data is in another domain \cite{arruda2019cross}. Instead of simply utilizing the fake images to train the model, we propose to solve the problem from a new perspective by concatenating the original images and their corresponding GAN-translated fake images to form new 6-channel representations. For instance, if we only have source domain images but we intend to test our model on unlabeled images in the target domain, what we did was training the image-to-image translation model with source domain data and target domain data. And then we could employ the trained image translation model to generate the corresponding fake images. Since some image-to-image translation models \cite{zhu2017unpaired} could translate images in both directions, we are able to acquire the corresponding fake data for the data from both the source domain and target domain. Thus, both training images and testing images would be augmented into 6-channel representations by concatenating the RGB three channels of the original images with those from the corresponding fake images. Then we can train and test the detection models using available detection models, the only difference is the dimension of the kernel of the CNN models for detection in the first layer becomes 6 instead of 3. The process of training and testing the proposed method is depicted in Fig. \ref{fig:1}. \begin{figure}[t] \centering \includegraphics[width=0.95\textwidth]{6_channel.pdf} \caption{The flow chart of the proposed 6-channel image augmentation approach for training and testing CNN-based detection models.} \label{fig:1} \end{figure} \section{Related Work} Image-to-image translation is a popular topic in computer vision \cite{xu2019toward,xu2019stacked}. With the advent of Generative Adversarial Networks \cite{goodfellow2014generative}, it could be mainly categorized as supervised image-to-image translation and unsupervised image-to-image translation \cite{alotaibi2020deep}. The supervised image-to-image translation models such as pix2pix \cite{isola2017image} and BicycleGAN \cite{zhu2017toward}, require image pairs from two or more domains (i.e., the exact same image scenes from day and night), which are extremely expensive and unrealistic to be acquired in the real world. Perhaps the quality of the translated images is sometimes beyond expectations, they are not ideal for real-world applications. The unsupervised image-to-image translation models can be divided as cycle consistency based models (i.e., CycleGAN \cite{zhu2017unpaired}, DiscoGAN \cite{kim2017learning}, DualGAN \cite{yi2017dualgan}) which introduce cycle consistency losses, autoencoder based models (i.e., UNIT \cite{liu2017unsupervised}) combined with autoencoder \cite{kingma2013auto}, and recent disentangled representation models (i.e., MUNIT \cite{huang2018multimodal}, DIRT \cite{lee2018diverse}). Since the unsupervised image-to-image translation models only require image sets from two or more domains and do not necessitate any paired images which are arduous to collect and annotate, they are often leveraged to generate some fake data in the target domain and applied to other computer vision tasks such as object detection and image classification. Among those unsupervised image-to-image translation models, CycleGAN \cite{zhu2017unpaired} is frequently utilized as the image-mapping model to generate some fake data to be employed in some cross-domain problems \cite{inoue2018cross}\cite{arruda2019cross}. Object detection addresses the problem that detects the semantic instances on digital images or videos. The fundamental purpose of object detection is to classify the objects shown on the images or videos and simultaneously locate those objects by coordinates \cite{ma2020mdfn}. The applications of object detection are in various fields such as medical image analysis \cite{mo2018efficient}, self-driving car, pose estimation, segmentation, etc. From the perspective of stages, the object detectors are categorized into two types: one-stage detectors and two-stage detectors. For two-stage object detectors such as Faster R-CNN \cite{ren2016faster}, MS-CNN \cite{cai2016unified}, R-FCN \cite{dai2016r}, FPN \cite{lin2017feature}, these models are often comprised of a region proposal network as the first stage that selects the candidate anchors which have high probabilities to contain objects and a detection network as the second stage that classify the objects to be contained by these candidates and further do the bounding box regression for these candidates to refine their coordinates and finally output the results. For one-stage object detectors like SSD \cite{liu2016ssd}, YOLOv1-v4 \cite{redmon2016you}\cite{redmon2017yolo9000}\cite{redmon2018yolov3}\cite{bochkovskiy2020yolov4}, RetinaNet \cite{lin2017focal}, these detectors often directly classify and regress the pre-defined anchor boxes instead of choosing some candidates. Thus the two-stage models often outperform the one-stage counterparts while one-stage models frequently have a faster inference rate than two-stage approaches. Due to the various sizes and shapes of the objects, some models \cite{liu2016ssd}\cite{lin2017feature}\cite{lin2017focal}\cite{zhang2018single} design anchor boxes on different levels of feature maps (the pixels on lower level feature maps have a small receptive field and the pixels on higher-level feature maps have large receptive field) so that the anchors on lower level features are responsible for the relative small objects and the anchors on higher-level features are in charge of detecting relatively large objects. The middle-sized objects are perhaps recognized by the middle-level feature maps. The aforementioned detection models are anchor-based that we have to design pre-defined anchor boxes for these models. In recent years, some anchor-free models \cite{zhu2019feature}\cite{zhou2019bottom}\cite{duan2019centernet}\cite{tian2019fcos}\cite{law2018cornernet} are attracting great attention for their excellent performance without any pre-defined anchor boxes. Some of them are even dominating the accuracy on COCO benchmark \cite{lin2014microsoft}. Since a large amount of anchors has to be generated for some anchor-based models and most of them are useless because no object is contained in the majority of anchors, anchor-free models might predominate in the designs of object detectors in the future. Recently, the transformer \cite{vaswani2017attention} is applied successfully to object detection \cite{carion2020end}, which is an anchor-free model with attention mechanisms. Nonetheless, many problems have not been well solved in this field, especially in cross-domain object detection. Since modern object detectors are based on deep learning techniques and deep learning is data-driven so that the performance of modern object detectors is highly dependent on how many annotated data can be employed as the training set. Cross-domain issues arise when there are not enough labeled training data that have the same domain as the testing data, or the dataset is diverse or composed of various datasets of different domains in both training and testing data. Domain Adaptive Faster R-CNN\cite{chen2018domain} explores the cross-domain object detection problem based on Faster R-CNN. By utilizing Gradient Reverse Layer (GRL) \cite{ganin2015unsupervised} in an adversarial training manner which is similar to Generative Adversarial Networks (GAN)\cite{goodfellow2014generative}, this paper proposes an image-level adaptation component and an instance-level adaptation component which augment the Faster R-CNN structure to realize domain adaptation. In addition, a consistent regularizer between those two components is to alleviate the effects of the domain shift between different dataset such as KITTI \cite{geiger2013vision}, Cityscapes \cite{cordts2016cityscapes}, Foggy Cityscapes \cite{sakaridis2018semantic}, and SIM10K \cite{johnson2016driving} Universal object detection by domain attention \cite{wang2019towards} addresses the universal object detection of various datasets by attention mechanism \cite{vaswani2017attention}. The universal object detection is arduous to realize since the object detection datasets are diverse and there exists a domain shift between them. The paper \cite{hu2018squeeze} proposes a domain adaption module which is comprised of a universal SE adapter bank and a new domain-attention mechanism to realize universal object detection. \cite{inoue2018cross} deals with cross-domain object detection that instance-level annotations are accessible in the source domain while only image-level labels are available in the target domain. The authors exploit an unpaired image-to-image translation model (CycleGAN \cite{zhu2017unpaired}) to generate fake data in the target domain to fine-tune the trained model which is trained on the data in the source domain. Finally, the model is fine-tuned again on the detected results of the testing data (pseudo-labeling) to make the model even better. The study \cite{arruda2019cross} utilizes CycleGAN \cite{zhu2017unpaired} as the image-to-image translation model to translate the images in both directions. The model trained on the fake data in the target domain has better performance than that trained on the original data in the source domain on testing the test data from the target domain. The dataset we employ in this paper is from \cite{arruda2019cross} and we follow exactly the same pre-processing procedure to prepare the dataset. In the following, we will discuss our proposal that utilizes concatenated image pairs (real images and corresponding fake images) to train the detection model and compare it to the corresponding approach from \cite{arruda2019cross}. \section{Proposed Approach} The framework of our proposed method is depicted in Fig. \ref{fig:1}. In our implementation, we employ CycleGAN for image-to-image translation, which is trained with the data from the source domain (i.e., day images) and the data from the target domain (i.e., night images). First, the fake data (target domain) is generated from the original data (source domain) via the trained image-to-image translation model (i.e., generating the fake night images from the real day images). Then, the real and fake images are normalized and concatenated (i.e., concatenating two 3-channel images to form a 6-channel representation of the image). Finally, the concatenated images are exploited to train the CNN models. During the stage of test, the test data is processed in a similar way as the training data to form concatenated images and sent to the trained CNN model for detection. \subsection{Image-to-Image Translation} To realize the cross-domain object detection, we have to collect and annotate the data in the target domain to train the model. While it is difficult to acquire the annotated data in the target domain, image-to-image translation models provide an option to generate fake data in the target domain. In our experiment, we employed an unpaired image-to-image translation model: CycleGAN \cite{zhu2017unpaired}. CycleGAN is an unsupervised image-to-image translation that only requires images from two different domains (without any image-level or instance-level annotations) to train the model. Furthermore, unpaired translation illustrates that the images from two domains do not need to be paired which is extremely demanding to be obtained. Last but not least, the locations and sizes of the objects on the images should be the same after the image-to-image translation so that any image-level labels and instance-level annotations of the original images can be utilized directly on the translated images. This property is extraordinarily significant since most CNN models are data-driven and the annotations of the images are indispensable to successfully train the supervised CNN models (i.e., most object detection models). Unpaired image-to-image translation models such as CycleGAN \cite{zhu2017unpaired} can translate the images in two directions without changing the key properties of the objects on the images. Thus the annotations such as coordinates and class labels of the objects on the original images can be smoothly exploited in the fake translated images. As manually annotating the images is significantly expensive, by image-to-image translation, the translated images would automatically have the same labels as their original counterparts, which to some extent makes manually annotating images unnecessary. \begin{figure}[t] \centering \includegraphics[width=.115\textwidth]{real_day/1.jpg} \includegraphics[width=.115\textwidth]{real_day/2.jpg} \includegraphics[width=.115\textwidth]{real_day/3.jpg} \includegraphics[width=.115\textwidth]{real_day/4.jpg} \includegraphics[width=.115\textwidth]{real_day/5.jpg} \includegraphics[width=.115\textwidth]{real_day/6.jpg} \includegraphics[width=.115\textwidth]{real_day/7.jpg} \includegraphics[width=.115\textwidth]{real_day/8.jpg}\\ \includegraphics[width=.115\textwidth]{fake_night/1.jpg} \includegraphics[width=.115\textwidth]{fake_night/2.jpg} \includegraphics[width=.115\textwidth]{fake_night/3.jpg} \includegraphics[width=.115\textwidth]{fake_night/4.jpg} \includegraphics[width=.115\textwidth]{fake_night/5.jpg} \includegraphics[width=.115\textwidth]{fake_night/6.jpg} \includegraphics[width=.115\textwidth]{fake_night/7.jpg} \includegraphics[width=.115\textwidth]{fake_night/8.jpg}\\ \caption{Several samples of original-day images (1st row) and their corresponding GAN-generated fake-night images (2nd row).} \label{fig:2} \end{figure} \begin{figure}[t] \centering \includegraphics[width=.115\textwidth]{real_night/1.jpg} \includegraphics[width=.115\textwidth]{real_night/2.jpg} \includegraphics[width=.115\textwidth]{real_night/3.jpg} \includegraphics[width=.115\textwidth]{real_night/4.jpg} \includegraphics[width=.115\textwidth]{real_night/5.jpg} \includegraphics[width=.115\textwidth]{real_night/6.jpg} \includegraphics[width=.115\textwidth]{real_night/7.jpg} \includegraphics[width=.115\textwidth]{real_night/8.jpg}\\ \includegraphics[width=.115\textwidth]{fake_day/1.jpg} \includegraphics[width=.115\textwidth]{fake_day/2.jpg} \includegraphics[width=.115\textwidth]{fake_day/3.jpg} \includegraphics[width=.115\textwidth]{fake_day/4.jpg} \includegraphics[width=.115\textwidth]{fake_day/5.jpg} \includegraphics[width=.115\textwidth]{fake_day/6.jpg} \includegraphics[width=.115\textwidth]{fake_day/7.jpg} \includegraphics[width=.115\textwidth]{fake_day/8.jpg}\\ \caption{Several samples of original-night images (1st row) and their corresponding GAN-generated fake-day images (2nd row).} \label{fig:3} \end{figure} \subsection{CNN Models} In Fig. \ref{fig:1}, the CNN model can be any CNN-based object detection model, where the dimension of the convolutional kernel in the first layer is changed from 3 to 6. In our implementation, we employ Faster R-CNN \cite{ren2016faster} for detection, and we use ResNet-101 \cite{he2016deep} as the backbone network for the detection model. Faster R-CNN is a classic two-stage anchor-based object detector that is comprised of Region Proposal Network (RPN) and detection network. Since it is an anchor-based model, we have to design some pre-defined anchor boxes on the feature maps. Typically, 9 anchors with 3 different sizes and 3 different aspect ratios are designed to act as the pre-defined anchor boxes on each location of the feature maps. The objective of RPN is to select some region proposals with a high probability of containing objects from the pre-defined anchors and further refine their coordinates. Each pre-defined anchor would be associated with a score indicating the probability of that anchor box containing an object. Only the anchor boxes with associated scores higher than some threshold can be selected as region proposals and those region proposals are further refined by RPN and later fed into the detection network. The purpose of the detection network is to receive the region proposals selected and refined by RPN and finally do the classification for each rectangle proposal and bounding box regression to improve the coordinates of the box proposals. Since the region proposals may have various sizes and shapes, more accurately, the number of elements each proposal has might be varying. To guarantee the region proposals are fed into the fully connected layers effectively (the fully connected layer needs the length of input data fixed), the ROI pooling layer is adopted to ensure the size of the input of each proposal to the detection network is fixed. The detection network is simply from Fast R-CNN \cite{girshick2015fast} that is to classify the object which might be contained by each region proposal and simultaneously refine the coordinates of the rectangle boxes. The output of the Faster R-CNN network is the class of the object each proposal might include and the coordinates of the bounding box for each refined proposal. \section{Experiments} In this section, the datasets and the experimental methodology and parameter settings are elaborated. We conducted some of the experiments from \cite{arruda2019cross} for comparison. \subsection{Datasets} We employ the same dataset as \cite{arruda2019cross} in our experiments. The original datasets are from BDD100K \cite{yu2018bdd100k} which is a large-scale diverse dataset for driving scenes. Since the dataset is extremely large and contains high-resolution images and various scenarios on the road and the weather conditions (sunny, rainy, foggy, etc.) \cite{arruda2019cross}, the authors only choose the clear or partly cloudy day and night images to demonstrate the domain shift from day to night \cite{arruda2019cross}. In addition, all selected images are cropped to 256$\times$256 pixels with proper adjustment. There are a total 12,000 images left and processed (6,000 day images and 6,000 night images). After that, the images are randomly sampled and divided into four sets: train-day, train-night, test-day, and test-night, each of the sets contains 3,000 256$\times$256 images. We harness the set of train-day and train-night to train the CycleGAN model and utilized the trained GAN model to generate fake train-night (from train-day), fake train-day (from train-night), fake test-night (from test-day), and fake test-day (from test-night). Now we have a total of 12,000 real images (3,000 for each set) and 12,000 fake images (3,000 for each set). Then we can concatenate the real images and their corresponding fake images to generate 6-channel representations that would be fed into the Faster R-CNN object detector. After choosing and processing the images, the car is the only object on the image to be detected. Some samples of real images and their corresponding GAN-generated fake counterparts are illustrated in Fig. \ref{fig:2} and Fig. \ref{fig:3}. \subsection{Experimental Evaluations} Faster R-CNN model is implemented in Python \cite{jjfaster2rcnn} with Pytorch 1.0.0 and CycleGAN is implemented in Python \cite{jyzhu2cyclegan} with PyTorch 1.4.0. All experiments are executed with CUDA 9.1.85 and cuDNN 7 on a single NVIDIA TITAN XP GPU with a memory of 12 GB. The metric we employed is mean Average Precision (mAP) from PASCAL VOC \cite{everingham2015pascal}, which is the same metric employed in \cite{arruda2019cross}. Since the car is the only object to be detected, the mAP is equivalent to AP in this dataset since mAP calculating the mean AP for all classes. For CycleGAN, the parameters are default values in \cite{jyzhu2cyclegan}. For Faster R-CNN, similarly to \cite{arruda2019cross}, we utilize pre-trained ResNet-101 \cite{he2016deep} on ImageNet \cite{deng2009imagenet} as our backbone network. We select the initial learning rates from 0.001 to 0.00001 and the experiments are implemented separately for those chosen initial learning rates, but we do not utilize them all for each experiment since our experiments demonstrate that the higher the learning rate we selected from above, the better the results would be. In each 5 epoch, the learning rate decays as 0.1 of the previous learning rate. The training process would be executed 20 to 30 epochs, but the results indicate that the Faster R-CNN model converges relatively early on the dataset. Training every 5 epochs, we record the testing results on test data, but we would report the best one for each experiment. The model parameters are the same for 6-channel experiments and 3-channel experiments, except for 6-channel experiments, the kernel dimension of the first layer of the Faster R-CNN model is 6 instead of 3. And we just concatenate each kernel by itself to create 6-dimension kernels in the first layer of ResNet-101 backbone for 6-channel experiments. While for 3-channel experiments, we simply exploit the original ResNet-101 backbone as our initial training parameters. \subsection{Experimental Results} First, we implemented the training and testing of the original 3-channel Faster R-CNN model which is illustrated in Table~\ref{table:1}. The test set is test-night data which is fixed. With different training sets, the detection results on test night are varying. \setlength{\tabcolsep}{15pt} \begin{table}[ht] \centering \caption{3-channel detection} \begin{tabular}{ |p{6cm}|p{1cm}|} \hline Train set & mAP\\ \hline train-day (3,000 images) & 0.777\\ fake train-night (3,000 images) & 0.893\\ train-night (3,000 images) & 0.933\\ train-day + train-night (6,000 images) & 0.941\\ \hline \end{tabular} \label{table:1} \end{table} \setlength{\tabcolsep}{15pt} From Table~\ref{table:1} we can see that, for testing the test-night set, the model trained on the fake-train night set is much better than that trained on the original train-day set, which corresponds to the results from \cite{arruda2019cross}. These experimental results indicate that if the annotated day images are the only available training data while the test set contains only night images, we could leverage fake night images generated by the image-to-image translation models to train the CNN model. The results are excellent when the model is trained on the train-night set (without domain shift), indicating the domain shift is the most significant influence on the performance of the CNN model in this experiment. Then we conduct the experiments for our proposed 6-channel Faster R-CNN model which is shown in Table~\ref{table:2}. The test data is comprised of test-night images concatenated with corresponding translated fake test-day images. The training sets in Table~\ref{table:2} have 6 channels. For instance, train-day in the table indicates train-day images concatenated with corresponding fake train-night images, and train-day plus train-night in the table represents train-day images concatenated with corresponding fake train-night images plus train-night images concatenated with corresponding fake train-day images. \setlength{\tabcolsep}{15pt} \begin{table}[ht] \centering \caption{6-channel detection} \begin{tabular}{ |p{9cm}|p{1cm}|} \hline Train set & mAP\\ \hline train-day (3,000 6-channel representations) & 0.830\\ train-night (3,000 6-channel representations) & 0.931\\ train-day + train-night (6,000 6-channel representations) & 0.938\\ \hline \end{tabular} \label{table:2} \end{table} \setlength{\tabcolsep}{15pt} From Table~\ref{table:1} and Table~\ref{table:2}, it is noticeable that even though the model trained on train-day images concatenated with fake train-night images (6-channel) has a better result with AP 0.830 than that just training on train-day (3-channel) with AP 0.777, it is worse than the model only trained on fake train-night (3-channel) with AP 0.893. To demonstrate if the 6-channel approach can improve the detection results in the situation where the training set and testing set do not have domain shift, we also performed the experiment that trains the model on train-night set (3-channel) and tests it on test-night set. From Table~\ref{table:1}, the average precision is 0.933, which is pretty high since there is no domain shift between the training data and testing data. Accordingly, we did the corresponding 6-channel experiment which trains on train-night set concatenated with fake train-day set and tests it on test-night images concatenated with fake test-day images. From Table~\ref{table:2}, the average precision of this 6-channel model is almost the same as its corresponding 3-channel model. We increase the size of the training data by training the model with the train-day set plus the train-night set and testing it on test-night data. From Table~\ref{table:1} and Table~\ref{table:2}, the result of 6-channel model also performs similar to its 3-channel counterpart. More experimental results are shown in Table~\ref{table:3}, which are from the original 3-channel models. To remove the effect of domain shift, the training set and the testing set do not have domain shift (they are all day images or night images). From Table~\ref{table:3}, it is obvious that the "quality" shift influences the performance of the models. For instance, the model trained on the original train-day (or train-night) set has better performance on the original test-day (or test-night) set than the GAN-generated fake day (or night) images. Similarly, the model which is trained on GAN-generated fake train-day (or fake train-night) set performs better on the GAN-generated fake test-day (or fake test-night) set than the original test-day (or test-night) set. \setlength{\tabcolsep}{20pt} \begin{table}[ht] \centering \caption{3-channel extra experiments} \begin{tabular}{ |c|c|c|} \hline Train set & Test set & mAP\\ \hline \multirow{2}{*}{train-day} & test-day & 0.945\\ & fake test-day & 0.789\\ \hline \multirow{2}{*}{fake train-day} & fake test-day & 0.914\\ & test-day & 0.903\\ \hline \multirow{2}{*}{train-night} & test-night & 0.932\\ & fake test-night & 0.859\\ \hline \multirow{2}{*}{fake train-night} & fake test-night & 0.924\\ & test-night & 0.868\\ \hline \end{tabular} \label{table:3} \end{table} \setlength{\tabcolsep}{20pt} \section{Conclusion} The study has evaluated a 6-channel approach to address the domain-shift issue by incorporating the generated fake images using image-to-image translation. However, we have not achieved the expected results. One possible reason is the quality of the generated images is inferior compared to the original images, especially the fake day images generated from the data of night scenes, as illustrated in Fig. \ref{fig:2} and Fig. \ref{fig:3}. If we merely concatenate the original high-quality images with their inferior counterparts, the model may treat the low-quality fake image channels as some kind of "noise", and thus, the model could hardly learn more useful information from the concatenated 6-channel representations. Another possible reason is that the domain shift issue may still exist in the combined 6-channel representations, which prevents the model from extracting useful information from the concatenated representations. Moreover, the dataset we used in the experiments only has limited samples, which are insufficient to train the model. We hope the idea of augmented data representation can inspire more further investigations and applications. \bibliographystyle{splncs04}
{'timestamp': '2021-06-30T02:05:01', 'yymm': '2101', 'arxiv_id': '2101.00561', 'language': 'en', 'url': 'https://arxiv.org/abs/2101.00561'}
arxiv
\section{Introduction} \label{sec:Introduction} In the presence of limited sensing range, certain complex tasks, such as covering a region of interest, can be executed within a smaller amount of time by letting a team of robots move in formation than when it is carried out by a single robot. In addition, each robot within the formation can be equipped with different sensors and therefore, more (local) information can be gathered \cite{Anderson2008}. With this application perspective, the study on attaining and maintaining a particular geometric shape by a team of robots has attracted research interests; see \cite{Oh2015, Zhao2019, Chen2020} for an overview of approaches whereby the desired formation shape is described by a set of only inter-robot relative position, distance, bearing, or angle constraints. Recently, approaches on realizing a formation shape using a mixed set of constraints have been considered. In \cite{Kwon2018}, distance and angle constraints are employed; the paper \cite{Bishop2013} considers the combination of distance and bearing constraints, while the work in \cite{Kwon2019a} use distance, bearing, and angle constraints to describe the desired formation shape. Furthermore, a series of works \cite{Anderson2017a, Sugie2018, Cao2019a, Sugie2020} focus on the combination of distance and signed area constraints. By adding signed area constraints, the authors tackle the flip and flex ambiguity problem present in distance-based formation control. Except for \cite{Sugie2018, Cao2019a, Sugie2020}, the referred works deal with an undirected graph. Moreover, it is usually assumed that all robots within the formation sense a common (geometric) variable, such as a relative position, distance, or bearing. In formation control, triangular formations consisting of three autonomous agents serve as a class of benchmarks that can be used to test and compare the performances of different controllers. This apparently simple setup allows detailed rigorous analysis for novel techniques and methodologies as we aim at in this work (see \cite{Cao2007, anderson2007control, Marina2017, Cao2008, liu2014controlling, 7039453}), and therefore, it provides a starting point in order to achieve more general formations. Our earlier work \cite{Chan2020} dealt with the formation control problem in which the robots can have different sensing mechanism and as a result also different individual task(s). In particular, we partitioned the team of robots in two categories, namely distance robots carrying out distance tasks and bearing robots fulfilling bearing constraints. We mention that the interconnection topology is a directed graph. For the particular case of one distance and two bearing robots, the (\textbf{1D2B}) setup, we showed the existence of moving configurations, i.e., where the robots converge to a non-zero translation velocity, which are locally attractive under certain conditions. One observation on the moving configurations is that the signed area of the corresponding shape has an opposite sign when compared with the desired formation shape, i.e., the robots converge to an \textit{incorrect} shape. Building on \cite{Chan2020}, in this work, we aim to avoid the occurrence of moving configurations by adding a signed area constraint to the distance robot. We remark that this does not increase the sensing load on the robot. For the current analysis, we consider isosceles triangles as the desired formation shape. Our main contribution is then the identification of a specific constraint on the gain ratio $ R_{\text{Ad}} $ between the signed area and the distance control term yielding robots to always evolve to the correct isosceles triangular shape. The remainder of this paper is organized as follows: We first present some preliminaries in Section \ref{sec:Preliminaries}. The (\textbf{1D2B}) setup with the added signed area constraint is then considered in Section \ref{sec:Problem-Setup}. We provide preliminary analysis for the specific case of isosceles triangles in Section \ref{sec:Isosceles-Triangle-Analysis}. In Sections \ref{sec:Isosceles-Triangle-Analysis-Acute} and \ref{sec:Isosceles-Triangle-Analysis-Right-Obtuse}, we then consider more in depth the case of acute isosceles triangles and right and obtuse isosceles triangles, respectively. The theoretical claims are supported by numerical results in Section \ref{sec:Numerical-Example}. Finally, we end with the conclusion in Section \ref{sec:Conclusions}. \paragraph*{Notation} For a vector $ x \in \RN^{n} $, $ x^{\top} $ is the transpose, and $ \norm{x} = \sqrt{x^{\top}x} $ the $ 2 $-norm. The vector $ \mathbb{1}_{n} $ (or $ \mathbb{0}_{n} $) denotes the vector with entries being all $ 1 $s (or $ 0 $s). In the plane $ \RN^{2} $, the symbol $ \angle v_{1} $ denotes the counter-clockwise angle from the $ x $-axis of a coordinate frame $ \Sigma $ to the vector $ v_{1} \in \RN^{2} $. The matrix $ J = \left[ \begin{smallmatrix} 0 & 1 \\ -1 & 0 \end{smallmatrix} \right] $ is the rotation matrix with angle $ -90^{\degree} $. We denote $ x^{\perp} $ as the perpendicular vector obtained by rotating $ x $ with a counter-clockwise angle of $ +90^{\degree} $; we have $ x^{\perp} = - J x $. For two points $ p_{i} $ and $ p_{j} $ in the plane, we define the relative position vector as $ z_{ij} = p_{j} - p_{i} \in \RN^{2} $, the distance as $ d_{ij} = \norm{z_{ij}} \in \RN_{\geq 0} $ and the relative bearing vector, when $d_{ij}\neq 0, $ as $ g_{ij} = \frac{z_{ij}}{d_{ij}} \in \RN^{2} $, all relative to a global coordinate frame $ \Sigma^{\text{g}} $. It follows $ z_{ji} = - z_{ij} $, $ d_{ji} = d_{ij} $ and $ g_{ji} = - g_{ij} $. \section{Preliminaries} \label{sec:Preliminaries} \subsection{Robot configurations} \label{subsec:Robot-Conf} We consider a team consisting of three robots in which \texttt{Ri} is the label assigned to robot $ i $. The robots are moving in the plane $ \RN^{2} $ according to the single integrator dynamics, i.e., \begin{equation} \label{eq:Prel-Robot-Dynamics} \begin{aligned} \dot{p}_{i}\BR{t} = u_{i}\BR{t}, \quad i \in \CBR{1, \, 2, \, 3} , \end{aligned} \end{equation} where $ p_{i} \in \RN^{2} $ (a point in the plane) and $ u_{i} \in \RN^{2} $ represent the position of and the control input for \texttt{Ri}, respectively. For convenience, all spatial variables are given relative to a global coordinate frame $ \Sigma^{\text{g}} $. We assume $ p_{i}\BR{t^{*}} \neq p_{j}\BR{t^{*}}, \, \forall t^{*} \in \left[0, \, t \right) $ if $ i \neq j $, i.e., two robots cannot occupy the same position at the same time. The vector $ p = \begin{bmatrix} p_{1}^{\top} & p_{2}^{\top} & p_{3}^{\top} \end{bmatrix}^{\top} \in \RN^{6} $ represents the \textit{team configuration}. We define $ p_{\text{ref}} $ as the \textit{reference configuration} where the three positions describe a particular triangle $ T $ of interest up to translation. Therefore, the set of \textit{desired configurations} can be formally written from the reference configuration $ p_{\text{ref}} $ as \begin{equation} \label{eq:Prel-Desired-Configurations-p} \mathcal{S}_{p} := \CBR{p \in \RN^{6} \, \rvert \, p = p_{\text{ref}} + \BR{\mathbb{1}_{3} \otimes v}, v\in\RN^2} , \end{equation} where $ v$ is a translation vector and $ \otimes $ denotes the Kronecker product. Note that the desired configurations can also be described in terms of relative positions (or links) $ z_{ij} $'s with $ z_{ij} = p_{j} - p_{i} \in \RN^{2} $. In particular, it is the singleton $ \mathcal{S}_{z} $ whose one element is \begin{equation} \label{eq:Prel-Desired-Configurations-z} z_{\text{ref}} = \BR{H \otimes I_{2}} p_{\text{ref}}, \quad H = \begin{bmatrix} -1 & 1 & 0 \\ -1 & 0 & 1 \\ 0 & -1 & 1 \end{bmatrix} \end{equation} where $ I_{2} $ is the identity matrix. Consider the link vector $ z\BR{t} := \BR{H \otimes I_{2}} p\BR{t} $ converging to a point $ \widetilde{z} \in \RN^{6} $ and $ \dot{p}\BR{t} \to (\mathbb{1}_{3} \otimes w) $ as time progresses, where $ w \in \RN^{2} $ denotes a constant velocity vector. Let $ \widetilde{p} \in \RN^{6} $ denotes a configuration yielding $ \widetilde{z} $. Then, the team trajectory converges to $ p_{\text{traj}}\BR{t} = \BR{\mathbb{1}_{3} \otimes c_{0}} + \widetilde{p} + \BR{\mathbb{1}_{3} \otimes w} t $, where $c_{0} \in \RN^2 $ is an arbitrary offset given by the initial condition $ p\BR{0} $. We have an \textit{equilibrium configuration} when $ w = \mathbb{0}_{2} $, and otherwise, the configuration is \textit{moving}. In the latter case, $ p_{\text{traj}}\BR{t} \to \infty $ as $ t \to \infty $. Depending on whether $ \widetilde{z} \in \mathcal{S}_{z} $ or not, we classify the obtained configuration $ \widetilde{p} $ as \textit{desired} or \textit{incorrect}. \subsection{Signed area of a triangle} \label{subsec:Signed-Area} For a triangle $ T $ with points $ p_{1} $, $ p_{2} $, and $ p_{3} $ in the plane $ \RN^{2} $, the \textit{signed area} $ A $ is given by \begin{equation} \label{eq:Prel-Signed-Area} \begin{aligned} A = \frac{1}{2} \DET{ \begin{bmatrix} 1 & 1 & 1 \\ p_{1} & p_{2} & p_{3} \end{bmatrix} }, \end{aligned} \end{equation} where $ \DET{\bullet} $ denotes the determinant of a matrix. Alternative expressions for $ A $ are $ A = \frac{1}{2} z_{12}^{\top} J z_{13} $ or $ A = \frac{1}{2} \sin \theta_{213} \, d_{12} d_{13} $ with $ \sin \theta_{213} = g_{12}^{\top} J g_{13} $ and $ \theta_{213} $ being the \textit{signed angle} enclosed by the bearing vectors $ g_{12} $ and $ g_{13} $ at point $ p_{1} $. Assuming $ \angle g_{12} = \alpha $ and $ \angle g_{13} = \beta $ with respect to a coordinate frame $ \Sigma $, it follows that $ \sin \theta_{213} = \sin \BR{\beta - \alpha} $. Hence for a counter-clockwise (or clockwise) ordering of points $ p_{1} $, $ p_{2} $, and $ p_{3} $, we obtain $ \theta_{213} > 0 $ and also $ A > 0 $ (or $ \theta_{213} < 0 $ and also $ A < 0 $). \subsection{Cubic equations} \label{subsec:Cubic-Equations} Consider a \textit{reduced}\footnote{in some texts, the term `depressed' is used.} cubic equation \begin{equation} \label{eq:Prel-Reduced-Cubic} y^{3} + cy + d = 0 , \end{equation} where $ c, \, d \in \RN $ and discriminant $ \Delta = -4 c^{3} - 27 d^{2} $. \begin{lemma}[\cite{Chan2020}] \label{lem:Prel-Reduced-Cubic-Roots-Positive} Given a reduced cubic equation \eqref{eq:Prel-Reduced-Cubic} with coefficients $ c < 0 $ and $ d > 0 $. Assume the discriminant is $ \Delta \geq 0 $. Then two positive real roots exist with values \begin{equation} \label{eq:Prel-Reduced-Cubic-Roots-Positive} \begin{aligned} y_{\text{p}_{1}} & = 2 \sqrt[3]{r_{v}} \cos \BR{\frac{1}{3} \varphi_{v} - 120^{\degree}} & & \in \left(0, \, 1\right] \sqrt[3]{r_{v}} , \\ y_{\text{p}_{2}} & = 2 \sqrt[3]{r_{v}} \cos \BR{\frac{1}{3} \varphi_{v}} & & \in \left[1, \, \sqrt{3}\right) \sqrt[3]{r_{v}} , \end{aligned} \end{equation} where $ r_{v} = \sqrt{- \BR{\frac{c}{3}}^{3}} $ and $ \varphi_{v} = \tan^{-1} \BR{\frac{-2}{d}\sqrt{\frac{\Delta}{108}}} \in \left(90^{\degree}, \, 180^{\degree} \right] $. When $ \Delta = 0 $, the two positive real roots are equal and have value $ y_{\text{p}_{1}} = y_{\text{p}_{2}} = \sqrt[3]{r_{v}} = \sqrt[3]{\frac{d}{2}} $. \end{lemma} \section{The (\textbf{1D2B}) Setup with a Signed Area Constraint} \label{sec:Problem-Setup} As discussed in the Introduction, we consider the setup in which the robots possess heterogeneous sensing mechanism; as a result, they each fulfill different task(s) within the formation. Without loss of generality, we let robot \texttt{R1} be the \textit{distance robot} and \texttt{R2} and \texttt{R3} be \textit{bearing robots}. Since \texttt{R1} is the distance robot, it needs to maintain \textit{distance constraint} $ d_{12}^{\star} $ with \texttt{R2} and similarly, $ d_{13}^{\star} $ with \texttt{R3}. It possesses an \textit{independent local coordinate frame} $ \Sigma^{\text{1}} $ which is \textit{not necessarily aligned} with that of \texttt{R2} and \texttt{R3} or the global coordinate frame $ \Sigma^{\text{g}} $. Within $ \Sigma^{\text{1}} $, \texttt{R1} obtains the relative position information $ z_{12} $ and $ z_{13} $ from the neighboring robots. Robot \texttt{R2} has the task to keep a \textit{bearing constraint} $ g_{21}^{\star} $ relative to \texttt{R1}. The local coordinate frame $ \Sigma^{2} $ is \textit{aligned with} $ \Sigma^{\text{g}} $ and \texttt{R2} obtains the bearing measurement $ g_{21} $ within $ \Sigma^{2} $. In a similar fashion, \texttt{R3} obtains bearing measurement $ g_{31} $ with respect to $ \Sigma^{3} $ and is required to satisfy a desired bearing $ g_{31}^{\star} $ relative to \texttt{R1}. In our previous work \cite{Chan2020}, the closed-loop dynamics corresponding to this setup is obtained as \begin{equation} \label{eq:3R-1D2B-p-Dynamics} \begin{aligned} \begin{bmatrix} \dot{p}_{1} \\ \dot{p}_{2} \\ \dot{p}_{3} \end{bmatrix} = \begin{bmatrix} K_{\text{d}} u_{12\text{d}} + K_{\text{d}} u_{13\text{d}} \\ K_{\text{b}} u_{21\text{b}} \\ K_{\text{b}} u_{31\text{b}} \end{bmatrix} , \end{aligned} \end{equation} where $ K_{\text{d}} > 0 $ and $ K_{\text{b}} > 0 $ are the gains for the distance and bearing control terms. Let $ \left[ \text{L} \right] $ be the dimension for length and $ \left[ \text{T} \right] $ the dimension for time. Then we obtain that $ K_{\text{d}} $ has dimension $ \left[ \text{L} \right]^{-2} \left[ \text{T} \right]^{-1} $, and $ K_{\text{b}} $ is expressed in $ \left[ \text{L} \right] \left[ \text{T} \right]^{-1} $. The \textit{distance control terms} are of the form $ u_{ij\text{d}} = e_{ij\text{d}} z_{ij} $ with the \textit{distance error signal} $ e_{ij\text{d}} = d_{ij}^{2} - \BR{d_{ij}^{\star}}^{2} $. These are gradient-based control laws obtained from the \textit{distance potential function} $ V_{ij{\text{d}}}\BR{e_{ij\text{d}}} = \frac{1}{4} e_{ij{\text{d}}}^{2} $. Similarly, the \textit{bearing control terms} are gradient-based control laws obtained from the \textit{bearing potential function} $ V_{ij\text{b}}\BR{e_{ij\text{b}}} = d_{ij} \norm{e_{ij\text{b}}}^{2} $ and are of the form $ u_{ij\text{b}} = e_{ij\text{b}} $ with the \textit{bearing error signal} $ e_{ij\text{b}} = g_{ij} - g_{ij}^{\star} $. The following findings are reported in \cite{Chan2020} on the stability analysis of the closed-loop system \eqref{eq:3R-1D2B-p-Dynamics}: \begin{enumerate} \item The equilibrium configurations are the desired configurations in which all error signals are zero or zero vector; Furthermore, they are locally asymptotically stable. \item The moving configurations occur when the desired distances satisfy $ d_{12}^{\star} \geq \widehat{d} $ and $ d_{13}^{\star} \geq \widehat{d} $ with $ \widehat{d} = \sqrt{3}\sqrt[3]{\frac{R_{\text{bd}}}{2}} $ and gain ratio $ R_{\text{bd}} = \frac{K_{\text{b}}}{K_{\text{d}}} $. The error vector is of the form \begin{equation} \label{eq:3R-1D2B-Moving-Conditions} \begin{aligned} \begin{bmatrix} e_{12\text{d}} \\ e_{13\text{d}} \\ e_{12\text{b}} \\ e_{13\text{b}} \end{bmatrix} = - \begin{bmatrix} \frac{1}{d_{12}} R_{\text{bd}} \\ \frac{1}{d_{13}} R_{\text{bd}} \\ \BR{g_{12}^{\star} + g_{13}^{\star}} \\ \BR{g_{12}^{\star} + g_{13}^{\star}} \end{bmatrix} \end{aligned} \end{equation} and the steady-state translation velocity is $ w = K_{\text{b}} \BR{g_{12}^{\star} + g_{13}^{\star}} $. It is remarked that these moving configurations have a signed area which is opposite in sign to that of the correct shape. When a condition on $ \cos \theta^{\star} $ is satisfied (Lemma 3 in \cite{Chan2020}), we obtained that the linearization matrix has eigenvalues with negative real parts and hence the moving configurations are locally asymptotically stable. \end{enumerate} \subsection{Adding a signed area constraint to \texttt{R1}} In the works \cite{Anderson2017a, Sugie2018, Cao2019a, Sugie2020}, it was shown that the inclusion of a \textit{signed area constraint} with a proper gain for the resulting control term avoids the occurence of flipped formations. Since the moving configurations have a signed area which is opposite to that of the correct formation shape, it can be classified as a flipped formation. Hence in the current work, we require \texttt{R1} to additionally fulfill a signed area constraint $ A^{\star} $ involving \texttt{R2} and \texttt{R3}. This serves as a strategy to avoid flipped formations and therefore also the moving configurations. Recall the expression for the signed area is $ A = \frac{1}{2} z_{12}^{\top} J z_{13} $ with $ J $ being a rotation matrix. \texttt{R1} is able to compute this quantity with the available local information. For obtaining the control law, we define the \textit{signed area error signal} as $ e_{\text{A}} = A - A^{\star} $. The \textit{signed area potential function} is taken as $ V_{\text{A}}\BR{e_{\text{A}}} = e_{\text{A}}^{2} $. Since \texttt{R1} will be responsible for the signed area constraint, taking the derivative of $ V_{\text{A}} $ with respect to $ p_{1} $ yields $ \PARDIFF{}{p_{1}} V_{\text{A}} = e_{\text{A}} \BR{z_{13} - z_{12}}^{\top} J $. The gradient-based control law for the signed area task is then $ u_{\text{A}} = e_{\text{A}} J \BR{z_{13} - z_{12}} $. \subsection{The (\textbf{1D2B}) setup with signed area control term} Adding the control term $ u_{\text{A}} $ to \texttt{R1} in \eqref{eq:3R-1D2B-p-Dynamics} results in \begin{equation} \label{eq:3R-1D2B-S-p-Dynamics} \begin{aligned} \begin{bmatrix} \dot{p}_{1} \\ \dot{p}_{2} \\ \dot{p}_{3} \end{bmatrix} = \begin{bmatrix} K_{\text{d}} u_{12\text{d}} + K_{\text{d}} u_{13\text{d}} + K_{\text{A}} u_{\text{A}} \\ K_{\text{b}} u_{21\text{b}} \\ K_{\text{b}} u_{31\text{b}} \end{bmatrix} . \end{aligned} \end{equation} The control gain for the area task is $ K_{\text{A}} > 0 $ and has dimension $ \left[ \text{L} \right]^{-2} \left[ \text{T} \right]^{-1} $. Relative to the global coordinate system $ \Sigma^{\text{g}} $, we have $ u_{12\text{b}} = - u_{21\text{b}} $ and $ u_{13\text{b}} = - u_{31\text{b}} $. The link dynamics corresponding to \eqref{eq:3R-1D2B-S-p-Dynamics} is obtained as \begin{equation} \label{eq:3R-1D2B-S-z-Dynamics} \begin{aligned} \begin{bmatrix} \dot{z}_{12} \\ \dot{z}_{13} \\ \dot{z}_{23} \end{bmatrix} = - \begin{bmatrix} K_{\text{b}} u_{12\text{b}} + K_{\text{d}} u_{12\text{d}} + K_{\text{d}} u_{13\text{d}} + K_{\text{A}} u_{\text{A}} \\ K_{\text{b}} u_{13\text{b}} + K_{\text{d}} u_{12\text{d}} + K_{\text{d}} u_{13\text{d}} + K_{\text{A}} u_{\text{A}} \\ K_{\text{b}} \BR{u_{13\text{b}} - u_{\text{12\text{b}}}} \end{bmatrix} . \end{aligned} \end{equation} In the remainder of this paper, we investigate the effect of adding the signed area control term $ u_{\text{A}} $ to the closed-loop system \eqref{eq:3R-1D2B-p-Dynamics}. In particular, \begin{enumerate} \item we aim to preclude moving configurations by including $ u_{\text{A}} $ and a proper tuning of the associated gain $ K_{\text{A}} $ in relation to other gains; and \item as including $ u_{\text{A}} $ may introduce other undesired (moving) configurations, we provide conditions which prevent these possible undesired configurations to occur. \end{enumerate} We note that the configurations $ \widehat{p} $ yielding the collective error variable $ e = \begin{bmatrix} e_{12\text{d}} & e_{13\text{d}} & e_{\text{A}} & e_{12\text{b}}^{\top} & e_{13\text{b}}^{\top} \end{bmatrix}^{\top} \in \RN^{7} $ to be the zero vector are in the set $ \mathcal{S}_{p} $, i.e., another characterization of the set of desired configurations in terms of the error vector $ e $ is $ \mathcal{S}_{p} = \CBR{p \in \RN^{6} \, | \, e = \mathbb{0}_{7}} $. To provide answers to the above determined goals, we are required to solve the following vector equation for the distance pair $ \BR{d_{12}, \, d_{13}} $. \begin{proposition} \label{prop:3R-1D2B-S-Condition-EQ-MV-Conf} Consider a team of three robots moving according to \eqref{eq:3R-1D2B-S-p-Dynamics}. Define the gain ratios $ R_{\text{bd}} = \frac{K_{\text{b}}}{K_{\text{d}}} > 0 $ and $ R_{\text{Ad}} = \frac{K_{\text{A}}}{K_{\text{d}}} > 0 $. Then for the equilibrium and moving configurations, the feasible distance pairs $ \BR{d_{12}, \, d_{13}} $ are solutions to the vector equation \begin{equation} \label{eq:3R-1D2B-S-g12-g13-Eq} \begin{aligned} a g_{12}^{\star} + b g_{13}^{\star} = c g_{12}^{\star \, \perp} + d g_{13}^{\star \, \perp} , \end{aligned} \end{equation} where the coefficients $ a $, $ b $, $ c $, and $ d $ are \begin{equation} \label{eq:3R-1D2B-S-EQ-g12-g13-Eq-Coeff} \begin{aligned} & a = e_{12\text{d}} d_{12} , & & b = e_{13\text{d}} d_{13} , \\ & c = - R_{\text{Ad}} e_{\text{A}} d_{12} , & & d = R_{\text{Ad}} e_{\text{A}} d_{13} \end{aligned} \end{equation} for equilibrium configurations and \begin{equation} \label{eq:3R-1D2B-S-MV-g12-g13-Eq-Coeff} \begin{aligned} & a = e_{13\text{d}} d_{13} + R_{\text{bd}} , & & b = e_{12\text{d}} d_{12} + R_{\text{bd}} , \\ & c = R_{\text{Ad}} e_{\text{A}} d_{13} , & & d = - R_{\text{Ad}} e_{\text{A}} d_{12} \end{aligned} \end{equation} when considering moving configurations. \end{proposition} \begin{proof} First, we consider equilibrium configurations for which $ \dot{p} = \mathbb{0}_{6} $. From the dynamics for the bearing robots \texttt{R2} and \texttt{R3}, we immediately obtain $ e_{12\text{b}} = \mathbb{0}_{2} $ and $ e_{13\text{b}} = \mathbb{0}_{2} $; the bearing constraints are attained. In addition, we have $ d_{12} \neq 0 $ and $ d_{13} \neq 0 $. Substituting the correct bearing vectors $ g_{12} = g_{12}^{\star} $ and $ g_{13} = g_{13}^{\star} $ in the dynamics of \texttt{R1} and rearranging the terms result in \eqref{eq:3R-1D2B-S-g12-g13-Eq} with coefficients in \eqref{eq:3R-1D2B-S-EQ-g12-g13-Eq-Coeff}. Next, we consider moving configurations. For this, we focus on the equilibrium points of the link dynamics \eqref{eq:3R-1D2B-S-z-Dynamics} since $ \dot{p}_{i} = \dot{p}_{j} = w \implies \dot{z}_{ij} = \mathbb{0}_{2} $. We have already considered the case $ w = \mathbb{0}_{2} $, so our focus will be on $ w \neq \mathbb{0}_{2} $. Setting $ \dot{z}_{23} = \mathbb{0}_{2} $ leads to $ g_{12} - g_{13} = g_{12}^{\star} - g_{13}^{\star} $. The possible solutions are found to be the combinations $ \BR{g_{12}, \, g_{13}} = \BR{g_{12}^{\star}, \, g_{13}^{\star}} $ and $ \BR{g_{12}, \, g_{13}} = \BR{- g_{13}^{\star}, \, - g_{12}^{\star}} $. The former corresponds to equilibrium configurations, so $ w = \mathbb{0}_{2} $. The latter results in the bearing error signal $ e_{12\text{b}} = e_{13\text{b}} = - \BR{g_{12}^{\star} + g_{13}^{\star}} $. Substituting the obtained bearing error signal in \eqref{eq:3R-1D2B-S-z-Dynamics} and rearranging terms, we obtain \eqref{eq:3R-1D2B-S-g12-g13-Eq} with coefficients provided in \eqref{eq:3R-1D2B-S-MV-g12-g13-Eq-Coeff}. Since the bearing vectors are already known, provided $ R_{\text{Ad}} $ and $ R_{\text{bd}} $ are given, the coefficients $ \CBR{a, \, b, \, c, \, d} $ in \eqref{eq:3R-1D2B-S-EQ-g12-g13-Eq-Coeff} and \eqref{eq:3R-1D2B-S-MV-g12-g13-Eq-Coeff} depend solely on the distances $ d_{12} $ and $ d_{13} $. This completes the proof. \end{proof} Note that pre-multiplying \eqref{eq:3R-1D2B-S-g12-g13-Eq} by a rotation matrix $ Q $ with angle $ \xi $ has no effect on the coefficients $ \CBR{a, \, b, \, c, d} $. Hence without loss of generality, we take \begin{equation} \label{eq:3R-1D2B-S-g12-g13-Bearing} \begin{aligned} g_{12}^{\star} = \begin{bmatrix} 1 \\ 0 \end{bmatrix} , \: g_{13}^{\star} = \begin{bmatrix} \cos \theta^{\star} \\ \sin \theta^{\star} \end{bmatrix} , \: \begin{aligned} g_{12}^{\star \, \perp} & = - J g_{12} \\ g_{13}^{\star \, \perp} & = - J g_{13} \end{aligned} . \end{aligned} \end{equation} This corresponds to $ \angle g_{12}^{\star} = 0^{\degree} $, $ \angle g_{13}^{\star} = \theta^{\star} $, $ \angle g_{12}^{\star \, \perp} = 90^{\degree} $, and $ \angle g_{13}^{\star \, \perp} = 90^{\degree} + \theta^{\star} $, where $ \theta^{\star} $ is the \textit{desired inner angle} enclosed by the bearing vectors $ g_{12}^{\star} $ and $ g_{13}^{\star} $. When $ \angle g_{12}^{\star} = \alpha \neq 0^{\degree} $, we can pre-multiply \eqref{eq:3R-1D2B-S-g12-g13-Eq} by $ Q\BR{-\alpha} $ to obtain the bearing vectors in \eqref{eq:3R-1D2B-S-g12-g13-Bearing}. Substituting \eqref{eq:3R-1D2B-S-g12-g13-Bearing} in \eqref{eq:3R-1D2B-S-g12-g13-Eq} yields the set of equations \begin{equation} \label{eq:3R-1D2B-S-g12-g13-Eq-Set} \left \{ \begin{aligned} a + b \cos \theta^{\star} & = - d \sin \theta^{\star} \\ b \sin \theta^{\star} & = c + d \cos \theta^{\star} . \end{aligned} \right. \end{equation} Equivalently, we obtain \begin{equation} \label{eq:3R-1D2B-S-g12-g13-Eq-Set-V2} \left \{ \begin{aligned} a \sin \theta^{\star} & = - c \cos \theta^{\star} - d \\ b \sin \theta^{\star} & = c + d \cos \theta^{\star} . \end{aligned} \right. \end{equation} In the forthcoming analysis, we aim to find feasible distance pairs $ \BR{d_{12}, \, d_{13}} $ in Proposition \ref{prop:3R-1D2B-S-Condition-EQ-MV-Conf} by solving \eqref{eq:3R-1D2B-S-g12-g13-Eq-Set-V2}. We assume $ \theta^{\star} $ is in the region $ \theta^{\star} \in \BR{0^{\degree}, 180^{\degree}} $; in this case, the robots are ordered in a counter-clockwise setting and hence the \textit{desired} signed area $ A^{\star} $ is positive. \section{Analysis on Isosceles Triangles} \label{sec:Isosceles-Triangle-Analysis} As a first endeavor, we focus on solving the set of equations \eqref{eq:3R-1D2B-S-g12-g13-Eq-Set-V2} for the class of \textit{isosceles} triangles. An isosceles triangle has two equal sides of length $ \ell > 0 $ and two equal angles with value $ \gamma \in \BR{0^{\degree}, \, 90^{\degree}} $. The equal sides are called legs and the third side is the base. The equal angles are called base angles and the angle included by the legs is the vertex angle. In the current setup, we assume the distance constraints $ d_{12}^{\star} $ and $ d_{13}^{\star} $ are equal, i.e., $ d_{12}^{\star} = d_{13}^{\star} = \ell $ are the legs of the triangle and the desired inner angle $ \theta^{\star} $ is the vertex angle and satisfies $ \theta^{\star} = 180^{\degree} - 2\gamma $. The isosceles triangle is \textit{acute} when $ \theta^{\star} \in \BR{0^{\degree}, \, 90^{\degree}} $, \textit{right} when $ \theta^{\star} = 90^{\degree} $, and \textit{obtuse} when $ \theta^{\star} \in \BR{90^{\degree}, \, 180^{\degree}} $. We first obtain the set of equations \eqref{eq:3R-1D2B-S-g12-g13-Eq-Set-V2} for the equilibrium and moving configurations corresponding to this class of triangles. To this end, we parametrize the actual distances $d_{12}$ and $d_{13}$ by \begin{equation} \label{eq:3R-1D2B-S-ISO-EQ-PAR-XY} d_{12} = x \ell, \, d_{13} = y \ell \quad \text{ with } x, \, y > 0. \end{equation} The value $ x = 1 $ means robot \texttt{R1} satisfies the distance constraint relative to \texttt{R2}. A similar result concerning \texttt{R3} holds when $ y = 1 $. \subsection{Equilibrium configurations} For equilibrium configurations, we recall that according to Proposition \ref{prop:3R-1D2B-S-Condition-EQ-MV-Conf}, the bearing robots \texttt{R2} and \texttt{R3} attain its individual bearing task, i.e. $ g_{12} = g_{12}^{\star} $ and $ g_{13} = g_{13}^{\star} $. It follows then that $ \sin \theta = \sin \theta^{\star} $. With the parametrization in \eqref{eq:3R-1D2B-S-ISO-EQ-PAR-XY}, the distance and signed area error signals evaluate to $ e_{12\text{d}} = \BR{x^{2} - 1} \ell^{2} $, $ e_{13\text{d}} = \BR{y^{2} - 1} \ell^{2} $, and $ e_{\text{A}} = \frac{1}{2} \sin \theta^{\star} \BR{xy - 1} \ell^{2} $. Substituting these relations into \eqref{eq:3R-1D2B-S-g12-g13-Eq-Set-V2} with coefficients $ \CBR{a, \, b, \, c, \, d} $ defined in \eqref{eq:3R-1D2B-S-EQ-g12-g13-Eq-Coeff} yields \begin{equation} \label{eq:3R-1D2B-S-ISO-EQ-g12-g13-Set} \left \{ \begin{aligned} \BR{x^{2} - 1} x & = \frac{1}{2} R_{\text{Ad}} \BR{xy - 1} \BR{x \cos \theta^{\star} - y} \\ \BR{y^{2} - 1} y & = \frac{1}{2} R_{\text{Ad}} \BR{xy - 1} \BR{y \cos \theta^{\star} - x} . \end{aligned} \right. \end{equation} We find out whether solutions of the form $ x = y $ and $ x \neq 1 $ are feasible. In this case, expression \eqref{eq:3R-1D2B-S-ISO-EQ-g12-g13-Set} reduces to $ \BR{1 + \frac{1}{2} R_{\text{Ad}} \BR{1 - \cos \theta^{\star}}} x = 0 $. For it to hold, we require $ R_{\text{Ad}} = - \frac{2}{1 - \cos \theta^{\star}} < -1 $ or $ x = 0 $. Since $ R_{\text{Ad}} > 0 $ and $ x > 0 $, it follows both conditions cannot be met. By De Morgan's laws, solutions to \eqref{eq:3R-1D2B-S-ISO-EQ-g12-g13-Set} are either of the form $ x \neq y $ or $ x = 1 $. When $ x \neq y $, subtracting the equations in \eqref{eq:3R-1D2B-S-ISO-EQ-g12-g13-Set} results in \begin{equation} \label{eq:3R-1D2B-S-ISO-EQ-g12-g13-Diff} \begin{aligned} x^{2} + y^{2} + xy - 1 & = \frac{1}{2} R_{\text{Ad}} \BR{1 + \cos \theta^{\star}} \BR{xy - 1} . \end{aligned} \end{equation} In \eqref{eq:3R-1D2B-S-ISO-EQ-g12-g13-Set}, we see the presence of $ \cos \theta^{\star} $ terms. For acute isosceles triangles, $ \cos \theta^{\star} \in \BR{0, \, 1} $ while for right and obtuse isosceles triangles, $ \cos \theta^{\star} \in \left(-1, \, 0\right] $. In the forthcoming sections, we will divide the analysis in these two sub-regions. We state the following result which holds for both sub-regions of $ \cos \theta^{\star} $: \begin{proposition} \label{prop:3R-1D2B-S-ISO-EQ-Conditions-I} For robot \texttt{R1}, satisfying one of its assigned tasks is equivalent to satisfying all its assigned tasks. In particular, with the parametrization of the distances in \eqref{eq:3R-1D2B-S-ISO-EQ-PAR-XY}, we have \begin{enumerate} \item $ x = 1 \iff y = 1 \, \wedge \, xy = 1 $; \item $ y = 1 \iff x = 1 \, \wedge \, xy = 1 $; \item $ xy = 1 \iff x = 1 \, \wedge \, y = 1 $. \end{enumerate} \end{proposition} \begin{proof} The necessity part $ \BR{\impliedby} $ is immediately observed for all the three statements, so we focus only on the sufficient part $ \BR{\implies} $. \begin{enumerate} \item $ x = 1 \implies y = 1 \, \wedge \, xy = 1 $; ~\\ Substituting $ x = 1 $ in \eqref{eq:3R-1D2B-S-ISO-EQ-g12-g13-Set} yields \begin{equation} \label{eq:3R-1D2B-S-ISO-EQ-g12-g13-Set-Case-1} \left \{ \begin{aligned} 0 & = \frac{1}{2} R_{\text{Ad}} \BR{y - 1} \BR{\cos \theta^{\star} - y} \\ \BR{y^{2} - 1} y & = \frac{1}{2} R_{\text{Ad}} \BR{y - 1} \BR{y\cos \theta^{\star} - 1} . \end{aligned} \right. \end{equation} The first equation in \eqref{eq:3R-1D2B-S-ISO-EQ-g12-g13-Set-Case-1} is satisfied when $ y = 1 $ or $ y = \cos \theta^{\star} $. The option $ y = 1 $ holds for the second equation. In addition, $ xy = 1 $. Since we know $ y > 0 $, it follows that option $ y = \cos \theta^{\star} $ is feasible only when $ \cos \theta^{\star} > 0 $. Substituting $ y = \cos \theta^{\star} $ in the second equation yields $ \cos \theta^{\star} = - \frac{1}{2} R_{\text{Ad}} \BR{1 - \cos \theta^{\star}} $. The left-hand side (LHS) is positive while the right-hand side (RHS) is negative since $ R_{\text{Ad}} > 0 $. We infer that $ y = \cos \theta^{\star} $ does not satisfy the second equation and hence it is not a solution to \eqref{eq:3R-1D2B-S-ISO-EQ-g12-g13-Set-Case-1}. \item $ y = 1 \implies x = 1 \, \wedge \, xy = 1 $; ~\\ Substituting $ y = 1 $ in \eqref{eq:3R-1D2B-S-ISO-EQ-g12-g13-Set} yields \begin{equation} \label{eq:3R-1D2B-S-ISO-EQ-g12-g13-Set-Case-2} \left \{ \begin{aligned} \BR{x^{2} - 1} x & = \frac{1}{2} R_{\text{Ad}} \BR{x - 1} \BR{x \cos \theta^{\star} - 1} \\ 0 & = \frac{1}{2} R_{\text{Ad}} \BR{x - 1} \BR{\cos \theta^{\star} - x} . \end{aligned} \right. \end{equation} The second equation in \eqref{eq:3R-1D2B-S-ISO-EQ-g12-g13-Set-Case-2} is satisfied when $ x = 1 $ or $ x = \cos \theta^{\star} $. The option $ x = 1 $ holds for the first equation. In addition, $ xy = 1 $. Since we know $ x > 1 $, it follows that option $ x = \cos \theta^{\star} $ is feasible only when $ \cos \theta^{\star} > 0 $. Substituting $ x = \cos \theta^{\star} $ in the first equation yields $ \cos \theta^{\star} = - \frac{1}{2} R_{\text{Ad}} \BR{1 - \cos \theta^{\star}} $. The LHS is positive while the RHS is negative since $ R_{\text{Ad}} > 0 $. We infer that $ x = \cos \theta^{\star} $ does not satisfy the first equation and hence it is not a solution to \eqref{eq:3R-1D2B-S-ISO-EQ-g12-g13-Set-Case-2}. \item $ xy = 1 \implies x = 1 \, \wedge \, y = 1 $; ~\\ Substituting $ xy = 1 $ in \eqref{eq:3R-1D2B-S-ISO-EQ-g12-g13-Set} yields \begin{equation} \label{eq:3R-1D2B-S-ISO-EQ-g12-g13-Set-Case-3} \left \{ \begin{aligned} \BR{x^{2} - 1} x & = 0 \\ \BR{y^{2} - 1} y & = 0 \end{aligned} \right. \iff \left \{ \begin{aligned} x & = \pm 1 \\ y & = \pm 1 . \end{aligned} \right. \end{equation} Since $ x > 0 $ and $ y > 0 $ holds, the only possible combination is $ x = 1 \, \wedge \, y = 1 $. \end{enumerate} This completes the proof. \end{proof} In Proposition \ref{prop:3R-1D2B-S-ISO-EQ-Conditions-I}, at least one of the tasks assigned to \texttt{R1} is attained. It remains to investigate the case when none of the assigned tasks is achieved, i.e., the case $ x \neq 1 $, $ y \neq 1 $, $ xy \neq 1 $, and $ x \neq y $ by De Morgan's laws for the sub-regions of $ \cos \theta^{\star} $. We will deal with this in the forthcoming sections. \subsection{Moving configurations} Previously, in Proposition \ref{prop:3R-1D2B-S-Condition-EQ-MV-Conf}, we have obtained that the bearing vectors corresponding to moving formations are $ g_{12} = - g_{13}^{\star} $ and $ g_{13} = - g_{12}^{\star} $. It follows that $ \sin \theta = - \sin \theta^{\star} $; the formation is flipped and rotated. With the parametrization of the distances $ d_{12} = x \ell $ and $ d_{13} = y \ell $ in \eqref{eq:3R-1D2B-S-ISO-EQ-PAR-XY}, we obtain that distance error signals are the same as before while the signed area error signal evaluates to $ e_{\text{A}} = \frac{1}{2} \sin \theta^{\star} \BR{-xy - 1} \ell^{2} $ for moving configurations. The set of equations \eqref{eq:3R-1D2B-S-g12-g13-Eq-Set-V2} with coefficients $ \CBR{a, \, b, \, c, \, d} $ in \eqref{eq:3R-1D2B-S-MV-g12-g13-Eq-Coeff} is found to be \begin{equation} \label{eq:3R-1D2B-S-ISO-MV-g12-g13-Set} \left \{ \begin{aligned} \BR{x^{2} - 1} x \ell^{3} + R_{\text{bd}} & = \frac{1}{2} R_{\text{Ad}} \BR{xy + 1} \BR{x \cos \theta^{\star} - y} \ell^{3} \\ \BR{y^{2} - 1} y \ell^{3} + R_{\text{bd}} & = \frac{1}{2} R_{\text{Ad}} \BR{xy + 1} \BR{y \cos \theta^{\star} - x} \ell^{3} . \end{aligned} \right. \end{equation} Again, we find out whether solutions of the form $ x = y $ are feasible. With $ x = y $, \eqref{eq:3R-1D2B-S-ISO-MV-g12-g13-Set} reduces to \begin{equation} \label{eq:3R-1D2B-S-ISO-MV-g12-g13-Equal} \begin{aligned} & \BR{x^{2} - 1} x \ell^{3} + R_{\text{bd}} = -\frac{1}{2} R_{\text{Ad}} \BR{1 - \cos \theta^{\star}} \BR{x^{2} + 1} x \ell^{3} . \end{aligned} \end{equation} Observe that the RHS of \eqref{eq:3R-1D2B-S-ISO-MV-g12-g13-Equal} is negative; for the LHS to be negative, $ x < 1 $ is required. The exact range for $ x $ is provided in Corollary \ref{cor:3R-1D2B-S-MV-Cubic-Equation-r}. The difference equation for \eqref{eq:3R-1D2B-S-ISO-MV-g12-g13-Set} is with $ x \neq y $, \begin{equation} \label{eq:3R-1D2B-S-ISO-MV-g12-g13-Diff} \begin{aligned} & x^{2} + y^{2} + xy - 1 = \frac{1}{2} R_{\text{Ad}} \BR{1 + \cos \theta^{\star}} \BR{xy + 1} . \end{aligned} \end{equation} Similar to the equilibrium configurations, we will divide the forthcoming analysis on moving configurations in two sub-regions, namely acute isosceles triangles with $ \cos \theta^{\star} > 0 $ and right and obtuse isosceles triangles having $ \cos \theta^{\star} \leq 0 $. Before getting into these analyses, we state the following result for the LHS of \eqref{eq:3R-1D2B-S-ISO-MV-g12-g13-Set}: \begin{proposition} \label{prop:3R-1D2B-S-ISO-MV-Cubic-Equation-z} Given a cubic equation of the form \begin{equation} \label{eq:3R-1D2B-S-ISO-MV-Case-I-2-Cubic} \begin{aligned} f\BR{\mathbb{z}} \coloneqq \mathbb{z}^{3} - \ell^{2} \mathbb{z} + R_{\text{bd}} , \end{aligned} \end{equation} where $ \mathbb{z} = \mathbb{r} \ell $ denotes a general variable for the distance and $ \mathbb{r} \in \CBR{x, \, y} $. Let $ \widehat{d} = \sqrt{3} \sqrt[3]{\frac{R_{\text{bd}}}{2}} $. Then for $ \mathbb{z} > 0 $, the cubic equation in \eqref{eq:3R-1D2B-S-ISO-MV-Case-I-2-Cubic} takes values \begin{equation} \label{eq:3R-1D2B-S-ISO-MV-Case-I-2-Cubic-Value} f\BR{\mathbb{z}} = \begin{cases} > 0 & \text{if } \ell < \widehat{d} \\ \geq 0 & \text{if } \ell = \widehat{d} \\ \gtreqqless 0 & \text{if } \ell > \widehat{d} . \end{cases} \end{equation} \end{proposition} \begin{proof} By comparison with \eqref{eq:Prel-Reduced-Cubic}, we obtain the coefficients $ c = - \ell^{2} $ and $ d = R_{\text{bd}} $ for \eqref{eq:3R-1D2B-S-ISO-MV-Case-I-2-Cubic}. The discriminant evaluates to $ \Delta = 4 \ell^{6} - 27 R_{\text{bd}}^{2} $. Since $ c < 0 $ and $ d > 0 $, applying Lemma \ref{lem:Prel-Reduced-Cubic-Roots-Positive} yields for $ \Delta \geq 0 \iff \ell \geq \widehat{d} $ the positive roots \begin{equation} \label{eq:3R-1D2B-S-ISO-MV-Case-I-2-Cubic-Pos-Roots} \begin{aligned} \mathbb{z}_{\text{p}1} & = \frac{2}{3} \sqrt{3} \cos \BR{\frac{1}{3} \varphi - 120^{\degree}} \ell & \in \left(0, \, \frac{1}{3}\sqrt{3} \right] \ell \\ \mathbb{z}_{\text{p}2} & = \frac{2}{3} \sqrt{3} \cos \BR{\frac{1}{3} \varphi} \ell & \in \left[\frac{1}{3}\sqrt{3}, \, 1\right) \ell , \end{aligned} \end{equation} where $ \varphi = \tan^{-1} \BR{-2 R_{\text{bd}}^{-1} \sqrt{\frac{\Delta}{108}}} \in \left(90^{\degree}, \, 180^{\degree} \right] $. Notice that $ \varphi $ depends on both the desired length $ \ell $ and the gain ratio $ R_{\text{bd}} $. Before considering the different sub-regions for $ \ell $, we also compute the derivative of \eqref{eq:3R-1D2B-S-ISO-MV-Case-I-2-Cubic}, yielding $ f'\BR{\mathbb{z}} = 3 \mathbb{z}^{2} - \ell^{2} $. The roots are $ f'\BR{\mathbb{z}} = 0 \iff \mathbb{z} = \pm \frac{1}{3} \sqrt{3} \ell $. From the first derivative test, the maximum and minimum are found to be $ f_{\max} = f\BR{- \frac{1}{3}\sqrt{3} \ell} = \frac{2}{9} \sqrt{3} \ell^{3} + R_{\text{bd}} > 0 $ and $ f_{\min} = f\BR{\frac{1}{3}\sqrt{3} \ell} = - \frac{2}{9} \sqrt{3} \ell^{3} + R_{\text{bd}} \gtreqqless 0 $. The sign of $ f_{\min} $ depends on the value for $ \ell $. In addition, $ f\BR{0} = f \BR{\ell} = R_{\text{bd}} > 0 $. Now we are ready to consider the different sub-regions of $ \ell $ for $ \mathbb{z} > 0 $: \begin{enumerate} \item $ \ell < \widehat{d} $; ~\\ We only have one local minimum for $ f\BR{\mathbb{z}} $ in the positive range. With $ \ell < \widehat{d} $, it follows $ \ell^{3} < \frac{3}{2} \sqrt{3} R_{\text{bd}} $. Correspondingly, we have $ f_{\min} = - \frac{2}{9} \sqrt{3} \ell^{3} + R_{\text{bd}} > 0 $ implying that $ f\BR{\mathbb{z}} > 0 $ for all $ \mathbb{z} > 0 $. \item $ \ell = \widehat{d} $; ~\\ With $ \Delta = 0 $, we obtain $ \varphi = 180^{\degree} $; the positive roots \eqref{eq:3R-1D2B-S-ISO-MV-Case-I-2-Cubic-Pos-Roots} are equal and have value $ \mathbb{z}_{\text{p}1} = \mathbb{z}_{\text{p}2} = \frac{1}{3} \sqrt{3} \ell $. Also, the minimum of $ f\BR{\mathbb{z}} $ occurs at this point, i.e., $ f\BR{\mathbb{z}_{\text{p1}}} = f\BR{\mathbb{z}_{\text{p2}}} = 0 = f_{\min} $. We thus have $ f\BR{\mathbb{z}} \geq 0 $ for all $ \mathbb{z} > 0$. \item $ \ell > \widehat{d} $; ~\\ For $ \ell > \widehat{d} $, we have two distinct positive roots in \eqref{eq:3R-1D2B-S-ISO-MV-Case-I-2-Cubic-Pos-Roots}. Also, it follows $ \ell^{3} > \frac{3}{2} \sqrt{3} R_{\text{bd}} $. Correspondingly, we have $ f_{\min} = - \frac{2}{9} \sqrt{3} \ell^{3} + R_{\text{bd}} < 0 $. We note that $ \mathbb{z} = \frac{1}{3}\sqrt{3} $ lies in the region $ \BR{\mathbb{z}_{\text{p}1}, \, \mathbb{z}_{\text{p}2}} $. The function $ f\BR{\mathbb{z}} $ thus takes values \begin{equation} \label{eq:3R-1D2B-S-ISO-MV-Case-I-2-Cubic-Value-l>d} f\BR{\mathbb{z}} = \begin{cases} > 0 & \text{if } \mathbb{z} \in \BR{0, \, \mathbb{z}_{\text{p}1}} \cup \BR{\mathbb{z}_{\text{p}2}, \, \infty} \\ = 0 & \text{if } \mathbb{z} \in \CBR{\mathbb{z}_{\text{p}1}, \, \mathbb{z}_{\text{p}2}} \\ < 0 & \text{if } \mathbb{z} \in \BR{\mathbb{z}_{\text{p}1}, \, \mathbb{z}_{\text{p}2}} . \end{cases} \end{equation} \end{enumerate} This completes the proof. \end{proof} Since $ \mathbb{z} = \mathbb{r} \ell $, we obtain the following corollary: \begin{corollary} \label{cor:3R-1D2B-S-MV-Cubic-Equation-r} The cubic function $ f $ in \eqref{eq:3R-1D2B-S-ISO-MV-Case-I-2-Cubic} takes on values $ f\BR{\mathbb{r}} > 0 $ when $ \ell < \widehat{d} $, $ f\BR{\mathbb{r}} \geq 0 $ when $ \ell = \widehat{d} $ and for $ \ell > \widehat{d} $, we have \begin{equation} \label{eq:3R-1D2B-S-ISO-MV-Case-I-2-Cubic-Value-l>d-r} f\BR{\mathbb{r}} = \begin{cases} > 0 & \text{if } \mathbb{r} \in \BR{0, \, \mathbb{r}_{1}} \cup \BR{\mathbb{r}_{2}, \, \infty} \\ = 0 & \text{if } \mathbb{r} \in \CBR{\mathbb{r}_{1}, \, \mathbb{r}_{2}} \\ < 0 & \text{if } \mathbb{r} \in \BR{\mathbb{r}_{1}, \, \mathbb{r}_{2}} , \end{cases} \end{equation} where $ \mathbb{r}_{1} = \frac{2}{3} \sqrt{3} \cos \BR{\frac{1}{3} \varphi - 120^{\degree}} \in \left(0, \, \frac{1}{3}\sqrt{3} \right) $, $ \mathbb{r}_{2} = \frac{2}{3} \sqrt{3} \cos \BR{\frac{1}{3} \varphi} \in \left(\frac{1}{3}\sqrt{3}, \, 1 \right) $, and \\ $ \varphi\BR{\ell, \, R_{\text{bd}}} = \tan^{-1} \BR{-2 R_{\text{bd}}^{-1} \sqrt{\frac{\Delta}{108}}} \in \left(90^{\degree}, \, 180^{\degree} \right) $. \end{corollary} In the upcoming sections, we will study more in detail the set of equations for the equilibrium and the moving configurations for acute, right, and obtuse isosceles triangles. \section{Acute Isosceles Triangles} \label{sec:Isosceles-Triangle-Analysis-Acute} Herein, we focus on acute isosceles triangles in which the vertex angle $ \theta^{\star} $ is in the range $ \theta^{\star} \in \BR{0, \, 90^{\degree}} \iff \cos \theta^{\star} \in \BR{0, \, 1} $. \subsection{Equilibrium configurations} Previously, we have shown in Proposition \ref{prop:3R-1D2B-S-ISO-EQ-Conditions-I} that when distance robot \texttt{R1} attains one of its assigned tasks, it is equivalent to attaining all its assigned tasks. We investigate now whether there exist equilibrium configurations in which none of the tasks assigned to \texttt{R1} is attained. The following proposition provides necessary conditions which the variables $ x $, $ y $, and the product $ xy $ are required to satisfy: \begin{proposition} \label{prop:3R-1D2B-S-ISO-EQ-Conditions-II} Assume $ x \neq 1 $, $ y \neq 1 $, $ xy \neq 1 $, and $ x \neq y $, where $ x $ and $ y $ are defined in \eqref{eq:3R-1D2B-S-ISO-EQ-PAR-XY}. Define $ \mathbb{A} = x \cos \theta^{\star} - y $ and $ \mathbb{B} = y \cos \theta^{\star} - x $. For the existence of equilibrium configurations in \eqref{eq:3R-1D2B-S-ISO-EQ-g12-g13-Set} satisfying the given constraints, we require that $ xy - 1 > 0 $ in combination with either $ 1). $ $ x > 1 $, $ y < 1 $, and $ \mathbb{A} > 0 $ or $ 2). $ $ x < 1 $, $ y > 1 $, and $ \mathbb{B} > 0 $. \end{proposition} \begin{proof} By direct computation, the following two relations hold: $ 1). $ $ \mathbb{A} \geq 0 \implies \mathbb{B} < 0 $, and $ 2). $ $ \mathbb{B} \geq 0 \implies \mathbb{A} < 0 $. Due to $ x \neq 1 $, we cannot have $ \mathbb{A} = 0 $. Similarly, with $ y \neq 1 $, $ \mathbb{B} = 0 $ does not hold. Also, the combination $ \mathbb{A} < 0 $ and $ \mathbb{B} < 0 $ cannot hold since assuming $ xy - 1 > 0 $ on the RHS of \eqref{eq:3R-1D2B-S-ISO-EQ-g12-g13-Set} yields $ x < 1 $ and $ y < 1 $ on the LHS. With $ x < 1 $ and $ y < 1 $, we obtain $ xy < 1 $ and this contradicts the assumption $ xy - 1 > 0 $. Similar argument holds when $ xy - 1 < 0 $ is taken. The remaining feasible combinations are then $ \mathbb{A} > 0 \, \wedge \, \mathbb{B} < 0 $ and $ \mathbb{A} < 0 \, \wedge \, \mathbb{B} > 0 $. It follows that on the LHS, we either have the combination $ x < 1 \, \wedge \, y > 1 $ or $ x > 1 \, \wedge \, y < 1 $. This depends on the sign of $ xy - 1 $ as follows: \begin{enumerate} \item $ xy - 1 > 0 $; \begin{enumerate} \item $ \mathbb{A} > 0 \, \wedge \, \mathbb{B} < 0 $ results in $ x > 1 \, \wedge \, y < 1 $. \item $ \mathbb{A} < 0 \, \wedge \, \mathbb{B} > 0 $ results in $ x < 1 \, \wedge \, y > 1 $. \end{enumerate} \item $ xy - 1 < 0 $; \begin{enumerate} \item $ \mathbb{A} > 0 \, \wedge \, \mathbb{B} < 0 $ results in $ x < 1 \, \wedge \, y > 1 $. \item $ \mathbb{A} < 0 \, \wedge \, \mathbb{B} > 0 $ results in $ x > 1 \, \wedge \, y < 1 $. \end{enumerate} \end{enumerate} Consider now the cases where $ xy - 1 < 0 $. Assuming $ \mathbb{A} > 0 $ leads to $ y < x $. However, we have found $ x < 1 \, \wedge \, y > 1 $ on the LHS implying $ x < y $ and hence a contradiction. With $ \mathbb{B} > 0 $, we infer $ x < y $ while based on the signs of $ x $ and $ y $ on the LHS, we have $ y < x $ and again a contradiction. For $ xy - 1 > 0 $, we can find feasible values for $ x $ and $ y $ satisfying the listed constraints. This completes the proof. \end{proof} A proper choice for the gain ratio $ R_{\text{Ad}} $ can prevent the occurrence of equilibrium points satisfying the conditions in Proposition \ref{prop:3R-1D2B-S-ISO-EQ-Conditions-II}: \begin{lemma} \label{lem:3R-1D2B-S-ISO-EQ-Main-Acute} Consider a team of three robots moving according to \eqref{eq:3R-1D2B-S-p-Dynamics} with $ K_{\text{d}} > 0 $, $ K_{\text{b}} > 0 $, and $ K_{\text{A}} > 0 $. Define the gain ratio $ R_{\text{Ad}} = \frac{K_{\text{A}}}{K_{\text{d}}} $. Furthermore, let the desired formation shape be an isosceles triangle with legs $ \ell > 0 $ and vertex angle $ \theta^{\star} \in \BR{0^{\degree}, \, 90^{\degree}} $. Finally, parametrize the distances $ d_{12} $ and $ d_{13} $ as in \eqref{eq:3R-1D2B-S-ISO-EQ-PAR-XY}. If $ R_{\text{Ad}} \leq \frac{6}{1 + \cos \theta^{\star}} $, then the equilibrium configurations $ p_{\text{eq}} $ are the desired ones in $ \mathcal{S}_{p} $ in which all the individual assigned tasks are attained. \end{lemma} \begin{proof} We first consider \eqref{eq:3R-1D2B-S-ISO-EQ-g12-g13-Diff}. Rearranging the terms yields \begin{equation} \label{eq:3R-1D2B-S-ISO-EQ-g12-g13-Diff-V2} \begin{aligned} x^{2} + y^{2} + \BR{1 - \mathbb{d}} \BR{xy - 1} & = 0 , \end{aligned} \end{equation} where $ \mathbb{d} = \frac{1}{2} R_{\text{Ad}} \BR{1 + \cos \theta^{\star}} > 0 $. Since $ x > 0 $, $ y > 0 $, and $ xy - 1 > 0 $ from Proposition \ref{prop:3R-1D2B-S-ISO-EQ-Conditions-II}, it follows that $ 1 - \mathbb{d} \geq 0 \iff \mathbb{d} \leq 1 $ will yield the LHS to be positive and hence no feasible combination $ \BR{x, \, y} $ for \eqref{eq:3R-1D2B-S-ISO-EQ-g12-g13-Diff-V2}. Adding and subtracting $ 2 xy $ to \eqref{eq:3R-1D2B-S-ISO-EQ-g12-g13-Diff-V2} yields \begin{equation} \label{eq:3R-1D2B-S-ISO-EQ-g12-g13-Diff-V3} \BR{x - y}^{2} + \BR{3 - \mathbb{d}} xy - \BR{1 - \mathbb{d}} = 0. \end{equation} Choosing $ \mathbb{d} $ in the range $ \left(1, \, 3\right] $, we obtain that all terms on the LHS are non-negative and at least one term is positive; their sum is then also positive and hence we have no feasible combination $ \BR{x, \, y} $ for \eqref{eq:3R-1D2B-S-ISO-EQ-g12-g13-Diff-V3}. Notice that $ \mathbb{d} \leq 3 \iff R_{\text{Ad}} \leq \frac{6}{1 + \cos \theta^{\star}} $. Since solutions to \eqref{eq:3R-1D2B-S-ISO-EQ-g12-g13-Set} should naturally satisfy \eqref{eq:3R-1D2B-S-ISO-EQ-g12-g13-Diff}, we infer that provided $ R_{\text{Ad}} \leq \frac{6}{1 + \cos \theta^{\star}} $, we do not have a feasible combination $ \BR{x, \, y} $ with $ x \neq y $ satisfying \eqref{eq:3R-1D2B-S-ISO-EQ-g12-g13-Set}. The only possible combination for $ x = y $ is the pair $ \BR{x, \, y} = \BR{1, \, 1} $ which corresponds to robot \texttt{R1} satisfying all its assigned tasks. As robots \texttt{R2} and \texttt{R3} also attain its individual task, we conclude that all robots in the team attain its individual tasks; i.e., $ e = \mathbb{0}_{7} $. This completes the proof. \end{proof} Since we are dealing with acute isosceles triangles, we obtain that the upper bound for $ R_{\text{Ad}} $ in Lemma \ref{lem:3R-1D2B-S-ISO-EQ-Main-Acute} is in the range $ \frac{6}{1 + \cos \theta^{\star}} \in \BR{3, \, 6} $. This seems rather limited. Moreover, in obtaining feasible ranges for $ R_{\text{Ad}} $ in Lemma \ref{lem:3R-1D2B-S-ISO-EQ-Main-Acute}, we only made use of the condition that the product $ xy $ is larger than $ 1 $ while no specific constraints on $ x $ and $ y $ in Proposition \ref{prop:3R-1D2B-S-ISO-EQ-Conditions-II} were utilized. We could ask ourselves $ 1). $ whether we can expand the region of $ R_{\text{Ad}} $ by taking into account all the conditions provided in Proposition \ref{prop:3R-1D2B-S-ISO-EQ-Conditions-II}. If there are still feasible combinations $ \BR{x, \, y} $ solving \eqref{eq:3R-1D2B-S-ISO-EQ-g12-g13-Diff} while at the same time satisfying all the conditions in Proposition \ref{prop:3R-1D2B-S-ISO-EQ-Conditions-II} with $ \mathbb{d} > 3 $, then a follow-up question would be $ 2). $ whether these particular combinations $ \BR{x, \, y} $ would solve the set of equations \eqref{eq:3R-1D2B-S-ISO-EQ-g12-g13-Set}. For now, we focus on the set of constraints $ x > 1 $, $ y < 1 $, $ \mathbb{A} > 0 $, and $ xy -1 > 0 $ in Proposition \ref{prop:3R-1D2B-S-ISO-EQ-Conditions-II}. For a fixed value $ x = \bar{x} > 1 $, we obtain as solutions to \eqref{eq:3R-1D2B-S-ISO-EQ-g12-g13-Diff-V2} \begin{equation} \label{eq:3R-1D2B-S-ISO-EQ-g12-g13-Diff-Roots} y = \frac{\mathbb{d} - 1}{2} \bar{x} \pm \frac{1}{2} \sqrt{\BR{\BR{\mathbb{d} + 1} \BR{\mathbb{d} - 3}}\bar{x}^{2} - 4\BR{\mathbb{d} - 1}} . \end{equation} With $ \mathbb{d} > 3 $, we have $ \frac{\mathbb{d} - 1}{2} > 1 $. The feasible value for $ y $ which could satisfy $ y < 1 $ is then $ \bar{y} = \mathbb{a} \bar{x} - \mathbb{b} $ with $ \mathbb{a} = \frac{\mathbb{d} - 1}{2} $ and $ \mathbb{b} = \frac{1}{2} \sqrt{\BR{\BR{\mathbb{d} + 1} \BR{\mathbb{d} - 3}}\bar{x}^{2} - 4\BR{\mathbb{d} - 1}} $ since the alternative $ y = \mathbb{a} \bar{x} + \mathbb{b} > \bar{x} > 1 $ and thus violates the constraint. We observe that for specific choices on the values $ \bar{x} > 1 $ and $ \mathbb{d} > 3 $, we have that $ \bar{y} $ satisfies the required constraints. Hence it is possible to find combinations $ \BR{\bar{x}, \, \bar{y}} $ solving the difference equation \eqref{eq:3R-1D2B-S-ISO-EQ-g12-g13-Diff-V2} while satisfying the required constraints. The second question now is whether these feasible combinations $ \BR{\bar{x}, \bar{y}} $ are also solutions to the set of equations \eqref{eq:3R-1D2B-S-ISO-EQ-g12-g13-Set}. Substituting and rearranging the terms yield \begin{equation} \label{eq:3R-1D2B-S-ISO-EQ-g12-g13-Diff-Back} \frac{1}{1 + \cos \theta^{\star}}\BR{\mathbb{k} \bar{x}^{3} + \mathbb{l} \bar{x}^{2} + \mathbb{m} \bar{x} + \mathbb{n}} = 0 , \end{equation} where \begin{equation} \label{eq:3R-1D2B-S-ISO-EQ-g12-g13-Diff-Back-Coeff} \begin{aligned} \mathbb{k} & = \frac{1}{2} \BR{\mathbb{d} - 2} \BR{\mathbb{d} + 1} \BR{\mathbb{d} - \BR{1 + \cos \theta^{\star}}} \\ \mathbb{l} & = - \mathbb{b} \, \mathbb{d} \BR{\mathbb{d} - \BR{1 + \cos \theta^{\star}}} \\ \mathbb{m} & = - \frac{1}{2} \BR{\BR{3\mathbb{d} - 2 \cos \theta^{\star}} \BR{\mathbb{d} - 1} + 2} \\ \mathbb{n} & = \mathbb{b} \, \mathbb{d} . \end{aligned} \end{equation} With $ \mathbb{d} > 3 $, we obtain $ \mathbb{k} > 0 $, $ \mathbb{l} < 0 $, $ \mathbb{m} < 0 $, and $ \mathbb{n} > 0 $. Hence we can not provide conclusions on the sign of the cubic term $ \mathbb{k} \bar{x}^{3} + \mathbb{l} \bar{x}^{2} + \mathbb{m} \bar{x} + \mathbb{n} $ on the LHS of \eqref{eq:3R-1D2B-S-ISO-EQ-g12-g13-Diff-Back}. In Section \ref{sec:Numerical-Example}, we will numerically evaluate this term. Considering the set of constraints $ y > 1 $, $ x < 1 $, $ \mathbb{B} > 0 $, and $ xy -1 > 0 $ in Proposition \ref{prop:3R-1D2B-S-ISO-EQ-Conditions-II}, we would have obtained the same result but with the roles for $ x $ and $ y $ reversed. \subsection{Moving configurations} Consider the equations for the moving configurations and again, let $ \mathbb{A} = x \cos \theta^{\star} - y $ and $ \mathbb{B} = y \cos \theta^{\star} - x $. We obtain $ \mathbb{A} \geq 0 \implies \mathbb{B} < 0 $ and $ \mathbb{B} \geq 0 \implies \mathbb{A} < 0 $. Since $ x > 0 $, $ y > 0 $, and $ R_{\text{Ad}} > 0 $, it follows that if one of the RHS is non-negative in \eqref{eq:3R-1D2B-S-ISO-MV-g12-g13-Set}, then the RHS of the other equation needs to be negative. From Proposition \ref{prop:3R-1D2B-S-ISO-MV-Cubic-Equation-z}, we obtain that the LHS can be negative only when the legs of the isosceles triangle satisfy $ \ell > \widehat{d} $. In particular, following Corollary \ref{cor:3R-1D2B-S-MV-Cubic-Equation-r}, the cubic equation on the LHS is negative in the range $ \BR{\mathbb{r}_{1}, \, \mathbb{r}_{2}} $. When $ \ell \leq \widehat{d} $, we do not have feasible combinations $ \BR{x, \, y} $ for the set of equations \eqref{eq:3R-1D2B-S-ISO-MV-g12-g13-Set} and hence the non-existence of moving configurations. Assume without loss of generality $ x \in \BR{\mathbb{r}_{1}, \, \mathbb{r}_{2}} $. For $ y \leq \mathbb{r}_{1} $, we know the LHS of the second equation in \eqref{eq:3R-1D2B-S-ISO-MV-g12-g13-Set} is positive. On the RHS, we require $ \mathbb{B} \geq 0 \implies x < y \implies x < \mathbb{r}_{1} $. This contradicts our assumption that $ x \in \BR{\mathbb{r}_{1}, \, \mathbb{r}_{2}} $ and hence we require $ y > \mathbb{r}_{1} $. Following Corollary \ref{cor:3R-1D2B-S-MV-Cubic-Equation-r}, we can divide $ y > \mathbb{r}_{1} $ in the three regions $ y \in \BR{\mathbb{r}_{1}, \, \mathbb{r}_{2}} $, $ y = \mathbb{r}_{2} $, and $ y > \mathbb{r}_{2} $. Before getting into the analysis, we provide the following result concerning the difference equation of \eqref{eq:3R-1D2B-S-ISO-MV-g12-g13-Set}: \begin{proposition} \label{prop:3R-1D2B-S-ISO-MV-g12-g13-Diff-SOL} Let $ x \in \BR{\mathbb{r}_{1}, \, \mathbb{r}_{2}} < 1 $ in \eqref{eq:3R-1D2B-S-ISO-MV-g12-g13-Diff} and $ \mathbb{d} = \frac{1}{2} R_{\text{Ad}} \BR{1 + \cos \theta^{\star}} $. We have the following statements: \begin{enumerate} \item Case: $ y \leq 1 $; ~\\ If $ \mathbb{d} \geq 1 \iff R_{\text{Ad}} \geq \frac{2}{1 + \cos \theta^{\star}} $, then there are no feasible combinations $ \BR{x, \, y} $ that satisfy \eqref{eq:3R-1D2B-S-ISO-MV-g12-g13-Diff}. \item Case: $ y > 1 $; ~\\ If $ \mathbb{d} \geq 3 \iff R_{\text{Ad}} \geq \frac{6}{1 + \cos \theta^{\star}} $, then the combination $ \BR{\bar{x}, \, \bar{y}} $ where $ \bar{y} = \mathbb{a}\bar{x} + \mathbb{b} $ with $ \mathbb{a} = \frac{\mathbb{d} - 1}{2} $ and $ \mathbb{b} = \frac{1}{2} \sqrt{\BR{\mathbb{d} + 1}\BR{\BR{\mathbb{d} - 3}\bar{x}^{2} + 4}} $ satisfies \eqref{eq:3R-1D2B-S-ISO-MV-g12-g13-Diff}. \end{enumerate} \end{proposition} \begin{proof} Rearranging the terms in \eqref{eq:3R-1D2B-S-ISO-MV-g12-g13-Diff} yields \begin{equation} \label{eq:3R-1D2B-S-ISO-MV-g12-g13-Diff-V2} \begin{aligned} x^{2} + y^{2} + \BR{1 - \mathbb{d}} xy = 1 + \mathbb{d} . \end{aligned} \end{equation} \begin{enumerate} \item Case: $ y \leq 1 $; ~\\ Choosing $ \mathbb{d} \geq 1 $, we have $ \BR{1 - \mathbb{d}} \leq 0 $. The LHS of \eqref{eq:3R-1D2B-S-ISO-MV-g12-g13-Diff-V2} has upper bound $ x^{2} + y^{2} + \BR{1 - \mathbb{d}} xy \leq x^{2} + y^{2} < 2 $ while the RHS has a value $ \BR{1 + \mathbb{d}} \geq 2 $. We infer $ \mathbb{d} \geq 1 \iff R_{\text{Ad}} \geq \frac{2}{1 + \cos \theta^{\star}} $ yields no solution for \eqref{eq:3R-1D2B-S-ISO-MV-g12-g13-Diff-V2}. \item Case: $ y > 1 $; ~\\ We consider a specific value for $ x = \bar{x} $ in the given range. Note that $ \bar{x} < 1 $. Solving \eqref{eq:3R-1D2B-S-ISO-MV-g12-g13-Diff-V2} for the unknown $ y $, we obtain \begin{equation} \label{eq:3R-1D2B-S-ISO-MV-g12-g13-Diff-Roots} y = \frac{\mathbb{d} - 1}{2} \bar{x} \pm \frac{1}{2} \sqrt{\BR{\mathbb{d} + 1} \BR{\BR{\mathbb{d} - 3} \bar{x}^{2} + 4}} . \end{equation} With $ \mathbb{d} \geq 3 $, we have that the term under the square root is positive. Also, $ \frac{\mathbb{d} - 1}{2} \geq 1 $. Applying Descartes' rule of signs, we infer that for $ \mathbb{d} \geq 3 $, we have one positive and one negative root. The positive root is then $ \bar{y} = \frac{\mathbb{d} - 1}{2} \bar{x} + \frac{1}{2} \sqrt{\BR{\mathbb{d} + 1} \BR{\BR{\mathbb{d} - 3} \bar{x}^{2} + 4}} $. \end{enumerate} This completes the proof. \end{proof} For moving configurations, we state the following result: \begin{lemma} \label{lem:} \label{lem:3R-1D2B-S-ISO-MV-Main-Acute} Consider a team of three robots moving according to \eqref{eq:3R-1D2B-S-p-Dynamics} with specific gains $ K_{\text{d}} > 0 $ and $ K_{\text{b}} > 0 $. Define the gain ratios $ R_{\text{bd}} = \frac{K_{\text{b}}}{K_{\text{d}}} $ and $ R_{\text{Ad}} = \frac{K_{\text{A}}}{K_{\text{d}}} $ with $ K_{\text{A}} > 0 $, and $ \widehat{d} = \sqrt{3} \sqrt[3]{\frac{R_{\text{bd}}}{2}} $. Furthermore, let the desired formation shape be an isosceles triangle with legs $ \ell > \widehat{d} $ and vertex angle $ \theta^{\star} \in \BR{0^{\degree}, \, 90^{\degree}} $. Finally, assume $ x \in \BR{\mathbb{r}_{1}, \, \mathbb{r}_{2}} $ and $ y > \mathbb{r}_{1} $, where $ x $ and $ y $ are defined in \eqref{eq:3R-1D2B-S-ISO-EQ-PAR-XY}. If $ R_{\text{Ad}} \geq \max \CBR{\frac{6}{1 + \cos \theta^{\star}}, \, \frac{2}{1 - \cos \theta^{\star}}} $, then there are no feasible combinations $ \BR{x, \, y} $ satisfying the set of equations \eqref{eq:3R-1D2B-S-ISO-MV-g12-g13-Set}. \end{lemma} \begin{proof} The proof will be given for the three regions of $ y > \mathbb{r}_{1} $ obtained from Corollary \ref{cor:3R-1D2B-S-MV-Cubic-Equation-r}: \begin{enumerate} \item $ x \in \BR{\mathbb{r}_{1}, \, \mathbb{r}_{2}} $ and $ y \in \BR{\mathbb{r}_{1}, \, \mathbb{r}_{2}} $; ~\\ In this region, we can divide the analysis to the cases $ x = y $ and $ x \neq y $: \begin{enumerate} \item Case: $ x = y $; ~\\ Rearranging the terms in \eqref{eq:3R-1D2B-S-ISO-MV-g12-g13-Equal} yields \begin{equation} \label{eq:3R-1D2B-S-ISO-MV-g12-g13-Equal-Acute} \begin{aligned} & x \ell^{3} \BR{\BR{\mathbb{c} + 1} x^{2} + \BR{\mathbb{c} - 1}} + R_{\text{bd}} = 0 , \end{aligned} \end{equation} where $ \mathbb{c} = \frac{1}{2} R_{\text{Ad}} \BR{1 - \cos \theta^{\star}} $. Choosing $ \mathbb{c} \geq 1 $, we have $ \BR{\mathbb{c} + 1} \geq 2 $ and $ \BR{\mathbb{c} - 1} \geq 0 $. Therefore, all terms in \eqref{eq:3R-1D2B-S-ISO-MV-g12-g13-Equal-Acute} are non-negative and at least one term is positive; then the sum on the LHS is also positive. The equation \eqref{eq:3R-1D2B-S-ISO-MV-g12-g13-Equal-Acute} does not have roots for $ \mathbb{c} \geq 1 \iff R_{\text{Ad}} \geq \frac{2}{1 - \cos \theta^{\star}} $. \item Case: $ x \neq y $; ~\\ Since both $ x < 1 $ and $ y < 1 $, it follows from Proposition \ref{prop:3R-1D2B-S-ISO-MV-g12-g13-Diff-SOL} that the difference equation \eqref{eq:3R-1D2B-S-ISO-MV-g12-g13-Diff} does not have a solution when the gain ratio $ R_{\text{Ad}} $ satisfies $ R_{\text{Ad}} \geq \frac{2}{1 + \cos \theta^{\star}} $, This implies that the set of equations \eqref{eq:3R-1D2B-S-ISO-MV-g12-g13-Set} also does not have a solution. \end{enumerate} Combining both cases, we infer that $ R_{\text{Ad}} \geq \frac{2}{1 - \cos \theta^{\star}} $ will yield no feasible combinations $ \BR{x, \, y} $ for \eqref{eq:3R-1D2B-S-ISO-MV-g12-g13-Set}. \item $ x \in \BR{\mathbb{r}_{1}, \, \mathbb{r}_{2}} $ and $ y = \mathbb{r}_{2} $; ~\\ We have $ x < 1 $ and $ y = \mathbb{r}_{2} < 1 $. From Proposition \ref{prop:3R-1D2B-S-ISO-MV-g12-g13-Diff-SOL}, we infer that when $ R_{\text{Ad}} \geq \frac{2}{1 + \cos \theta^{\star}} $, we have no feasible combinations $ \BR{x, \, y} $ for \eqref{eq:3R-1D2B-S-ISO-MV-g12-g13-Set}. \item $ x \in \BR{\mathbb{r}_{1}, \, \mathbb{r}_{2}} $ and $ y > \mathbb{r}_{2} $; ~\\ We can divide the region for $ y $ in two sub-regions, namely $ \mathbb{r_{2}} < y \leq 1 $ and $ y > 1 $. \begin{enumerate} \item Case: $ y \in \left(\mathbb{r}_{2}, \, 1\right] $; ~\\ Since $ x < 1 $ and $ y \leq 1 $, following Proposition \ref{prop:3R-1D2B-S-ISO-MV-g12-g13-Diff-SOL}, we infer $ R_{\text{Ad}} \geq \frac{2}{1 + \cos \theta^{\star}} $ is sufficient to obtain no feasible combinations $ \BR{x, \, y} $ for \eqref{eq:3R-1D2B-S-ISO-MV-g12-g13-Set}. \item Case: $ y > 1 $; ~\\ With the particular choice $ R_{\text{Ad}} \geq \frac{6}{1 + \cos \theta^{\star}} \iff \mathbb{d} \geq 3 $ from Proposition \ref{prop:3R-1D2B-S-ISO-MV-g12-g13-Diff-SOL}, we obtain $ \bar{y} = \mathbb{a}\bar{x} + \mathbb{b} $ with $ \mathbb{a} = \frac{\mathbb{d} - 1}{2} $ and $ \mathbb{b} = \frac{1}{2} \sqrt{\BR{\mathbb{d} + 1} \BR{\BR{\mathbb{d} - 3} \bar{x}^{2} + 4}} $ is the solution to \eqref{eq:3R-1D2B-S-ISO-MV-g12-g13-Diff} for a fixed $ \bar{x} $. Substituting the obtained pair $ \BR{\bar{x}, \, \bar{y}} $ back in \eqref{eq:3R-1D2B-S-ISO-MV-g12-g13-Set} yields \begin{equation} \label{eq:3R-1D2B-S-ISO-MV-g12-g13-Diff-Back} \frac{1}{1 + \cos \theta^{\star}}\BR{\mathbb{k} \bar{x}^{3} + \mathbb{l} \bar{x}^{2} + \mathbb{m} \bar{x} + \mathbb{n}} \ell^{3} + R_{\text{bd}} = 0 , \end{equation} where \begin{equation} \label{eq:3R-1D2B-S-ISO-MV-g12-g13-Diff-Back-Coeff} \begin{aligned} \mathbb{k} & = \frac{1}{2} \BR{\mathbb{d} - 2} \BR{\mathbb{d} + 1} \BR{\mathbb{d} - \BR{1 + \cos \theta^{\star}}} \\ \mathbb{l} & = \mathbb{b} \, \mathbb{d} \BR{\mathbb{d} - \BR{1 + \cos \theta^{\star}}} \\ \mathbb{m} & = \frac{1}{2} \BR{\mathbb{d} + 1} \BR{3 \mathbb{d} - 2\BR{1 + \cos \theta^{\star}}} \\ \mathbb{n} & = \mathbb{b} \, \mathbb{d} \end{aligned} \end{equation} With $ \mathbb{d} \geq 3 $, we obtain $ \mathbb{k} > 0 $, $ \mathbb{l} > 0 $, $ \mathbb{m} > 0 $, and $ \mathbb{n} > 0 $. Since the individual terms are positive, it follows the sum is also positive; the combination $ \BR{\bar{x}, \, \bar{y}} $ satisfying \eqref{eq:3R-1D2B-S-ISO-MV-g12-g13-Diff} is not a solution to \eqref{eq:3R-1D2B-S-ISO-MV-g12-g13-Set}. So solutions to \eqref{eq:3R-1D2B-S-ISO-MV-g12-g13-Set} are of the form $ \BR{x, \, y} \neq \BR{\bar{x}, \, \bar{y}} $. However, these will not solve \eqref{eq:3R-1D2B-S-ISO-MV-g12-g13-Diff} and therefore, we conclude that for $ R_{\text{Ad}} \geq \frac{6}{1 + \cos \theta^{\star}} $, the solution set to \eqref{eq:3R-1D2B-S-ISO-MV-g12-g13-Set} is empty for the mentioned region of $ x $ and $ y $. \end{enumerate} Combining the results of both parts, we obtain that $ R_{\text{Ad}} \geq \frac{6}{1 + \cos \theta^{\star}} $ is sufficient to obtain no feasible combinations $ \BR{x, \, y} $ for \eqref{eq:3R-1D2B-S-ISO-MV-g12-g13-Set}. \end{enumerate} Gathering the results for all the three considered regions for $ y $, we conclude that $ R_{\text{Ad}} \geq \max \CBR{\frac{6}{1 + \cos \theta^{\star}}, \, \frac{2}{1 - \cos \theta^{\star}}} $. This completes the proof. \end{proof} From a design perspective, provided $ \ell $ is given, we can tune the gains $ K_{\text{d}} $ and $ K_{\text{b}} $ such that $ \ell \leq \widehat{d} $ is satisfied. In this scenario, any choice of $ K_{\text{A}} > 0 $ would yield no solutions $ \BR{x, \, y} $ to the set of equations \eqref{eq:3R-1D2B-S-ISO-MV-g12-g13-Set}. This is in agreement with our earlier work \cite{Chan2020} in which moving configurations may occur only when $ d_{12}^{\star} \geq \widehat{d} $ and $ d_{13}^{\star} \geq \widehat{d} $ hold. We need Lemma \ref{lem:3R-1D2B-S-ISO-MV-Main-Acute} when tuning the gains $ K_{\text{d}} $ and $ K_{\text{b}} $ only is not enough. It provides a lower bound on the gain $ K_{\text{A}} $ for a chosen $ K_{\text{d}} $. In the region $ \theta^{\star} \in \left[60^{\degree}, \, 90^{\degree} \right) $, this lower bound is $ K_{\text{A}} \geq \frac{6}{1 + \cos \theta^{\star}} K_{\text{d}} $ while $ K_{\text{A}} \geq \frac{2}{1 - \cos \theta^{\star}} K_{\text{d}}$ when the vertex angle is $ \theta^{\star} \in \BR{0, \, 60} $ in Lemma \ref{lem:3R-1D2B-S-ISO-MV-Main-Acute}. Furthermore, Proposition \ref{prop:3R-1D2B-S-ISO-MV-g12-g13-Diff-SOL} and Lemma \ref{lem:3R-1D2B-S-ISO-MV-Main-Acute} are results which hold for $ x \in \BR{\mathbb{r}_{1}, \, \mathbb{r}_{2}} $ and $ y > \mathbb{r}_{1} $. For the case $ y \in \BR{\mathbb{r}_{1}, \, \mathbb{r}_{2}} $ and $ x > \mathbb{r}_{1} $, we obtain the same result, albeit the roles of $ x $ and $ y $ are reversed. We conclude this section with the following main result: \begin{theorem} \label{thm:3R-1D2B-S-Global-Convergence-Acute} Consider a team of three robots moving according to \eqref{eq:3R-1D2B-S-p-Dynamics} with $ K_{\text{d}} > 0 $, $ K_{\text{b}} > 0 $, and $ K_{\text{A}} > 0 $. Define the gain ratios $ R_{\text{bd}} = \frac{K_{\text{b}}}{K_{\text{d}}} $ and $ R_{\text{Ad}} = \frac{K_{\text{A}}}{K_{\text{d}}} $, and also $ \widehat{d} = \sqrt{3} \sqrt[3]{\frac{R_{\text{bd}}}{2}} $. Let the desired formation shape be an acute isosceles triangle with legs $ \ell > 0 $ and vertex angle $ \theta^{\star} $. Finally, parametrize the distances $ d_{12} $ and $ d_{13} $ as in \eqref{eq:3R-1D2B-S-ISO-EQ-PAR-XY}. Then, starting from all feasible initial configurations, the robots converge to a desired equilibrium configuration $ p_{\text{eq}} \in \mathcal{S}_{p} $ in which all the individual tasks are attained if either $ \BR{K_{\text{d}}, \, K_{\text{b}}, \, K_{\text{A}}} $ is chosen such that $ \ell \leq \widehat{d} $ and $ R_{\text{Ad}} \leq \frac{6}{1 + \cos \theta^{\star}} $ for $ \theta^{\star} \in \BR{0^{\degree}, \, 90^{\degree}} $ or if $ \BR{K_{\text{d}}, \, K_{\text{b}}, \, K_{\text{A}}} $ is chosen such that $ \ell > \widehat{d} $ and $ R_{\text{Ad}} = \frac{6}{1 + \cos \theta^{\star}} $ for $ \theta^{\star} \in \left[60^{\degree}, \, 90^{\degree} \right) $. \end{theorem} \begin{proof} The proof follows directly from the results obtained in Lemmas \ref{lem:3R-1D2B-S-ISO-EQ-Main-Acute} and \ref{lem:3R-1D2B-S-ISO-MV-Main-Acute}. This completes the proof. \end{proof} With the current constraints imposed on the gain ratio $ R_{\text{Ad}} $, we can not provide convergence results for isosceles triangles with legs $ \ell > \widehat{d} $ and vertex angle $ \theta^{\star} \in \BR{0^{\degree}, \, 60^{\degree}} $. We will numerically evaluate this in Section \ref{sec:Numerical-Example}. \section{Right and Obtuse Isosceles Triangles} \label{sec:Isosceles-Triangle-Analysis-Right-Obtuse} We continue with right and obtuse isosceles triangles in which the vertex angle $ \theta^{\star} $ is in the range $ \theta^{\star} \in \left[90^{\degree}, \, 180^{\degree}\right) \iff \cos \theta^{\star} \in \left(-1, \, 0\right] $. \subsection{Equilibrium configurations} We state the following result on equilibrium configurations for right and obtuse isosceles triangles: \begin{lemma} \label{lem:3R-1D2B-S-ISO-EQ-Main-Right-Obtuse} Consider a team of three robots moving according to \eqref{eq:3R-1D2B-S-p-Dynamics} with gains $ K_{\text{d}} > 0 $, $ K_{\text{b}} > 0 $, and $ K_{\text{A}} > 0 $. Let the desired formation shape be an isosceles triangle with legs $ \ell > 0 $ and vertex angle $ \theta^{\star} \in \left[90^{\degree}, \, 180^{\degree}\right) $. In addition, parametrize the distances $ d_{12} $ and $ d_{13} $ as in \eqref{eq:3R-1D2B-S-ISO-EQ-PAR-XY}. Then the equilibrium configurations $ p_{\text{eq}} $ are all in the desired set $ \mathcal{S}_{p} $. \end{lemma} \begin{proof} Given $ \theta^{\star} \in \left[90^{\degree}, \, 180^{\degree}\right) $, we obtain $ \cos \theta^{\star} \in \left(-1, \, 0\right] $. Correspondingly, in \eqref{eq:3R-1D2B-S-ISO-EQ-g12-g13-Set}, $ \mathbb{A} = x \cos \theta^{\star} - y \leq -y < 0 $ and $ \mathbb{B} = y \cos \theta^{\star} - x \leq -x < 0 $. Assuming $ xy - 1 > 0 $ on the RHS leads to $ x < 1 $ and $ y < 1 $ on the LHS; in turn, this results in $ xy < 1 $ and therefore contradicting the assumption. Similar arguments hold for $ xy - 1 < 0 $. Hence there are no feasible combinations $ \BR{x, \, y} $ satisfying $ xy - 1 \neq 0 $. In addition, it follows from Proposition \ref{prop:3R-1D2B-S-ISO-EQ-Conditions-I} that $ xy - 1 = 0 $ is equivalent to the combination $ \BR{x, \, y} = \BR{1, \, 1} $; Robot \texttt{R1} attains all its assigned tasks. With robots \texttt{R2} and \texttt{R3} also attaining its individual task, we conclude that all robots in the team attain its individual tasks, i.e., $ e = \mathbb{0}_{7} $. This completes the proof. \end{proof} In Lemma \ref{lem:3R-1D2B-S-ISO-EQ-Main-Right-Obtuse}, we do not have to impose additional constraints on the gains $ K_{\text{d}} $, $ K_{\text{b}} $, and $ K_{\text{A}} $ other than that they should be positive. \subsection{Moving configurations} For moving configurations, we observe that the sign on the RHS of \eqref{eq:3R-1D2B-S-ISO-MV-g12-g13-Set} depends only on the terms $ \mathbb{A} = x \cos \theta^{\star} - y $ and $ \mathbb{B} = y \cos \theta^{\star} - x $. Since $ \cos \theta^{\star} \in \left(-1, \, 0\right] $, it follows that $ \mathbb{A} < 0 $ and $ \mathbb{B} < 0 $ implying the RHS of \eqref{eq:3R-1D2B-S-ISO-MV-g12-g13-Set} is negative. For the LHS to be also negative, we require from Proposition \ref{prop:3R-1D2B-S-ISO-MV-Cubic-Equation-z} that the desired length $ \ell $ should satisfy $ \ell > \widehat{d} $. In particular, the LHS is negative when $ x \in \BR{\mathbb{r}_{1}, \, \mathbb{r}_{2}} $ and $ y \in \BR{\mathbb{r}_{1}, \, \mathbb{r}_{2}} $ with $ \mathbb{r}_{1} $ and $ \mathbb{r}_{2} $ given in Corollary \ref{cor:3R-1D2B-S-MV-Cubic-Equation-r}. The following lemma states a condition on $ R_{\text{Ad}} $ for precluding moving configurations when $ \ell > \widehat{d} $: \begin{lemma} \label{lem:3R-1D2B-S-ISO-MV-Main-Right-Obtuse} Consider a team of three robots moving according to \eqref{eq:3R-1D2B-S-p-Dynamics} with specific gains $ K_{\text{d}} > 0 $ and $ K_{\text{b}} > 0 $. Define the gain ratios $ R_{\text{bd}} = \frac{K_{\text{b}}}{K_{\text{d}}} $ and $ R_{\text{Ad}} = \frac{K_{\text{A}}}{K_{\text{d}}} $ with $ K_{\text{A}} > 0 $, and also $ \widehat{d} = \sqrt{3} \sqrt[3]{\frac{R_{\text{bd}}}{2}} $. Furthermore, let the desired formation shape be an isosceles triangle with legs $ \ell > \widehat{d} $ and vertex angle $ \theta^{\star} \in \left[90^{\degree}, \, 180^{\degree}\right) $. Finally, parametrize the distances $ d_{12} $ and $ d_{13} $ as in \eqref{eq:3R-1D2B-S-ISO-EQ-PAR-XY}. If $ R_{\text{Ad}} \geq \frac{2}{1 + \cos \theta^{\star}} $, then there are no feasible combinations $ \BR{x, \, y} $ satisfying the set of equations \eqref{eq:3R-1D2B-S-ISO-MV-g12-g13-Set}. \end{lemma} \begin{proof} The proof is divided in two parts, namely considering $ x = y $ and $ x \neq y $ in the feasible region $ \BR{\mathbb{r}_{1}, \, \mathbb{r}_{2}}^{2} $. \begin{enumerate} \item Case: $ x = y $; ~\\ Rearranging the terms in \eqref{eq:3R-1D2B-S-ISO-MV-g12-g13-Equal} yields \begin{equation} \label{eq:3R-1D2B-S-ISO-MV-g12-g13-Equal-Right-Obtuse} \begin{aligned} & x \ell^{3} \BR{\BR{\mathbb{c} + 1} x^{2} + \BR{\mathbb{c} - 1}} + R_{\text{bd}} = 0 , \end{aligned} \end{equation} where $ \mathbb{c} = \frac{1}{2} R_{\text{Ad}} \BR{1 - \cos \theta^{\star}} $. Choosing $ \mathbb{c} \geq 1 $, we have $ \BR{\mathbb{c} + 1} \geq 2 $ and $ \BR{\mathbb{c} - 1} \geq 0 $. Therefore, all terms in \eqref{eq:3R-1D2B-S-ISO-MV-g12-g13-Equal-Right-Obtuse} are non-negative and at least one term is positive; then, the sum on the LHS is also positive. The equation \eqref{eq:3R-1D2B-S-ISO-MV-g12-g13-Equal-Right-Obtuse} does not have roots for $ \mathbb{c} \geq 1 \iff R_{\text{Ad}} \geq \frac{2}{1 - \cos \theta^{\star}} $. \item Case: $ x \neq y $; ~\\ It follows from Proposition \ref{prop:3R-1D2B-S-ISO-MV-g12-g13-Diff-SOL} that \eqref{eq:3R-1D2B-S-ISO-MV-g12-g13-Diff} does not have a solution for $ R_{\text{Ad}} \geq \frac{2}{1 + \cos \theta^{\star}} $ since $ x < 1 $ and $ y < $ 1. This in turn implies the set of equations \eqref{eq:3R-1D2B-S-ISO-MV-g12-g13-Set} does not have a solution, since solutions to \eqref{eq:3R-1D2B-S-ISO-MV-g12-g13-Set} are immediate solutions to \eqref{eq:3R-1D2B-S-ISO-MV-g12-g13-Diff}. \end{enumerate} We have obtained two lower bounds on $ R_{\text{Ad}} $ for the different cases. Notice that $ \frac{2}{1 + \cos \theta^{\star}} \geq \frac{2}{1 - \cos \theta^{\star}} $ for $ \cos \theta^{\star} \leq 0 $. Hence the choice of $ R_{\text{Ad}} \geq \frac{2}{1 + \cos \theta^{\star}} $ will yield no feasible combinations $ \BR{x, \, y} $ satisfying the set of equations \eqref{eq:3R-1D2B-S-ISO-MV-g12-g13-Set}. This completes the proof. \end{proof} Similar to acute isosceles triangles, provided $ \ell $ is given, we can first tune the gains $ K_{\text{d}} $ and $ K_{\text{b}} $ such that $ \ell \leq \widehat{d} $ is satisfied. Then any choice of $ K_{\text{A}} > 0 $ would yield no solutions $ \BR{x, \, y} $ to the set of equations \eqref{eq:3R-1D2B-S-ISO-MV-g12-g13-Set}. We need Lemma \ref{lem:3R-1D2B-S-ISO-MV-Main-Right-Obtuse} when tuning the gains $ K_{\text{d}} $ and $ K_{\text{b}} $ only is not enough. In that case, for a specific value $ K_{\text{d}} > 0 $, we know from the lemma that the gain for the signed area control term needs to satisfy $ K_{\text{A}} \geq \frac{2}{1 + \cos \theta^{\star}} K_{\text{d}} $. When $ \cos \theta^{\star} \to -1 $, i.e., when the vertex angle $ \theta^{\star} $ of the isosceles triangle is close to $ 180^{\degree} $, we obtain that $ K_{\text{A}} \to \infty $. Combining the analyses on the equilibrium and moving configurations, we have the following result for the three-robot formation tasked with displaying a right or obtuse isosceles triangle with legs $ \ell > 0 $: \begin{theorem} \label{thm:3R-1D2B-S-Global-Convergence-Right-Obtuse} Consider a team of three robots moving according to \eqref{eq:3R-1D2B-S-p-Dynamics} with gains $ K_{\text{d}} > 0 $, $ K_{\text{b}} > 0 $, and $ K_{\text{A}} > 0 $. Define the gain ratios $ R_{\text{bd}} = \frac{K_{\text{b}}}{K_{\text{d}}} $ and $ R_{\text{Ad}} = \frac{K_{\text{A}}}{K_{\text{d}}} $, and also $ \widehat{d} = \sqrt{3} \sqrt[3]{\frac{R_{\text{bd}}}{2}} $. Furthermore, let the desired formation shape be an isosceles triangle with legs $ \ell > 0 $ and vertex angle $ \theta^{\star} \in \left[90^{\degree}, \, 180^{\degree}\right) $. Finally, parametrize the distances $ d_{12} $ and $ d_{13} $ as in \eqref{eq:3R-1D2B-S-ISO-EQ-PAR-XY}. Then, starting from all feasible initial configurations, the robots converge to a desired equilibrium configuration $ p_{\text{eq}} \in \mathcal{S}_{p} $ if $ \BR{K_{\text{d}}, \, K_{\text{b}}} $ is chosen such that $ \ell \leq \widehat{d} $ or if $ \BR{K_{\text{d}}, \, K_{\text{b}}, \, K_{\text{A}}} $ is chosen such that $ \ell > \widehat{d} $ and $ R_{\text{Ad}} \geq \frac{2}{1 + \cos \theta^{\star}} $. \end{theorem} \begin{proof} The proof follows directly from the results obtained in Lemmas \ref{lem:3R-1D2B-S-ISO-EQ-Main-Right-Obtuse} and \ref{lem:3R-1D2B-S-ISO-MV-Main-Right-Obtuse}. This completes the proof. \end{proof} In Table \ref{tab:3R-1D2B-S-ISO-Summary-Results}, we summarize the results on the gain ratio $ R_{\text{Ad}} $ such that convergence to the desired isosceles triangular formation is obtained. \begin{table*}[!tb] \centering \caption{Conditions on the gain ratio $ R_{\text{Ad}} = \frac{K_{\text{A}}}{K_{\text{d}}} $ in Theorems \ref{thm:3R-1D2B-S-Global-Convergence-Acute} and \ref{thm:3R-1D2B-S-Global-Convergence-Right-Obtuse} and Corollary \ref{cor:3R-1D2B-S-Global-Convergence-Acute-V2} for yielding convergence to the desired isosceles triangular formation.} \label{tab:3R-1D2B-S-ISO-Summary-Results} \begin{tabularx}{0.975\linewidth}{llXl} \toprule & Acute isosceles triangle & Acute isosceles triangle (with numerics) & Right \& obtuse isosceles triangle \\ \midrule \addlinespace $ \ell \leq \widehat{d} $ & $ R_{\text{Ad}} \in \left(0, \, \frac{6}{1 + \cos \theta^{\star}} \right] $ & $ R_{\text{Ad}} \in \BR{0, \infty} $ & $ R_{\text{Ad}} \in \BR{0, \infty} $ \\ \addlinespace $ \ell > \widehat{d} $ & $ R_{\text{Ad}} = \frac{6}{1 + \cos \theta^{\star}} $ for $ \theta^{\star} \in \left[60^{\degree}, \, 90^{\degree} \right) $ & $ R_{\text{Ad}} \in \left[ \max \CBR{\frac{6}{1 + \cos \theta^{\star}}, \frac{2}{1 - \cos \theta^{\star}}}, \, \infty \right) $ & $ R_{\text{Ad}} \in \left[ \frac{2}{1 + \cos \theta^{\star}}, \, \infty \right) $ \\ \bottomrule \end{tabularx} \end{table*} \section{Numerical Example} \label{sec:Numerical-Example} \subsection{Numerical evaluation of \eqref{eq:3R-1D2B-S-ISO-EQ-g12-g13-Diff-Back}} Earlier, during the analysis of acute isosceles triangles in Section \ref{sec:Isosceles-Triangle-Analysis-Acute}, we have found that the difference equation \eqref{eq:3R-1D2B-S-ISO-EQ-g12-g13-Diff} contains solutions satisfying Proposition \ref{prop:3R-1D2B-S-ISO-EQ-Conditions-II} for $ \mathbb{d} > 3 $. Substituting these solutions back to the set of equation \eqref{eq:3R-1D2B-S-ISO-EQ-g12-g13-Set} yields the cubic equation \eqref{eq:3R-1D2B-S-ISO-EQ-g12-g13-Diff-Back} for which we could not determine its sign since positive and negative coefficients are present. Hence we approach this in a numerical manner. We first choose a value for $ \mathbb{d} $ satisfying $ \mathbb{d} > 3 $ ($ \mathbb{d} = \frac{1}{2} R_{\text{Ad}} \cos \theta^{\star} $). In the current simulation, we let $ \mathbb{d} \in \begin{bmatrix} 3.1 & 4 & 6 & 11 & 16 & 26 & 51 & 101 & 501 & 1001 \end{bmatrix} $. Next, we let $ x $ be in the range $ x \in \BR{1, \, 30} $ and compute the corresponding value for $ y $ which solves \eqref{eq:3R-1D2B-S-ISO-EQ-g12-g13-Diff}. By applying the constraints found in Proposition \ref{prop:3R-1D2B-S-ISO-EQ-Conditions-II}, we obtain the feasible combinations $ \BR{x_{\text{f}}, \, y_{\text{f}}} $ for the corresponding value of $ \mathbb{d} $. Finally, these combinations $ \BR{x_{\text{f}}, \, y_{\text{f}}} $ are fed back in \eqref{eq:3R-1D2B-S-ISO-EQ-g12-g13-Set}. We compute the value on the LHS and on the RHS and take the difference between them. In Fig. \ref{fig:3R-1D2B-S-ISO-EQ-NUM-theta-ALL}, we have plotted the results for $ \theta^{\star} \in \begin{bmatrix} 5^{\degree} & 15^{\degree} & 45^{\degree} & 75^{\degree} \end{bmatrix} $. \begin{figure*}[!tb] \centering { \subfigure[$ \theta^{\star} = 5^{\degree} $ ] { \includegraphics[width=0.475\textwidth]{./Figures/Numerical_EQtheta_005.pdf} \label{fig:3R-1D2B-S-ISO-EQ-NUM-theta-005} } \hfill \subfigure[$ \theta^{\star} = 15^{\degree} $ ] {\includegraphics[width=0.475\textwidth]{./Figures/Numerical_EQtheta_015.pdf} \label{fig:3R-1D2B-S-ISO-EQ-NUM-theta-015} } \hfill \subfigure[$ \theta^{\star} = 45^{\degree} $ ] { \includegraphics[width=0.475\textwidth]{./Figures/Numerical_EQtheta_045.pdf} \label{fig:3R-1D2B-S-ISO-EQ-NUM-theta-045} } \hfill \subfigure[$ \theta^{\star} = 75^{\degree} $ ] {\includegraphics[width=0.475\textwidth]{./Figures/Numerical_EQtheta_075.pdf} \label{fig:3R-1D2B-S-ISO-EQ-NUM-theta-075} } } \caption{Numerical results when evaluating \eqref{eq:3R-1D2B-S-ISO-EQ-g12-g13-Diff-Back} for different values of the vertex angle $ \theta^{\star} $ and gain $ \mathbb{d} $} \label{fig:3R-1D2B-S-ISO-EQ-NUM-theta-ALL} \end{figure*} From Fig. \ref{fig:3R-1D2B-S-ISO-EQ-NUM-theta-ALL}, we observe that the difference between the LHS and the RHS of \eqref{eq:3R-1D2B-S-ISO-EQ-g12-g13-Set} is positive for the different combinations of $ \mathbb{d} $ and vertex angle $ \theta^{\star} $. This difference increases for increasing value of $ x $ and also its minimum value increases for increasing value of $ \theta^{\star} $. For smaller values of $ \mathbb{d} $, we have a smaller set of $ x $-values in the chosen range which satisfy the constraints in Proposition \ref{prop:3R-1D2B-S-ISO-EQ-Conditions-II}. From the results of this numerical evaluation, we can conclude that solutions $ \BR{x_{\text{f}}, y_{\text{f}}} $ to the difference equation \eqref{eq:3R-1D2B-S-ISO-EQ-g12-g13-Diff} do not satisfy the set of equations \eqref{eq:3R-1D2B-S-ISO-EQ-g12-g13-Set}. This also means that the solution set to \eqref{eq:3R-1D2B-S-ISO-EQ-g12-g13-Set} is empty when considering $ x \neq 1 $, $ y \neq 1 $, $ xy \neq 1 $, and $ x \neq q $. The upper bound for $ R_{\text{Ad}} $ in Lemma \ref{lem:3R-1D2B-S-ISO-EQ-Main-Acute} can be extended to $ \infty $, i.e, we do not need to constrain the gain ration $ R_{\text{Ad}} $. Given this, we can extend the results for Theorem \ref{thm:3R-1D2B-S-Global-Convergence-Acute} as follows: \begin{corollary} \label{cor:3R-1D2B-S-Global-Convergence-Acute-V2} Consider a team of three robots moving according to \eqref{eq:3R-1D2B-S-p-Dynamics} with $ K_{\text{d}} > 0 $, $ K_{\text{b}} > 0 $, and $ K_{\text{A}} > 0 $. Define the gain ratios $ R_{\text{bd}} = \frac{K_{\text{b}}}{K_{\text{d}}} $ and $ R_{\text{Ad}} = \frac{K_{\text{A}}}{K_{\text{d}}} $, and also $ \widehat{d} = \sqrt{3} \sqrt[3]{\frac{R_{\text{bd}}}{2}} $. Furthermore, let the desired formation shape be an acute isosceles triangle with legs $ \ell > 0 $ and vertex angle $ \theta^{\star} \in \BR{0^{\degree}, \, 90^{\degree}} $. Finally, parametrize the distances $ d_{12} $ and $ d_{13} $ as in \eqref{eq:3R-1D2B-S-ISO-EQ-PAR-XY}. Then, starting from all feasible initial configurations, the robots converge to a desired equilibrium configuration $ p_{\text{eq}} \in \mathcal{S}_{p} $ in which all the individual tasks are attained if either $ \BR{K_{\text{d}}, \, K_{\text{b}}} $ is chosen such that $ \ell \leq \widehat{d} $ or if $ \BR{K_{\text{d}}, \, K_{\text{b}}, \, K_{\text{A}}} $ is chosen such that $ \ell > \widehat{d} $ and $ R_{\text{Ad}} \geq \max \CBR{\frac{6}{1 + \cos \theta^{\star}}, \, \frac{2}{1 - \cos \theta^{\star}}} $. \end{corollary} \subsection{Simulation setup for different isosceles triangular formations} For illustrating the theoretical claims, we consider simulations of isosceles triangles with different values for the legs $ \ell $ and the vertex angle $ \theta^{\star} $. The gains are taken as $ K_{\text{d}} = 3 $ and $ K_{\text{b}} = 48 $ yielding the threshold distance $ \widehat{d} = 2\sqrt{3} \approx 3.4641 $. We let the legs $ \ell $ and vertex angle $ \theta^{\star} $ of the isosceles triangle take values \begin{equation} \label{eq:3R-1D2B-S-SIM-ISO-Para} \begin{aligned} \ell & \in \begin{bmatrix} 3 & 6 & 10 \end{bmatrix} , \\ \theta^{\star} & \in \begin{bmatrix} 5^{\degree} & 10^{\degree} & 30^{\degree} & 60^{\degree} & 90^{\degree} & 120^{\degree} & 150^{\degree} \end{bmatrix} \end{aligned} \end{equation} while the gain ratio $ R_{\text{Ad}} $ can be chosen from \begin{equation} \label{eq:3R-1D2B-S-SIM-RAd-Para} \begin{aligned} R_{\text{Ad}} & \in \left[ 0.05 \quad 0.1 \quad 0.3 \quad 0.5 \quad 0.7 \quad 0.9 \right. \\ & \quad \left. \quad 1 \quad 3 \quad 6 \quad 10 \quad 20 \quad 50 \right. \\ & \quad \left. \quad \frac{2}{1 - \cos \theta^{\star}} \quad \frac{2}{1 + \cos \theta^{\star}} \quad \frac{6}{1 + \cos \theta^{\star}} \right] . \end{aligned} \end{equation} The initial positions of the robots are in the square $ \left[-100, \, 100 \right]^{2} $ and we consider simulations from $ 5000 $ starting positions for the team of robots. \subsection{Simulation results for different isosceles triangular formations} Here we present the results from the numerical set up. For the isosceles triangle with legs $ \ell = 3 < \widehat{d} $, we obtain that starting from all the considered initial positions, the robots converge to a desired equilibrium configuration in $ \mathcal{S}_{p} $. For isosceles triangles with legs $ \ell = 6 $ and $ \ell = 10 $, we observe that for small values of $ R_{\text{Ad}} $ less than $ 1 $, we have convergence to moving configurations. For $ \ell = 6 $, this is $ R_{\text{Ad}} \leq 0.5 $ while for $ \ell = 10 $, we have $ R_{\text{Ad}} \leq 0.7 $. To be safe, we can infer from the current results that starting from $ R_{\text{Ad}} = 1 $, we only have convergence to a desired equilibrium. This value is smaller than the lower bound that we have obtained in Lemmas \ref{lem:3R-1D2B-S-ISO-MV-Main-Acute} and \ref{lem:3R-1D2B-S-ISO-MV-Main-Right-Obtuse}. To better illustrate the convergence observation, we plot the results of two simulations in Fig. \ref{fig:3R-1D2B-S-ISO-Conv}. The desired shape is an equilateral triangle with legs $ \ell = 10 $. We start from the same initial position. In order to show the simulation results clearly, we plot them side-by-side by shifting the trajectories horizontally. For $ R_{\text{Ad}} = 0.5 $, we observe that the robots converge to a moving configuration while choosing $ R_{\text{Ad}} = 1 $ results in convergence to the desired formation shape. In order to observe whether for larger values of $ \ell $ we also have this result, we consider taking $ \theta^{\star} = 60^{\degree} $; this corresponds to an equilateral triangle. Now, we let $ \ell $ and $ R_{\text{Ad}} $ take values \begin{equation} \label{eq:3R-1D2B-S-SIM-ISO-Para-V2} \begin{aligned} \ell & \in \left[ 3 \quad 4 \quad 6 \quad 8 \quad 10 \quad 15 \quad 20 \quad 25 \quad 50 \quad 75 \quad 100 \right] , \\ R_{\text{Ad}} & \in \begin{bmatrix} 0.25 & 0.5 & 0.75 & 1 & 2 & 4 \end{bmatrix} . \end{aligned} \end{equation} We observe that convergence to moving configurations occur when $ R_{\text{Ad}} \leq 0.75 $ while starting from $ R_{\text{Ad}} = 1 $, all initial configurations evolve to a desired configuration in the set $ \mathcal{S}_{p} $. From Lemma \ref{lem:3R-1D2B-S-ISO-MV-Main-Acute}, we have that the theoretical lower bound is $ R_{\text{Ad}} = 4 $ while numerically $ R_{\text{Ad}} = 1 $ suffices. From these numerical results, we can say that the bounds for $ R_{\text{Ad}} $ obtained during the theoretical analyses are conservative and that a value $ R_{\text{Ad}} \geq 1 $ suffices to prevent the occurrence of moving configurations for isosceles triangles. \begin{figure*}[!tb] \centering { \subfigure[Isosceles Triangle] { \includegraphics[width=0.475\textwidth]{./Figures/Numerical_1D2B_S_ISO_CONV.pdf} \label{fig:3R-1D2B-S-ISO-Conv} } \hfill \subfigure[General Triangle] {\includegraphics[width=0.475\textwidth]{./Figures/Numerical_1D2B_S_GEN_CONV} \label{fig:3R-1D2B-S-GEN-Conv} } } \caption{Robot trajectories for the (\textbf{1D2B}) setup; \textbf{Left}: Desired shape is an equilateral triangle with leg $ \ell = 10 $. For $ R_{\text{Ad}} = 0.5 $, the trajectories converge to an incorrect moving configuration while for $ R_{\text{Ad}} = 1 $, the trajectories converge to the desired equilateral triangle. \textbf{Right}: Desired shape is a general triangle with $ d_{12}^{\star} = 10 $, $ d_{13}^{\star} = 15 $, and $ \theta_{213} = 60^{\degree} $. The incorrect moving configuration occurs when $ R_{\text{Ad}} = 0.2 $ while convergence to the desired shape is obtained when $ R_{\text{Ad}} = 1 $. } \label{fig:3R-1D2B-S-ISO-GEN-CONV} \end{figure*} \subsection{Extension to general triangles} So far, we have obtained results for the analysis of the (\textbf{1D2B}) setup with a signed area constraint when the desired formation shape is an isosceles triangle. To demonstrate that the proposed closed-loop formation system \eqref{eq:3R-1D2B-S-p-Dynamics} may also work for general triangles, we have carried out some simulations. In Fig. \ref{fig:3R-1D2B-S-GEN-Conv}, we plot the result of two simulations. The desired formation shape is a general triangle with lengths $ d_{12}^{\star} = 10 $ and $ d_{13}^{\star} = 15 $ and angle $ \theta_{213} = 60^{\degree} $. The moving configuration is obtained when $ R_{\text{Ad}} = 0.2 $ while we observe convergence to the desired shape when $ R_{\text{Ad}} = 1 $. This illustrates that by a proper tuning of the gains, we could also have convergence results to $ \mathcal{S}_{p} $ for general triangles. Furthermore, we notice that when one of the desired lengths is less than $ \widehat{d} $, we always have convergence to the desired formation shape. This is in accordance with our earlier work \cite{Chan2020}. \section{Conclusions \& Future Work} \label{sec:Conclusions} In this paper, we provided a comprehensive analysis for the formation shape control problem involving a team of three robots partitioned into one distance and two bearing robots. We let the distance robot also maintained a signed area constraint next to the existing distance constraints considered in our previous work \cite{Chan2020}, and studied the effect of this new constraint for the class of isosceles triangles. We showed theoretically and using numerical simulations that the existing equilibrium configurations were maintained and no other undesired equilibrium configurations were introduced by the addition of the signed area control term. Moreover, we derived sufficient conditions on the gain ratio $ R_{\text{Ad}} $ for preventing moving configurations to occur when the leg $ \ell $ of the triangle is larger than a threshold distance $ \widehat{d} $. As a result, convergence results to the desired set $ \mathcal{S}_{p} $ were established for arbitrary isosceles triangular formations. Numerical results indicated that a lower bound of $ R_{\text{Ad}} = 1 $ suffices for preventing convergence to moving configurations while the theoretical analyses resulted in a more restrictive value that depends on the vertex angle $ \theta^{\star} $. Furthermore, simulations showed that the proposed strategy could also work for general triangles. The formal analysis of general triangles is the subject of future work. \bibliographystyle{abbrv}
{'timestamp': '2021-01-05T02:18:33', 'yymm': '2101', 'arxiv_id': '2101.00474', 'language': 'en', 'url': 'https://arxiv.org/abs/2101.00474'}
arxiv
\section{Improving Vision (V) in Vision Language (VL)} \label{sec:vision_pretrain} Deep learning-based VL models typically consist of two modules: an image understanding module $\mathbf{Vision}$ and a cross-modal understanding module $\mathbf{VL}$: \begin{equation}\label{eq:vlm} (\qv, \boldsymbol{v}) = \mathbf{Vision}(Img), \quad y = \mathbf{VL}(\boldsymbol{w}, \qv, \boldsymbol{v}), \end{equation} where $Img$ and $\boldsymbol{w}$ are the inputs of the vision and language modalities, respectively. The output of the $\mathbf{Vision}$ module consists of $\qv$ and $\boldsymbol{v}$. $\qv$ is the semantic representation of the image, such as tags or detected objects, and $\boldsymbol{v}$ the distributional representation of the image in a high-dimensional latent space represented using e.g., the box or region\footnote{We use the terms region and box interchangeably.} features produced by a VG-pre-trained Faster-RCNN model~\cite{anderson2018bottom}. Most $\mathbf{VL}$ models use only the visual features $\boldsymbol{v}$, while the recently proposed \textsc{Oscar}~\cite{li2020oscar} model shows that $\qv$ can serve as anchors for learning better vision-language joint representations and and thus can improve the performance on various VL tasks. $\boldsymbol{w}$ and $y$ of the $\mathbf{VL}$ module of Equation~\eqref{eq:vlm} vary among different VL tasks. In VQA, $\boldsymbol{w}$ is a question and $y$ is an answer to be predicted. In text-image retrieval, $\boldsymbol{w}$ is a sentence and $y$ is the matching score of a sentence-image pair. In image captioning, $\boldsymbol{w}$ is not given and $y$ is a caption to be generated. Inspired by the great success of pre-trained language models to various natural language processing tasks, vision-language pre-training (VLP) has achieved remarkable success in improving the performance of the cross-modal understanding module $\mathbf{VL}$ by (1) unifying vision and language modeling $\mathbf{VL}$ with Transformer and (2) pre-training the unified $\mathbf{VL}$ with large-scale text-image corpora. However, most recent works on VLP treat the image understanding module $\mathbf{Vision}$ as a black box and leave the visual feature improvement untouched since the development of the classical OD model~\cite{anderson2018bottom} three years ago, despite that there has been much research progress on improving object detection by 1) developing much more diverse, richer, and larger training datasets (e.g. OpenImages and Objects 365), 2) gaining new insights in object detection algorithms such as feature pyramid network~\cite{lin2017feature}, one-stage dense prediction~\cite{lin2017focal}, and anchor-free detectors~\cite{tian2020fcos}, and 3) leveraging more powerful GPUs for training bigger models. In this work, we focus on improving $\mathbf{Vision}$ for better visual representations. We developed a new OD model by enriching the visual object and attribute categories, enlarging the model size and training on a much larger OD dasetset, and thus advanced the state of the arts on a wide range of VL tasks. We detail how the new OD model is developed in the rest of this section and then describe the use of \textsc{Oscar+}{} for $\mathbf{VL}$ pre-training in Section~\ref{sec:vl_pretrain}. \section{Introduction} Vision language pre-training (VLP) has proved effective for a wide range of vision-language (VL) tasks ~\cite{lu2019vilbert,tan2019lxmert,chen2019uniter,su2019vl,li2019visualbert,li2019unicoder,zhou2019unified,li2020oscar}. VLP typically consists of two stages: (1) an object detection model is pre-trained to encode an image and the visual objects in the image to feature vectors, and (2) a cross-modal fusion model is pre-trained to blend text and visual features. While existing VLP research focuses mainly on improving the cross-modal fusion model, this paper focuses on improving the object-centric visual representations and presents a comprehensive empirical study to demonstrate that visual features matter in VL models. \begin{table*}[!ht] \begin{center} \resizebox{\linewidth}{!}{ \scriptsize \begin{tabular}{c@{\hspace{3pt}}|c@{\hspace{5pt}}c@{\hspace{3pt}}|c@{\hspace{5pt}}c|c@{\hspace{5pt}}c@{\hspace{5pt}}c@{\hspace{6pt}}c@{\hspace{5pt}}|c@{\hspace{6pt}}c@{\hspace{6pt}}|c@{\hspace{6pt}}c@{\hspace{6pt}}c@{\hspace{6pt}}|c@{\hspace{6pt}}c@{\hspace{6pt}}c@{\hspace{3pt}}|c@{\hspace{6pt}}c} \toprule \multirow{2}{*}{Visual feature} & \multicolumn{2}{c|}{VQA} & \multicolumn{2}{c|}{GQA} & \multicolumn{4}{c|}{Image Captioning} & \multicolumn{2}{c|}{NoCaps} & \multicolumn{3}{c|}{Image Retrieval} & \multicolumn{3}{c|}{Text Retrieval} & \multicolumn{2}{c}{NLVR2} \\ & test-dev & test-std & test-dev & test-std & B@4 & M & C & S & C & S & R@1 & R@5 & R@10 & R@1 & R@5 & R@10 & dev & test-P \\ \midrule Anderson \ea \cite{anderson2018bottom} & $73.16$ & $73.44$ & $61.58$ & $61.62$ & $40.5$ & $29.7$ & $137.6$ & $22.8$ & $86.58$ & $12.38$ & $54.0$ & $80.8$ & $88.5$ & $70.0$ & $91.1$ & $95.5$ & $78.07$ & $78.36$ \\ \rowcolor{Graylight} Ours & $\bf 75.95$ & $\bf 76.12$ & $\bf 65.05$ & $\bf 64.65$ & $\bf 40.9$ & $\bf 30.9$ & $\bf 140.6$ & $\bf 25.1$ & $\bf 92.46$ & $\bf 13.07$ & $\bf 58.1$ & $\bf 83.2$ & $\bf 90.1$ & $\bf 74.6$ & $\bf 92.6$ & $\bf 96.3$ & $\bf 82.05$ & $\bf 83.08$ \\ \hline $\Delta$ & $\bf 2.79\uparrow$ & $\bf 2.68\uparrow$ & $\bf 3.47\uparrow$ & $\bf 3.03\uparrow$ & $\bf 0.4\uparrow$ & $\bf 1.2\uparrow$ & $\bf 3.0\uparrow$ & $\bf 2.3\uparrow$ & $\bf 5.9\uparrow$ & $\bf 0.7\uparrow$ & $\bf 4.1\uparrow$ & $\bf 2.4\uparrow$ & $\bf 1.6\uparrow$ & $\bf 4.6\uparrow$ & $\bf 1.5\uparrow$ & $\bf 0.8\uparrow$ & $\bf 3.98\uparrow$ & $\bf 4.71\uparrow$ \\ \bottomrule \end{tabular} } \end{center} \vspace{-5mm} \caption{ Uniform improvements on seven VL tasks by replacing visual features from Anderson \ea \cite{anderson2018bottom} with ours. The NoCaps baseline is from VIVO~\cite{hu2020vivo}, and our results are obtained by directly replacing the visual features. The baselines for rest tasks are from \textsc{Oscar}~\cite{li2020oscar}, and our results are obtained by replacing the visual features and performing $\textsc{Oscar+}$ pre-training. All models are BERT-Base size. As analyzed in Section~\ref{subsec:oscar_ablation}, the new visual features contributes 95\% of the improvement.} \label{tab:peter_vinvl_comp} \end{table*} \begin{figure*}[t!] \includegraphics[width=0.5\textwidth]{vinvl_figs/OI_X152FPN.PNG} \includegraphics[width=0.5\textwidth]{vinvl_figs/VinVL_X152C4.PNG} \caption{Predictions from an X152-FPN model trained on OpenImages (Left) and our X152-C4 model trained on four public object detection datasets (Right). Our model contains much richer semantics, such as richer visual concepts and attribute information, and the detected bounding boxes cover nearly all semantically meaningful regions. Compared with those from the common object classes in typical OD models (Left), the rich and diverse region features from our model (Right) are crucial for vision-language tasks. For concepts detected by both models, e.g., ``\texttt{boy}'', attributes from our model offer richer information, e.g., ``\texttt{young barefoot shirtless standing surfing smiling little playing looking blond boy}''. There are object concepts that are detected by our model but not by the OpenImages model, including \texttt{fin}, \texttt{wave}, \texttt{foot}, \texttt{shadow}, \texttt{sky}, \texttt{hair}, \texttt{mountain}, \texttt{water}, \texttt{(bare}, \texttt{tan}, \texttt{light}, \texttt{beige}) \texttt{back}, (\texttt{blue}, \texttt{colorful}, \texttt{floral}, \texttt{multi colored}, \texttt{patterned}) \texttt{trunk}, \texttt{sand}, \texttt{beach}, \texttt{ocean}, (\texttt{yellow}, \texttt{gold}) \texttt{bracelet}, \texttt{logo}, \texttt{hill}, \texttt{head}, (\texttt{black}, \texttt{wet}) \texttt{swim trunks}, \texttt{black}, \texttt{wet swim trunks}. Compared to the R101-C4 model of \cite{anderson2018bottom}, our model produces more accurate object-attribute detection results and better visual features for VL applications; see Appendix~\ref{app:visionqa} for the full pictures and predictions from ~\cite{anderson2018bottom}.} \label{fig:pretrain_finetune} \end{figure*} Among the aforementioned work, a widely-used object detection (OD) model~\cite{anderson2018bottom} is trained on the Visual Genome dataset~\cite{krishna2017visual}. The OD model provides an object-centric representation of images, and has been used in many VL models as a black box. In this work, we pre-train a large-scale object-attribute detection model based on the ResNeXt-152 C4 architecture (short as X152-C4). Compared to the OD model of ~\cite{anderson2018bottom}, the new model is better-designed for VL tasks, and is bigger and trained on much larger amounts of data, combining multiple public object detection datasets, including COCO~\cite{lin2014microsoft}, OpenImages (OI)~\cite{kuznetsova2018open}, Objects365~\cite{shao2019objects365} and Visual Genome (VG)~\cite{krishna2017visual}. As a result, our OD model achieves much better results on a wide range of VL tasks, as shown in Table~\ref{tab:peter_vinvl_comp}. Compared to other typical OD models, such as X152-FPN trained on OpenImages, our new model can encode a more diverse collection of visual objects and concepts (e.g., producing visual representations for $1848$ object categories and $524$ attribute categories), as illustrated by an example in Figure~\ref{fig:pretrain_finetune}. To validate the effectiveness of the new OD model, we pre-train a Transformer-based cross-modal fusion model \textsc{Oscar+}~\cite{li2020oscar} on a public dataset consisting of $8.85$ million text-image pairs, where the visual representations of these images are produced by the new OD model and are fixed during \textsc{Oscar+}{} pre-training. We then fine-tune the pre-trained \textsc{Oscar+}{} for a wide range of downstream tasks, including VL understanding tasks such as VQA~\cite{goyal2017making}, GQA~\cite{hudson2019gqa}, NLVR2~\cite{suhr2018corpus}, and COCO text-image retrieval~\cite{lin2014microsoft}, and VL generation tasks such as COCO image captioning~\cite{lin2014microsoft} and NoCaps~\cite{agrawal2019nocaps}. Our results show that the object-centric representations produced by the new OD model significantly improve the performance across all the VL tasks, often by a large margin over strong baselines using the classical OD model~\cite{anderson2018bottom}, creating new state of the arts on all these tasks, including GQA on which none of the published pre-trained models has surpassed the deliberately designed neural state machine (NSM)~\cite{hudson2019learning}. We will release the new OD model to the research community. The main contributions of this work can be summarized as follows: $(\RN{1})$ We present a comprehensive empirical study to demonstrate that visual features matter in VL models. $(\RN{2})$ We have developed a new object detection model that can produce better visual features of images than the classical OD model~\cite{anderson2018bottom} and substantially uplifts the state-of-the-art results on all major VL tasks across multiple public benchmarks. $(\RN{3})$ We provide a detailed ablation study of our pre-trained object detection model to investigate the relative contribution to the performance improvement due to different design choices regarding diversity of object categories, visual attribute training, training data scale, model size, and model architecture. \subsection{Object Detection Pre-training} \label{subsec:vision_pretrain} To improve the OD model for VL tasks, we utilize four public object detection datasets. As most datasets do not have attribute annotations, we adopt a \emph{pre-training and fine-tuning} strategy to build our OD model. We first pre-train an OD model on a large-scale corpus consisting of four public datasets, and then fine-tune the model with an additional attribute branch on Visual Genome, making it capable of detecting both objects and attributes. \paragraph{Data.} Table~\ref{tab:vision_pretrain_corpus} summarizes the statistics of the four public datasets used in our object detection pre-training, including COCO, OpenImagesV5 (OI), Objects365V1, and Visual Genome (VG). These datasets have complementary characters, and are extremely unbalanced in terms of data size, object vocabulary, and the number of annotations in each class. For example, the VG dataset has a rich and diverse set of annotations for both objects and their attributes with an open vocabulary. But its annotations are noisy and suffer from the missing-annotation problem. The COCO dataset, on the other hand, is very well annotated. But the coverage of visual objects and attributes is much lower than that in VG although we use both its 80 object classes and 91 stuff classes to include as diverse visual concepts as possible. We take the following steps to build a unified corpus by combining the four datasets. \begin{enumerate} \item First of all, to enhance visual concepts of tail classes, we perform class-aware sampling for OpenImages and Objects365 to get at least 2000 instances per class, resulting in 2.2M and 0.8M images, respectively. \item To balance the contribution of each dataset, we merge the four datasets with 8 copies of COCO (8$\times$0.11M), 8 copies of VG (8$\times$0.1M), 2 copies of class-aware sampled Objects365 (2$\times$0.8M) and one copy of the class-aware sampled OpenImages (2.2M). \item To unify their object vocabularies, we use the VG vocabulary and its object aliases as the base vocabulary, merge a class from the other three datasets into a VG class if their class names or aliases match, and add a new class if no match is found. \item Finally, we keep all VG classes that contain at least 30 instances, resulting in 1594 VG classes and 254 classes from the other three datasets that cannot be mapped to the VG vocabulary, resulting in a merged object detection dataset that contains 1848 classes. \end{enumerate} \begin{table}[h] \begin{center} \begin{tabular}{c@{\hspace{3pt}}|c@{\hspace{3pt}}|c|c|c@{\hspace{3pt}}|c} \toprule Source & VG & COCO w/ stuff & Objects365 & OpenImagesV5 & Total \\ \midrule Image & 97k & 111k & 609k & 1.67M & 2.49M \\ classes & 1594 & 171 & 365 & 500 & 1848 \\ Sampling & $\times 8$ & $\times 8$ & CA-2k, $\times 2$ & CA-2k & 5.43M \\ \bottomrule \end{tabular} \end{center} \vspace{-5mm} \caption{Statistics of the Vision pre-training datasets. In sampling, $\times k$ means $k$ copies in one epoch and ``CA-2k'' means class-aware sampling with at least 2000 instances per class.} \label{tab:vision_pretrain_corpus} \vspace{-3mm} \end{table} \paragraph{Model Architecture (FPN vs C4).} Although \cite{lin2017feature} shows that the FPN model outperforms the C4 model for object detection, recent studies ~\cite{jiang2020defense} demonstrate that FPN does not provide more effective region features for VL tasks than C4, which is also confirmed by our experimental results \footnote{We find in our experiments that using the same training process, the X152-C4 model even produces better object detection result than the X152-FPN model. See Appendix~\ref{app:c4vsfpn} for details.}. We thus conduct a set of carefully designed experiments, as to be detailed in Appendix~\ref{app:c4vsfpn}, and find two main reasons for this. The first is that all layers in the C4 model used for region feature extraction are pre-trained using the ImageNet dataset while the multi-layer-perceptron (MLP) head of the FPN model are not. It turns out that the VG dataset is still too small to train a good enough visual features for VL tasks and using ImageNet-pre-trained weights is beneficial. The second is due to the different network architectures (CNN vs. MLP). The convolutional head used in C4 has a better inductive bias for encoding visual information than the MLP head of FPN. Therefore, in this study we use C4 architecture for VLP. \paragraph{Model Pre-Training.} Following the common practice in object detection training, we freeze the first convolution layer, the first residual block, and all the batch-norm layers. We also use several data augmentation methods, including horizontal flipping and multi-scale training. To train a detection model with the X152-C4 architecture, we initialize the model backbone from an ImageNet-5K checkpoint~\cite{wu2019detectron2} and train for 1.8M iterations with a batch size of 16 images. \subsection{Injecting attribute information into the model} Following \cite{anderson2018bottom}, we add an attribute branch to the pre-trained OD model, and then fine-tune the OD model on VG to inject attribute information (524 classes). Since the object representations are pre-trained in the object detection pre-training stage, we can focus the VG fine-tuning on learning attributes by picking a much larger attribute loss weight $1.25$, compared to $0.5$ used in \cite{anderson2018bottom,jiang2020defense}. Thus, our fine-tuned model significantly outperforms previous models \cite{anderson2018bottom,jiang2020defense} in detecting objects and attributes on VG. \subsection{Efficient region feature extractor for VL tasks} With a richer set of visual objects and attributes, the classical class-aware non-maximal suppression (NMS) post-processing takes a significantly larger amount of time to remove overlapped bounding boxes, making the feature extraction process extremely slow. To improve the efficiency, we replace the class-aware NMS with the class-agnostic NMS that only conducts the NMS operation once\footnote{Counting the NMS in the RPN module, there are in total 2 NMS operations in our efficient region feature extractor.}. We also replace the time-consuming conv layers with dilation=2 used in \cite{anderson2018bottom} with conv layers without dilation. These two replacements make the region feature extraction process much faster than that in \cite{anderson2018bottom} without any accuracy drop on VL downstream tasks. We report the end-to-end inference time of VL models with different vision models on a Titan-X GPU and a CPU with a single thread in Table~\ref{tab:model_efficiency_cpu} in Appendix~\ref{appsec:gridfeature}. In summary, the pre-trained OD model serves as the image understanding module, as in Equation~\eqref{eq:vlm}, to produce vision presentations $(\qv, \boldsymbol{v})$ for downstream VL tasks. Here, $\qv$ is the set of detected object names (in text) and $\boldsymbol{v}$ is the set of region features. Each region feature is denoted as $(\hat{v}, z)$, where $\hat{v}$ is a $P$-dimensional representation from the input of the last linear classification layer of the detection head ( \ie $P=2048$) and $z$ is a $R$-dimensional position encoding of the region (\ie $R=6$)\footnote{It includes coordinates of the bounding boxes, and height \& width.}. \section{\textsc{Oscar+}{} Pre-training} \label{sec:vl_pretrain} The success of VLP lies in the use of a unifying model architecture for a wide range of VL tasks and the large-scale pre-training of the unified model using objectives that correlate with the performance metrics of these downstream VL tasks. In this study we pre-train an improved version of \textsc{Oscar}~ \cite{li2020oscar}, known as \textsc{Oscar+}{} models, to learn the joint image-text representations using image tags as anchors for image-text alignment. \subsection{Pre-training corpus} We build our pre-training corpus based on three types of existing vision and VL datasets: (1) image captioning datasets with human-annotated captions as $\boldsymbol{w}$ and machine-generated~\footnote{We use the same model to extract visual features.} image tags as $\qv$, including COCO~\cite{lin2014microsoft}, Conceptual Captions (CC)~\cite{sharma2018conceptual}, SBU captions~\cite{ordonez2011im2text} and flicker30k~\cite{young2014image}; (2) visual QA datasets with questions as $\boldsymbol{w}$ and human-annotated answers as $\qv$, including GQA~\cite{hudson2019gqa}, VQA~\cite{goyal2017making} and VG-QAs; (3) image tagging datasets with machine-generated~\footnote{We use the captioning model released by \textsc{Oscar}~\cite{li2020oscar}.} captions as $\boldsymbol{w}$ and human-annotated tags as $\qv$, including a subset of OpenImages (1.67M images). In total, the corpus contains 5.65 million unique images, 8.85 million text-tag-image triples. The detailed statistics are presented in Table~\ref{tab:pretrain_corpus} in the Appendix. The size of the pre-training corpus could have been significantly increased by combining large-scale image tagging datasets, such as the full set of OpenImages (9M images) and YFCC (92M images). We leave it to future work to leverage much larger corpora for model pre-training. \begin{table*}[!ht] \begin{center} \begin{tabular}{c|cc|c|cc} \toprule Loss & \multicolumn{2}{c|}{$(\boldsymbol{w}, \qv/\qv', \boldsymbol{v})$} & $(\boldsymbol{w}/\boldsymbol{w}', \qv, \boldsymbol{v})$ & \multicolumn{2}{c}{3-way contrastive} \\ $\boldsymbol{w}'/\qv'$ & All $\qv$'s (\textsc{Oscar}) & $\qv$'s from QA & All $\boldsymbol{w}$'s & All (\textsc{Oscar+}{}) & $\qv$'s from QA \\ \hline VQA (vqa-dev) & {\bf 69.8}\small{$\pm$0.08} & \textcolor{blue}{\bf 70.1}\small{$\pm$0.08} & 69.5\small{$\pm$0.05} & {\bf 69.8}\small{$\pm$0.06} & {\bf 69.7}\small{$\pm$0.06} \\ COCO-IR & 73.9\small{$\pm$0.2} & {\bf 75.0}\small{$\pm$0.2} & {\bf 75.0}\small{$\pm$0.7} & \textcolor{blue}{\bf 78.3}\small{$\pm$0.3} & \textcolor{blue}{\bf 77.7}\small{$\pm$0.7}\\ \bottomrule \end{tabular} \caption{Effects of different pre-training contrastive losses on downstream tasks (R50-C4 as $\mathbf{Vision}$ module and 4-layer Transformer as $\mathbf{VL}$ module in \eqref{eq:vlm} ). COCO-IR metric is Image-to-Text retrieval R@1 at COCO 1K test set. \textcolor{blue}{\bf Blue} indicates the best result for a task and {\bf Black} indicates the runner-up. } \label{tab:contrastive} \end{center} \vspace{-3mm} \end{table*} \subsection{Pre-training Objectives} \label{subsec:oscarobjective} There are two terms in the \textsc{Oscar+}{} pre-training loss as in Equation~\eqref{eq_pre_training}. \begin{align} \mathcal{L}_{\text{Pre-training}} = \mathcal{L}_{\text{MTL}} + \mathcal{L}_{\text{CL3}}. \label{eq_pre_training} \end{align} $\mathcal{L}_{\text{MTL}}$ is the {Masked Token Loss} defined on the text modality ($\boldsymbol{w}$ and $\qv$), following closely~\cite{li2020oscar}. (See Appendix~\ref{app:oscarlosses} for details.) $\mathcal{L}_{\text{CL3}}$ is a novel \emph{3-way Contrastive Loss}. Different from the binary contrastive loss used in \textsc{Oscar}~\cite{li2020oscar}, the proposed \emph{3-way Contrastive Loss} to effectively optimize the training objectives used for VQA \cite{yang2016stacked} and text-image matching \cite{fang2015captions}\footnote{\cite{fang2015captions} uses a deep-learning-based text-image matching model to select the best caption candidate for a given image.}. As shown in Equation~\ref{eq_two_views}, $\mathcal{L}_{\text{CL3}}$ takes into account two types of training samples $\boldsymbol{x}$: the \{caption, image-tags, image-features\} triplets of the image captioning and image tagging data, and the \{question, answer, image-features\} triplets of the VQA data. \begin{align} \boldsymbol{x} \triangleq (\underbrace{~\boldsymbol{w}_{~}}_{\text{\textcolor{red!50}{caption}} }, \underbrace{~\qv, \boldsymbol{v}~}_{\text{\textcolor{mygreen}{tags\&image}}}) \quad \text{ or } \quad ( \underbrace{~\boldsymbol{w}, \qv}_{\text{\textcolor{red!50}{Q\&A}}},~ \underbrace{~\boldsymbol{v}_{~_{~}}}_{\text{\textcolor{mygreen}{image}}}) \label{eq_two_views} \end{align} To compute contrastive losses, negative examples need to be constructed. We construct two types of negative (unmatched) triplets for the two types of training samples, respectively. One is the polluted ``captions'' $(\boldsymbol{w}', \qv, \boldsymbol{v})$ and the other the polluted ``answers'' $(\boldsymbol{w}, \qv', \boldsymbol{v})$. To classify whether a caption-tags-image triplet contains a polluted caption is a text-image matching task. To classify whether a question-answer-image triplet contains a polluted answer is an answer selection task for VQA. Since the encoding of $\mathtt{[CLS]}$ can be viewed as a representation of the triplet $(\boldsymbol{w}, \qv, \boldsymbol{v})$, we apply a fully-connected (FC) layer on top of it as a 3-way classifier $f(.)$ to predict whether the triplet is matched ($c=0$), contains a polluted $\boldsymbol{w}$ ($c=1$), or contains a polluted $\qv$ ($c=2$). The 3-way contrastive loss is defined as \begin{align} \mathcal{L}_{\text{CL3}} = -\mathbb{E}_{ (\boldsymbol{w}, \qv, \boldsymbol{v}; c ) \sim \Tilde{\mathcal{D}} } \log p( c | f(\boldsymbol{w}, \qv, \boldsymbol{v}) ), \label{eq_action_prediction} \end{align} where the dataset $(\boldsymbol{w}, \qv, \boldsymbol{v}; c ) \in \Tilde{\mathcal{D}}$ contains 50\% matched triples, 25\% $\boldsymbol{w}$-polluted triples, and 25\% $\qv$-polluted triples. For efficient implementation, the polluted $\boldsymbol{w}'$ is uniformly sampled from all $\boldsymbol{w}$'s (captions and questions) and $\qv'$ is uniformly sampled from all $\qv$'s (tags and answers) in the corpus. As demonstrated in Table~\ref{tab:contrastive}, when only the answer-polluted triplets are used, i.e., $(\boldsymbol{w}, \qv', \boldsymbol{v})$ with $\qv'$ sampled from $\qv$'s from QA corpus, the contrastive loss simulates closely the objective for the VQA task but not the text-image retrieval task. As a result, the pre-trained model can be effectively adapted to VQA, but not so to text-image retrieval. By contrast, the proposed 3-way contrastive loss transfers well to both tasks. \subsection{Pre-trained models} We pre-train two model variants, denoted as \textsc{Oscar+}$_{\text{B}}${} and \textsc{Oscar+}$_{\text{L}}${}, which are initialized with parameters $\boldsymbol{\theta}_{\text{BERT}}$ of BERT base ($L=12, H=768, A=12$) and large ($L=24, H=1024, A=16$), respectively, where $L$ is the number of layers, $H$ the hidden size, and $A$ the number of self-attention heads. To ensure that the image region features have the same input embedding size as BERT, we transform the position-augmented region features using a linear projection via matrix $\Wmat$. The trainable parameters are $\boldsymbol{\theta}=\{\boldsymbol{\theta}_{\text{BERT}}, \Wmat\}$. \textsc{Oscar+}$_{\text{B}}${} is trained for at least $1$M steps, with learning rate $1e^{-4}$ and batch size $1024$. \textsc{Oscar+}$_{\text{L}}${} is trained for at least $1$M steps, with learning rate $3e^{-5}$ and batch size $1024$. The sequence length of language tokens $[\boldsymbol{w}, \qv]$ and region features $\boldsymbol{v}$ are $35$ and $50$, respectively. \section{Adapting to VL Tasks} \label{sec:downstream_tasks} We adapt the pre-trained models to seven downstream VL tasks, including five understanding tasks and two generation tasks. Each task poses different challenges for adaptation. This section briefly introduces the tasks and our fine-tuning strategy. We refer the readers to Appendix~\ref{sec:downstreams} for details. \paragraph{VQA \& GQA} These two are the most widely used understanding task for evaluating VL models in the research community. The tasks require the model to answer natural language questions based on an image. In this study, we perform experiments on the widely-used VQA v2.0 dataset~\cite{goyal2017making} and GQA dataset~\cite{hudson2019gqa}, Following the setting of~\cite{anderson2018bottom}, for each question, the model picks an answer from a shared answer set (i.e., $3,129$ candidates for VQA, $1,852$ candidates for GQA). When adapting a VLP model to the VQA task, we construct the input by concatenating a given question, object tags and object region features, and then feed the $\mathtt{[CLS]}$ output from \textsc{Oscar+}{} to a task-specific linear classifier with a softmax layer for answer prediction. \begin{comment} \paragraph{GQA} Similar to VQA, GQA tests the model's reasoning capability of answering a question based on an image. Unlike VQA, GQA is developed on VG using a robust question engine to elimiate the prevalent real-world priors displayed in VQA datasets that can be exploited by VQA models, e.g., most tomatoes are red and most tables are wooden~\cite{hudson2019gqa}. Thus, GQA is more challenging than VQA such that none of the previous VLP models outperform the deliberately designed neural state machine~\cite{hudson2019gqa}. In this study, we conduct experiments on the public GQA dataset~\cite{hudson2019gqa}. For each question, the model needs to pick an answer from a shared set of $1,852$ candidates. Our fine-tuning procedure follows \cite{li2020oscar,chen2019meta}. We first fine-tune a pre-trained model on the unbalanced ``all-split'' dataset for $5$ epochs, and then continuously fine-tune using the ``balanced-split'' dataset for $2$ epochs. \end{comment} \paragraph{Image Captioning \& NoCaps} The captioning task is to generate a natural language caption for an image. This is the most widely used VL generation task in the research community -- the Image Captioning Leaderboard \footnote{Image Captioning Leaderboard: \url{https://competitions.codalab.org/competitions/3221}} hosts more than 260 models as of December 10, 2020. To enable caption generation, we fine-tune \textsc{Oscar+}{} using the seq2seq objective. Each training sample is converted to a triplet consisting of a caption, a set of image region features, and a set of object tags. We randomly mask out $15\%$ of the caption tokens, and use the encoding of the remaining context (the triplet) to predict the masked tokens. Similar to VLP~\cite{li2020oscar,zhou2019unified}, the self-attention mask is constrained such that a caption token can only attend to the tokens before its position to simulate a uni-directional generation process. All caption tokens have full attentions to image regions and object tags but not the other way around. During inference, we first encode the image regions, object tags, and a special token $\mathtt{[CLS]}$ as input. Then the model starts to generate a caption by feeding in a $\mathtt{[MASK]}$ token and sampling a token from a vocabulary based on the token probability output. Next, the $\mathtt{[MASK]}$ token in the previous input sequence is replaced with the sampled token and a new $\mathtt{[MASK]}$ is appended for the next word prediction. The generation process terminates when the model outputs the $\mathtt{[STOP]}$ token or the generated sentence exceeds a pre-defined max length. We perform image captioning experiments on the COCO image captioning dataset~\cite{lin2014microsoft}. \textbf{N}ovel \textbf{O}bject \textbf{Cap}tioning at \textbf{S}cale~\cite{agrawal2019nocaps} extends the image captioning task to test a model's capability of describing novel objects from the Open Images dataset~\cite{kuznetsova2018open} which are unseen in the training corpus. Following the restriction guideline of NoCaps, we use the predicted Visual Genome and Open Images labels to form the input tag sequences, and directly train \textsc{Oscar+}{} on COCO without the initialization from pre-training. VIVO~\cite{hu2020vivo} proposed a VLP technique by only using image tagging data, and achieved SOTA results on NoCaps by fine-tuning on COCO captions. We reproduced VIVO with only one change, i.e., replacing its original vision model with our new vision model, and improved the VIVO performance significantly (short as VinVL+VIVO), as reported in Table~\ref{tab:nocaps_caption}. \paragraph{Image(-to-Text) Retrieval \& Text(-to-Image) Retrieval} Both tasks require the model to calculate a similarity score between an image and a sentence. Thus, the task is widely used to directly measure the quality of the cross-modal VL representation. Following~\cite{li2020oscar}, we formulate the task as a binary classification problem, where given a matched image-text pair, we randomly select a different image or a different sentence to form an unmatched pair. The representation of $\mathtt{[CLS]}$ is used as the input to a classifier to predict a score indicating how likely the given pair is matched. In testing, the predicted score is used to rank a given image-text pairs of a query. Following~\cite{li2019unicoder}, we report the top-$K$ retrieval results on both the $1$K and $5$K COCO test sets. \paragraph{NLVR2} The dataset is developed for joint reasoning about natural language and images~\cite{suhr2018corpus}. The task is to determine whether a text description is true about a pair of images. For fine-tuning, we first construct two input sequences, each containing the concatenation of the given text description and one of the images, and then two $\mathtt{[CLS]}$ outputs from \textsc{Oscar+}{} are concatenated to form the input to a binary classifier for prediction. \begin{comment} \paragraph{NoCaps} Novel Object Captioning at Scale~\cite{agrawal2019nocaps} extends the image captioning task to test models' capability of describing novel objects from the Open Images dataset~\cite{kuznetsova2018open} which are unseen in the training corpus. Following the restriction guideline of NoCaps, we use the predicted Visual Genome and Open Images labels to form the input tag sequences, and train \textsc{Oscar+}{} on COCO without the initialization from pre-training. \end{comment} \section{Experiments \& Analysis} \label{sec:exps} \subsection{Main Results} \label{subsec:sotas} To account for model parameter efficiency, we group the SoTA models in three categories: $(\RN{1})$ SoTA$_{S}$ indicates the best performance achieved by small models prior to the Transformer-based VLP models. $(\RN{2})$ SoTA$_{B}$ indicates the best performance produced by VLP models of a similar size to BERT base. $(\RN{3})$ SoTA$_{L}$ indicates the best performance yielded by VLP models that have a similar size to BERT large. Table~\ref{tab:overall_result} gives an overview of the results of \textsc{Oscar+}{} with \textsc{VinVL} (short for \textsc{VinVL}) on seven VL tasks, compared to previous SoTAs\footnote{All the (single-model) SoTAs are from the published results. For all the tables in this paper, \textcolor{blue}{\textbf{Blue}} indicates the best result for a task, and gray background indicates results produced by \textsc{VinVL}.}. \textsc{VinVL} outperforms previous SoTA models on all tasks\footnote{The only exception is B@4 on image captioning.}, often by a significantly large margin. The result demonstrates the effectiveness of the region features produced by the new OD model. \begin{table*}[!ht] \begin{center} \resizebox{\linewidth}{!}{ \scriptsize \begin{tabular}{c@{\hspace{3pt}}|c@{\hspace{5pt}}c@{\hspace{3pt}}|c@{\hspace{5pt}}c|c@{\hspace{5pt}}c@{\hspace{5pt}}c@{\hspace{6pt}}c@{\hspace{5pt}}|c@{\hspace{6pt}}c@{\hspace{6pt}}|c@{\hspace{6pt}}c@{\hspace{5pt}}c@{\hspace{6pt}}|c@{\hspace{6pt}}c@{\hspace{6pt}}c@{\hspace{3pt}}|c@{\hspace{6pt}}c} \toprule \multirow{2}{*}{Task} & \multicolumn{2}{c|}{VQA} & \multicolumn{2}{c|}{GQA} & \multicolumn{4}{c|}{Image Captioning} & \multicolumn{2}{c|}{NoCaps} & \multicolumn{3}{c|}{Image Retrieval} & \multicolumn{3}{c|}{Text Retrieval} & \multicolumn{2}{c}{NLVR2} \\ & test-dev & test-std & test-dev & test-std & B@4 & M & C & S & C & S & R@1 & R@5 & R@10 & R@1 & R@5 & R@10 & dev & test-P \\ \midrule SoTA$_{S}$ & $70.55$ & $70.92$ & $-$ & $\bf 63.17$ & $38.9$ & $29.2$ & $129.8$ & $22.4$ & $61.5$ & $9.2$ & $39.2$ & $68.0$ & $81.3$ & $56.6$ & $84.5$ & $92.0$ & $54.10$ & $54.80$ \\ SoTA$_{B}$ & $73.59$ & $73.67$ & $61.58$ & $61.62$ & $40.5$ & $29.7$ & $137.6$ & $22.8$ & $86.58$ & $12.38$ & $54.0$ & $80.8$ & $88.5$ & $70.0$ & $91.1$ & $95.5$ & $78.39$ & $79.30$ \\ SoTA$_{L}$ & $74.75$ & $74.93$ & $-$ & $-$ & \textcolor{blue}{$\bf 41.7$} & $30.6$ & $140.0$ & $24.5$ & $-$ & $-$ & $57.5$ & $82.8$ & $89.8$ & $73.5$ & $92.3$ & $96.0$ & $79.76$ & $81.47$ \\ \hline \rowcolor{Graylight} \textsc{VinVL}$_{\text{B}}${} & $\bf 75.95$ & $\bf 76.12$ & \textcolor{blue}{$\bf 65.05$} & \textcolor{blue}{$\bf 64.65$} & $40.9$ & $\bf 30.9$ & \textcolor{blue}{$\bf 140.6$} & $\bf 25.1$ & $\textcolor{blue}{\bf 92.46}$ & \textcolor{blue}{$\bf 13.07$} & $\bf 58.1$ & $\bf 83.2$ & $\bf 90.1$ & $\bf 74.6$ & $\bf 92.6$ & \textcolor{blue}{$\bf 96.3$} & $\bf 82.05$ & $\bf 83.08$ \\ \rowcolor{Grayheavy} \textsc{VinVL}$_{\text{L}}${} & \textcolor{blue}{$\bf 76.52$} & \textcolor{blue}{$\bf 76.60$} & $-$ & $-$ & $\bf 41.0$ & \textcolor{blue}{$\bf 31.1$} & \textcolor{blue}{$\bf 140.9$} & \textcolor{blue}{$\bf 25.2$} & $-$ & $-$ & \textcolor{blue}{$\bf 58.8$} & \textcolor{blue}{$\bf 83.5$} & \textcolor{blue}{$\bf 90.3$} & \textcolor{blue}{$\bf 75.4$} & \textcolor{blue}{$\bf 92.9$} & $\bf 96.2$ & \textcolor{blue}{$\bf 82.67$} & \textcolor{blue}{$\bf 83.98$} \\ \hline $\Delta$ & $\bf 1.77\uparrow$ & $\bf 1.67\uparrow$ & $\bf 3.47\uparrow$ & $\bf 1.48\uparrow$ & $0.7\downarrow$ & $\bf 0.5\uparrow$ & $\bf 0.9\uparrow$ & $\bf 0.7\uparrow$ & $\bf 5.9\uparrow$ & $\bf 0.7\uparrow$ & $\bf 1.3\uparrow$ & $\bf 0.7\uparrow$ & $\bf 0.5\uparrow$ & $\bf 1.9\uparrow$ & $\bf 0.6\uparrow$ & $\bf 0.3\uparrow$ & $\bf 2.91\uparrow$ & $\bf 2.51\uparrow$ \\ \bottomrule \end{tabular} } \end{center} \vspace{-5mm} \caption{ An overall comparison with SoTAs on seven tasks. $\Delta$ indicates the improvement over SoTA. SoTA with subscript S, B, L indicates performance achieved by small models, and models with the model size similar to BERT base and large, respectively. SoTAs: VQA is from ERNIE-VIL~\cite{yu2020ernie}, GQA is from NSM~\cite{hudson2019learning}, NoCaps is from VIVO~\cite{hu2020vivo}, NLVR2 is from VILLA~\cite{gan2020large}, the rest tasks are from \textsc{Oscar}~\cite{li2020oscar}.} \label{tab:overall_result} \vspace{-3mm} \end{table*} \begin{table*}[ht] \begin{center} \resizebox{\linewidth}{!}{ \scriptsize \begin{tabular}{l@{\hspace{2pt}}|c@{\hspace{1pt}}c@{\hspace{1pt}}c@{\hspace{1pt}}c@{\hspace{1pt}}c@{\hspace{3pt}}c@{\hspace{5pt}}c@{\hspace{5pt}}c@{\hspace{5pt}}c@{\hspace{5pt}}c@{\hspace{5pt}}c@{\hspace{5pt}}c@{\hspace{5pt}}c@{\hspace{3pt}}|c@{\hspace{3pt}}|>{\columncolor[gray]{0.90}}c@{\hspace{6pt}}>{\columncolor[gray]{0.90}}c} \toprule \multirow{2}{*}{Method} & \multicolumn{1}{c}{ViLBERT} & \multicolumn{1}{c}{VL-BERT} & \multicolumn{1}{c}{VisualBERT} & \multicolumn{1}{c}{LXMERT} & \multicolumn{1}{c}{12-in-1} & \multicolumn{2}{c}{\textsc{UNITER}} & \multicolumn{2}{c}{\textsc{Oscar}} & \multicolumn{2}{c}{\textsc{VILLA}} & \multicolumn{2}{c|}{\textsc{ERNIE-ViL}} & InterBERT & \multicolumn{2}{c}{\textsc{Oscar+} w/ \textsc{VinVL}} \\ & Base & Base & Base & Base & Base & Base & Large & Base & Large & Base & Large & Base & Large & \textcolor{blue}{\textbf{Ensemble}*} & Base & Large \\ \midrule Test-dev & $70.63$ & $70.50$ & $70.80$ & $72.42$ & $73.15$ & $72.27$ & $73.24$ & $73.16$ & $73.61$ & $73.59$ & $73.69$ & $72.62$ & $74.75$ & - & $\bf 75.95$ & \textcolor{blue}{$\bf 76.52$} \\ Test-std & $70.92$ & $70.83$ & $71.00$ & $72.54$ & $-$ & $72.46$ & $73.40$ & $73.44$ & $73.82$ & $73.67$ & $74.87$ & $72.85$ & $74.93$ & $76.10$ & $\bf 76.12$ & \textcolor{blue}{$\bf 76.60$} \\ \bottomrule \end{tabular}} \end{center} \vspace{-5mm} \caption{Evaluation results on VQA. \textcolor{blue}{*} denotes the No.1 ensemble model of InterBERT Large on the VQA leaderboard.} \label{tab:vqa_result} \vspace{-3mm} \end{table*} \begin{table}[ht] \begin{center} \scriptsize \begin{tabular}{l|c@{\hspace{5pt}}c@{\hspace{5pt}}c@{\hspace{5pt}}c@{\hspace{5pt}}c|>{\columncolor[gray]{0.90}}c>{\columncolor[gray]{0.90}}c} \toprule Method & LXMERT & MMN~\cite{chen2019meta} & 12-in-1 & \textsc{Oscar}$_\text{B}$ & NSM~\cite{hudson2019learning} & \textsc{Oscar+}$_{\text{B}}${} w/ \textsc{VinVL} \\ \midrule Test-dev & $60.00$ & $-$ & $-$ & $\bf 61.58$ & $-$ & \textcolor{blue}{$\bf 65.05$} \\ Test-std & $60.33$ & $60.83$ & $60.65$ & $61.62$ & $\bf 63.17$ & \textcolor{blue}{$\bf 64.65$} \\ \bottomrule \end{tabular} \end{center} \vspace{-5mm} \caption{Evaluation results on GQA.} \label{tab:gqa_result} \vspace{-3mm} \end{table} \begin{table}[ht] \begin{center} \scriptsize \begin{tabular}{l@{\hspace{3pt}}|c@{\hspace{6pt}}c@{\hspace{6pt}}c@{\hspace{6pt}}c@{\hspace{5pt}}|c@{\hspace{6pt}}c@{\hspace{6pt}}c@{\hspace{6pt}}c} \toprule \multirow{2}{*}{Method} & \multicolumn{4}{c|}{cross-entropy optimization} & \multicolumn{4}{c}{CIDEr optimization}\\ & B@4 & M & C & S & B@4 & M & C & S\\ \midrule BUTD~\cite{anderson2018bottom} & $36.2$ & $27.0$ & $113.5$ & $20.3$ & $36.3$ & $27.7$ & $120.1$ & $21.4$ \\ VLP~\cite{zhou2019unified} & $36.5$ & $28.4$ & $117.7$ & $21.3$ & $39.5$ & $29.3$ & $129.3$ & $23.2$ \\ AoANet~\cite{huang2019attention} & $37.2$ & $28.4$ & $119.8$ & $21.3$ & $38.9$ & $29.2$ & $129.8$ & $22.4$ \\ \textsc{Oscar}$_\text{B}$~\cite{li2020oscar} & $36.5$ & $30.3$ & $123.7$ & $23.1$ & $40.5$ & $29.7$ & $137.6$ & $22.8$ \\ \textsc{Oscar}$_\text{L}$~\cite{li2020oscar} & $37.4$ & \textcolor{blue}{$\bf 30.7$} & $127.8$ & $\bf 23.5$ & \textcolor{blue}{$\bf 41.7$} & {$30.6$} & $140.0$ & $24.5$ \\ \hline \rowcolor{Gray} \textsc{Oscar+}$_{\text{B}}${} w/ \textsc{VinVL} & $\bf 38.2$ & $30.3$ & \textcolor{blue}{$\bf 129.3$} & \textcolor{blue}{$\bf 23.6$} & $40.9$ & $\bf 30.9$ & $\bf 140.4$ & $\bf 25.1$ \\ \rowcolor{Gray} \textsc{Oscar+}$_{\text{L}}${} w/ \textsc{VinVL} & \textcolor{blue}{$\bf 38.5$} & $\bf 30.4$ & \textcolor{blue}{$\bf 130.8$} & $23.4$ & $\bf 41.0$ & \textcolor{blue}{$\bf 31.1$} & \textcolor{blue}{$\bf 140.9$} & \textcolor{blue}{$\bf 25.2$} \\ \bottomrule \end{tabular} \end{center} \vspace{-5mm} \caption{Image captioning evaluation results (single model) on COCO ``Karpathy" test split. (Note: B@4: BLEU@4, M: METEOR, C: CIDEr, S: SPICE.)} \label{tab:mscoco_caption} \vspace{-2mm} \end{table} \begin{table*}[ht] \begin{center} \scriptsize \begin{tabular}{l@{\hspace{3pt}}|c@{\hspace{6pt}}c@{\hspace{6pt}}|c@{\hspace{6pt}}c@{\hspace{6pt}}|c@{\hspace{6pt}}c@{\hspace{6pt}}|c@{\hspace{6pt}}c@{\hspace{6pt}}|c@{\hspace{6pt}}c@{\hspace{6pt}}|c@{\hspace{6pt}}c@{\hspace{6pt}}|c@{\hspace{6pt}}c} \toprule \multirow{2}{*}{Method} & \multicolumn{2}{c|}{BLEU@1} & \multicolumn{2}{c|}{BLEU@2} & \multicolumn{2}{c|}{BLEU@3} & \multicolumn{2}{c|}{BLEU@4} & \multicolumn{2}{c|}{METEOR} & \multicolumn{2}{c|}{ROUGE-L} & \multicolumn{2}{c}{CIDEr-D} \\ & c5 & c40 & c5 & c40 & c5 & c40 & c5 & c40 & c5 & c40 & c5 & c40 & c5 & c40 \\ \midrule BUTD~\cite{anderson2018bottom} & $80.2$ & $95.2$ & $64.1$ & $88.8$ & $49.1$ & $79.4$ & $36.9$ & $68.5$ & $27.6$ & $36.7$ & $57.1$ & $72.4$ & $117.9$ & $120.5$ \\ AoANet~\cite{huang2019attention} & $81.0$ & $95.0$ & $65.8$ & $89.6$ & $51.4$ & $81.3$ & $39.4$ & $71.2$ & $29.1$ & $38.5$ & $58.9$ & $74.5$ & $126.9$ & $129.6$ \\ X-Transformer~\cite{pan2020x} & $81.9$ & $95.7$ & $66.9$ & $90.5$ & $52.4$ & $82.5$ & $40.3$ & $72.4$ & $29.6$ & $39.2$ & $59.5$ & $75.0$ & $131.1$ & $133.5$ \\ \hline \rowcolor{Gray} \textsc{Oscar+}{} w/ \textsc{VinVL} & \textcolor{blue}{$\bf 81.9$} & \textcolor{blue}{$\bf 96.9$} & \textcolor{blue}{$\bf 66.9$} & \textcolor{blue}{$\bf 92.4$} & \textcolor{blue}{$\bf 52.6$} & \textcolor{blue}{$\bf 84.7$} & \textcolor{blue}{$\bf 40.4$} & \textcolor{blue}{$\bf 74.9$} & \textcolor{blue}{$\bf 30.6$} & \textcolor{blue}{$\bf 40.8$} & \textcolor{blue}{$\bf 60.4$} & \textcolor{blue}{$\bf 76.8$} & \textcolor{blue}{$\bf 134.7$} & \textcolor{blue}{$\bf 138.7$} \\ \bottomrule \end{tabular} \end{center} \vspace{-5mm} \caption{Leaderboard of the state-of-the-art image captioning models on the COCO online testing.} \label{tab:coco_leaderboard} \vspace{-2mm} \end{table*} \begin{table}[h!] \begin{center} {\fontsize{7}{8}\selectfont \begin{tabular}{l@{\hspace{3pt}}@{\hspace{3pt}}|c@{\hspace{5pt}}c@{\hspace{1mm}}|c@{\hspace{5pt}}c@{\hspace{1mm}}|c@{\hspace{5pt}}c@{\hspace{1mm}}|c@{\hspace{5pt}}c@{\hspace{1pt}}@{\hspace{2pt}}|c@{\hspace{5pt}}c@{\hspace{1mm}}|c@{\hspace{5pt}}c@{\hspace{1mm}}|c@{\hspace{5pt}}c@{\hspace{1mm}}|c@{\hspace{5pt}}c} \toprule \multirow{2}{*}{Method } & \multicolumn{2}{c|}{in-domain} & \multicolumn{2}{c|}{near-domain} & \multicolumn{2}{c|}{out-of-domain} & \multicolumn{2}{c|}{overall} & \multicolumn{2}{c|}{in-domain} & \multicolumn{2}{c|}{near-domain} & \multicolumn{2}{c|}{out-of-domain} & \multicolumn{2}{c}{overall} \\ & CIDEr & SPICE & CIDEr & SPICE & CIDEr & SPICE & CIDEr & SPICE & CIDEr & SPICE & CIDEr & SPICE & CIDEr & SPICE & CIDEr & SPICE \\ \midrule \multicolumn{9}{c|}{Validation Set} & \multicolumn{8}{c}{Test Set} \\ \hline UpDown$^+$ & $79.3$ & $12.4$ & $73.8$ & $11.4$ & $71.7$ & $9.9$ & $74.3$ & $11.2$ & $76.0$ & $11.8$ & $74.2$ & $11.5$ & $66.7$ & $9.7$ & $73.1$ & $11.2$ \\ \textsc{Oscar}$_\text{B}$* & $83.4$ & $12.0$ & $81.6$ & $12.0$ & $77.6$ & $10.6$ & $81.1$ & $11.7$ & $81.3$ & $11.9$ & $79.6$ & $11.9$ & $73.6$ & $10.6$ & $78.8$ & $11.7$ \\ \textsc{Oscar}$_\text{L}$* & $85.4$ & $11.9$ & $84.0$ & $11.7$ & $80.3$ & $10.0$ & $83.4$ & $11.4$ & $84.8$ & $12.1$ & $82.1$ & $11.5$ & $73.8$ & $9.7$ & $80.9$ & $11.3$ \\ Human~\cite{agrawal2019nocaps} & $84.4$ & \textcolor{blue}{$\bf 14.3$} & $ 85.0$ & \textcolor{blue}{$\bf 14.3$} & \textcolor{blue}{$\bf 95.7$} & \textcolor{blue}{$\bf 14.0$} & $87.1$ & \textcolor{blue}{$\bf 14.2$} & $80.6$ & \textcolor{blue}{$\bf 15.0$} & $84.6$ & \textcolor{blue}{$\bf 14.7$} & \textcolor{blue}{$\bf 91.6$} & \textcolor{blue}{$\bf 14.2$} & $85.3$ & \textcolor{blue}{$\bf 14.6$} \\ VIVO*~\cite{hu2020vivo} & $92.2$ & $12.9$ & $87.8$ & $12.6$ & $\bf 87.5$ & $11.5$ & $88.3$ & $12.4$ & $89.0$ & $12.9$ & $87.8$ & $12.6$ & $\bf 80.1$ & $11.1$ & $\bf 86.6$ & $12.4$ \\ \midrule \rowcolor{Gray} VinVL* & {$\bf 96.8$} & $13.5$ & {$\bf 90.7$} & $13.1$ & $87.4$ & {$11.6$} & {$\bf 90.9$} & $12.8$ & {$\bf 93.8$} & $13.3$ & {$\bf 89.0$} & $12.8$ & $66.1$ & $10.9$ & {$85.5$} & $12.5$ \\ \rowcolor{Gray} VinVL+VIVO & \textcolor{blue}{$\bf 103.7$} & $\bf 13.7$ & \textcolor{blue}{$\bf 95.6$} & $\bf 13.4$ & $83.8$ & $\bf 11.9$ & \textcolor{blue}{$\bf 94.3$} & $\bf 13.1$ & \textcolor{blue}{$\bf 98.0$} & $\bf 13.6$ & \textcolor{blue}{$\bf 95.2$} & $\bf 13.4$ & $78.0$ & $\bf 11.5$ & \textcolor{blue}{$\bf 92.5$} & $\bf 13.1$ \\ \bottomrule \end{tabular} } \end{center} \vspace{-5mm} \caption{NoCaps evaluation results. All the models are trained on COCO without additional image-caption pairs following the restriction of NoCaps. (UpDown$^+$ is UpDown+ELMo+CBS, the models with * is +SCST+CBS, VinVL+VIVO is with SCST only.)} \label{tab:nocaps_caption} \vspace{-3mm} \end{table} \begin{comment} \begin{table}[h!] \begin{center} \scriptsize \begin{tabular}{l@{\hspace{1pt}}@{\hspace{2pt}}|c@{\hspace{5pt}}c@{\hspace{1mm}}|c@{\hspace{5pt}}c@{\hspace{1mm}}|c@{\hspace{5pt}}c@{\hspace{1mm}}|c@{\hspace{5pt}}c} \toprule \multirow{2}{*}{Method } & \multicolumn{2}{c|}{in-domain} & \multicolumn{2}{c|}{near-domain} & \multicolumn{2}{c|}{out-of-domain} & \multicolumn{2}{c}{overall}\\ & CIDEr & SPICE & CIDEr & SPICE & CIDEr & SPICE & CIDEr & SPICE \\ \midrule \multicolumn{9}{c}{Validation Set} \\ \hline UpDown$^+$ & $79.3$ & $12.4$ & $73.8$ & $11.4$ & $71.7$ & $9.9$ & $74.3$ & $11.2$ \\ \textsc{Oscar}$_\text{B}$* & $83.4$ & $12.0$ & $81.6$ & $12.0$ & $77.6$ & $10.6$ & $81.1$ & $11.7$ \\ \textsc{Oscar}$_\text{L}$* & $85.4$ & $11.9$ & $84.0$ & $11.7$ & $80.3$ & $10.0$ & $83.4$ & $11.4$ \\ Human~\cite{agrawal2019nocaps} & $84.4$ & \textcolor{blue}{$\bf 14.3$} & $ 85.0$ & \textcolor{blue}{$\bf 14.3$} & \textcolor{blue}{$\bf 95.7$} & \textcolor{blue}{$\bf 14.0$} & $87.1$ & \textcolor{blue}{$\bf 14.2$} \\ VIVO*~\cite{hu2020vivo} & $92.2$ & $12.9$ & $87.8$ & $12.6$ & $\bf 87.5$ & $11.5$ & $88.3$ & $12.4$ \\ \midrule \rowcolor{Gray} VinVL* & {$\bf 96.8$} & $13.5$ & {$\bf 90.7$} & $13.1$ & $87.4$ & {$11.6$} & {$\bf 90.9$} & $12.8$ \\ \rowcolor{Gray} VinVL+VIVO & \textcolor{blue}{$\bf 103.7$} & $\bf 13.7$ & \textcolor{blue}{$\bf 95.6$} & $\bf 13.4$ & $83.8$ & $\bf 11.9$ & \textcolor{blue}{$\bf 94.3$} & $\bf 13.1$ \\ \midrule \multicolumn{9}{c}{Test Set} \\ \hline \textsc{Oscar}$_\text{B}$* & $81.3$ & $11.9$ & $79.6$ & $11.9$ & $73.6$ & $10.6$ & $78.8$ & $11.7$ \\ \textsc{Oscar}$_\text{L}$* & $84.8$ & $12.1$ & $82.1$ & $11.5$ & $73.8$ & $9.7$ & $80.9$ & $11.3$ \\ Human~\cite{agrawal2019nocaps} & $80.6$ & \textcolor{blue}{$\bf 15.0$} & $84.6$ & \textcolor{blue}{$\bf 14.7$} & \textcolor{blue}{$\bf 91.6$} & \textcolor{blue}{$\bf 14.2$} & $85.3$ & \textcolor{blue}{$\bf 14.6$} \\ VIVO*~\cite{hu2020vivo} & $89.0$ & $12.9$ & $87.8$ & $12.6$ & $\bf 80.1$ & $11.1$ & $\bf 86.6$ & $12.4$ \\ \midrule \rowcolor{Gray} VinVL* & {$\bf 93.8$} & $13.3$ & {$\bf 89.0$} & $12.8$ & $66.1$ & $10.9$ & {$85.5$} & $12.5$ \\ \rowcolor{Gray} VinVL+VIVO & \textcolor{blue}{$\bf 98.0$} & $\bf 13.6$ & \textcolor{blue}{$\bf 95.2$} & $\bf 13.4$ & $78.0$ & $\bf 11.5$ & \textcolor{blue}{$\bf 92.5$} & $\bf 13.1$ \\ \bottomrule \end{tabular} \end{center} \vspace{-5mm} \caption{NoCaps evaluation. All the models are trained on COCO without additional image-caption pairs following the restriction of NoCaps. (UpDown$^+$ is UpDown+ELMo+CBS, the models with * is +SCST+CBS, VinVL+VIVO is with SCST only.)} \label{tab:nocaps_caption} \vspace{-3mm} \end{table} \end{comment} \begin{table}[t!] \begin{center} \scriptsize \begin{tabular}{@{\hspace{1mm}}l@{\hspace{1mm}}c@{\hspace{2mm}}c@{\hspace{2mm}}c@{\hspace{2mm}}c@{\hspace{2mm}}|c@{\hspace{2mm}}c@{\hspace{2mm}}c@{\hspace{1mm}}@{\hspace{2mm}}|c@{\hspace{2mm}}c@{\hspace{2mm}}c@{\hspace{2mm}}|c@{\hspace{2mm}}c@{\hspace{2mm}}c@{\hspace{1mm}}} \toprule \multirow{3}{*}{Method $\downarrow$} & \multirow{3}{*}{\texttt{BERT}} & \multicolumn{6}{c}{1K Test Set} & \multicolumn{6}{c}{5K Test Set} \\ \cline{3-14} & & \multicolumn{3}{c|}{Text Retrieval} & \multicolumn{3}{c|}{Image Retrieval} & \multicolumn{3}{c|}{Text Retrieval} & \multicolumn{3}{c}{Image Retrieval} \\ & & R@1 & R@5 & R@10 & R@1 & R@5 & R@10 & R@1 & R@5 & R@10 & R@1 & R@5 & R@10 \\ \midrule Unicoder-VL~\cite{li2019unicoder} & \texttt{B} & $84.3$ & $97.3$ & $99.3$ & $69.7$ & $93.5$ & $97.2$ & $62.3$ & $87.1$ & $92.8$ & $46.7$ & $76.0$ & $85.3$ \\ \multirow{2}{*}{\textsc{UNITER}~\cite{chen2019uniter}} & \texttt{B} & $-$ & $-$ & $-$ & $-$ & $-$ & $-$ & $63.3$ & $87.0$ & $93.1$ & $48.4$ & $76.7$ & $85.9$ \\ & \texttt{L} & $-$ & $-$ & $-$ & $-$ & $-$ & $-$ & $66.6$ & $89.4$ & $94.3$ & $51.7$ & $78.4$ & $86.9$ \\ \multirow{2}{*}{\textsc{Oscar}} & \texttt{B} & $88.4$ & $99.1$ & $99.8$ & $75.7$ & $95.2$ & $98.3$ & $70.0$ & $91.1$ & $95.5$ & $54.0$ & $80.8$ & $88.5$ \\ & \texttt{L} & $89.8$ & {$\bf 98.8$} & $\bf 99.7$ & $\bf 78.2$ & $\bf 95.8$ & $\bf 98.3$ & $73.5$ & $92.2$ & $96.0$ & $57.5$ & $82.8$ & $89.8$ \\ \hline \multirow{2}{*}{\textsc{Oscar+}{} w/ \textsc{VinVL}} & \texttt{B} & $\bf 89.8$ & {$\bf 98.8$} & $\bf 99.7$ & $\bf 78.2$ & $95.6$ & $98.0$ & $\bf 74.6$ & {$\bf 92.6$} & \textcolor{blue}{$\bf 96.3$} & $\bf 58.1$ & $\bf 83.2$ & $\bf 90.1$ \\ & \texttt{L} & \textcolor{blue}{$\bf 90.8$} & \textcolor{blue}{$\bf 99.0$} & \textcolor{blue}{$\bf 99.8$} & \textcolor{blue}{$\bf 78.8$} & \textcolor{blue}{$\bf 96.1$} & \textcolor{blue}{$\bf 98.5$} & \textcolor{blue}{$\bf 75.4$} & \textcolor{blue}{$\bf 92.9$} & $\bf 96.2$ & \textcolor{blue}{$\bf 58.8$} & \textcolor{blue}{$\bf 83.5$} & \textcolor{blue}{$\bf 90.3$} \\ \bottomrule \end{tabular} \end{center} \vspace{-5mm} \caption{Text and Image retrieval evaluation on the COCO $1$K and $5$K test sets. (\texttt{B} for Base, \texttt{L} for Large)} \label{tab:mscoco_retrieval} \end{table} \begin{table*}[ht!] \begin{center} \scriptsize \begin{tabular}{l|cccccccccc|>{\columncolor[gray]{0.90}}c>{\columncolor[gray]{0.90}}c} \toprule \multirow{2}{*}{Method} & \multicolumn{1}{c}{MAC} & \multicolumn{1}{c}{VisualBERT} & \multicolumn{1}{c}{LXMERT} & \multicolumn{1}{c}{12-in-1} & \multicolumn{2}{c}{\textsc{UNITER}} & \multicolumn{2}{c}{\textsc{Oscar}} & \multicolumn{2}{c|}{\textsc{VILLA}} & \multicolumn{2}{c}{\textsc{Oscar+} w/ \textsc{VinVL}}\\ & & base & base & base & base & large & base & large & base & large & base & large \\\midrule Dev & $50.8$ & $67.40$ & $74.90$ & $-$ & $77.14$ & $78.40$ & $78.07$ & $79.12$ & $78.39$ & $79.76$ & $\bf 82.05$ & \textcolor{blue}{$\bf 82.67$} \\ Test-P & $51.4$ & $67.00$ & $74.50$ & $78.87$ & $77.87$ & $79.50$ & $78.36$ & $80.37$ & $79.47$ & $81.47$ & $\bf 83.08$ & \textcolor{blue}{$\bf 83.98$} \\ \bottomrule \end{tabular} \end{center} \vspace{-5mm} \caption{Evaluation results on NLVR2.} \label{tab:nlvr2_result} \vspace{-3mm} \end{table*} \begin{comment} \begin{table*}[h!] \begin{center} \scriptsize \begin{tabular}{l@{\hspace{2mm}}|c@{\hspace{2mm}}c@{\hspace{1mm}}|c@{\hspace{2mm}}c@{\hspace{1mm}}|c@{\hspace{2mm}}c@{\hspace{1mm}}|c@{\hspace{2mm}}c} \toprule \multirow{2}{*}{Method } & \multicolumn{2}{c|}{in-domain} & \multicolumn{2}{c|}{near-domain} & \multicolumn{2}{c|}{out-of-domain} & \multicolumn{2}{c}{overall}\\ & CIDEr & SPICE & CIDEr & SPICE & CIDEr & SPICE & CIDEr & SPICE \\ \midrule \multicolumn{9}{c}{Validation Set} \\ \hline UpDown + ELMo + CBS~\cite{agrawal2019nocaps} & $79.3$ & $12.4$ & $73.8$ & $11.4$ & $71.7$ & $9.9$ & $74.3$ & $11.2$ \\ Oscar$_\text{B}$ + SCST + CBS & $83.4$ & $12.0$ & $81.6$ & $12.0$ & $77.6$ & $10.6$ & $81.1$ & $11.7$ \\ Oscar$_\text{L}$ + SCST + CBS & $85.4$ & $11.9$ & $84.0$ & $11.7$ & $80.3$ & $10.0$ & $83.4$ & $11.4$ \\ Human~\cite{agrawal2019nocaps} & $84.4$ & \textcolor{blue}{$\bf 14.3$} & $\bf 85.0$ & \textcolor{blue}{$\bf 14.3$} & \textcolor{blue}{$\bf 95.7$} & \textcolor{blue}{$\bf 14.0$} & $\bf 87.1$ & \textcolor{blue}{$\bf 14.2$} \\ \midrule \rowcolor{Gray} \rowcolor{Gray} \textsc{Oscar+}$_{\text{B}}${} + SCST + CBS & \textcolor{blue}{$\bf 96.8$} & $\bf 13.5$ & \textcolor{blue}{$\bf 90.7$} & $\bf 13.1$ & $\bf 87.4$ & {$\bf 11.6$} & \textcolor{blue}{$\bf 90.9$} & $\bf 12.8$ \\ \midrule \multicolumn{9}{c}{Test Set} \\ \hline Oscar$_\text{B}$ + SCST + CBS & $81.3$ & $11.9$ & $79.6$ & $11.9$ & $73.6$ & $10.6$ & $78.8$ & $11.7$ \\ Oscar$_\text{L}$ + SCST + CBS & $\bf 84.8$ & $12.1$ & $82.1$ & $11.5$ & $\bf 73.8$ & $9.7$ & $80.9$ & $11.3$ \\ Human~\cite{agrawal2019nocaps} & $80.6$ & \textcolor{blue}{$\bf 15.0$} & $\bf 84.6$ & \textcolor{blue}{$\bf 14.7$} & \textcolor{blue}{$\bf 91.6$} & \textcolor{blue}{$\bf 14.2$} & $\bf 85.3$ & \textcolor{blue}{$\bf 14.6$} \\ \midrule \rowcolor{Gray} \textsc{Oscar+}$_{\text{B}}${} + SCST + CBS & \textcolor{blue}{$\bf 93.8$} & $\bf 13.3$ & \textcolor{blue}{$\bf 89.0$} & $\bf 12.8$ & $66.1$ & $\bf 10.9$ & \textcolor{blue}{$\bf 85.5$} & $\bf 12.5$ \\ \bottomrule \end{tabular} \end{center} \vspace{-5mm} \caption{NoCaps evaluation. All the models are trained on COCO only without pre-training.} \label{tab:nocaps_caption} \vspace{-3mm} \end{table*} \end{comment} In Tables~\ref{tab:vqa_result} to \ref{tab:nlvr2_result}, we report the detailed results for each downstream task, respectively. $(\RN{1})$ The \textbf{VQA} results are shown in Table~\ref{tab:vqa_result}, where our single \textsc{Oscar+}$_{\text{B}}${} model outperforms the best ensemble model (InterBERT large~\cite{lin2020interbert}) on the VQA leaderboard as of Dec. 12, 2020 \footnote{VQA leaderboard: \url{https://eval.ai/web/challenges/challenge-page/514/leaderboard/1386}}. $(\RN{2})$ The \textbf{GQA} results are shown in Table~\ref{tab:gqa_result}, where \textsc{Oscar+}{}w/\textsc{VinVL} is the first VLP model that outperforms the neural state machine (NSM)~\cite{hudson2019learning} which contains some sophisticated reasoning components deliberately designed for the task. $(\RN{3})$ The \textbf{Image Captioning} results on the public ``Karpathy" 5k test split are shown in Table~\ref{tab:mscoco_caption}. Table~\ref{tab:coco_leaderboard} shows on a concise version of the COCO image captioning online leaderboard\footnote{Image Captioning Leaderboard: \url{https://competitions.codalab.org/competitions/3221\#results}}. The online testing setting reports the results on 40K images, with 5 reference captions (c5) and 40 reference captions (c40) per image. At the time of submitting this paper, our single model achieves No.1 on the entire leaderboard, outperforming all 263 models, including many ensemble (and anonymous) models. $(\RN{4})$ The Novel Object Captioning (\textbf{NoCaps}) results are shown in Table~\ref{tab:nocaps_caption}. Without any VLP, i.e. by directly training a BERT-based captioning model on COCO, the model with our new visual features (denoted as VinVL) already surpasses the human performance in CIDEr\footnote{NoCaps leaderboard: \url{https://eval.ai/web/challenges/challenge-page/355/leaderboard/1011}}. By adding VIVO~\cite{hu2020vivo} pre-training, our VinVL improves the original VIVO result by 6 CIDEr points and creates a new SoTA. $(\RN{5})$ Overall, on all these tasks (VQA in Table~\ref{tab:vqa_result}, Image Captioning in Table~\ref{tab:mscoco_caption}, NoCaps in Table~\ref{tab:nocaps_caption}, Image-Text Retrieval in Table~\ref{tab:mscoco_retrieval}, NLVR2 in Table~\ref{tab:nlvr2_result}), we show that \textsc{Oscar+}$_{\text{B}}${} can match or outperform previous SoTA large models, and \textsc{Oscar+}$_{\text{L}}${} substantially uplifts the SoTA. \subsection{Ablation Analysis} \label{subsec:vision_ablation} We select the VQA task for the ablation study because its evaluation metric is well-defined and the task has been used as a testbed for all VLP models. To assist our analysis, we create a local validation set, vqa-dev, out of the standard validation set to select the best model during training for evaluation. vqa-dev contains randomly sampled 2K images and their corresponding questions, amounting to 10.4K image-QA pairs in total. Except for Table~\ref{tab:overall_result} and \ref{tab:vqa_result}, all our VQA results are reported on this vqa-dev set. Unless otherwise specified, the reported STD is half of the difference of two runs of the VQA training with different random seeds. In VQA, the VL model $y = \mathbf{VL}(\boldsymbol{w}, \qv, \boldsymbol{v})$ has $\boldsymbol{w}$ as the question and $y$ as the answer. We focus on studying the effect of visual features $\boldsymbol{v}$ produced by different Vision models $\mathbf{Vision}(Img)$ to better understand their relative contribution in the VQA performance. To eliminate the impact of using different tags $\qv$, we use the same tags in the VQA models of \textsc{Oscar}~\cite{li2020oscar}. All the ablation experiments are conducted using models of the BERT-base size. \paragraph{How much do the V and VL matter to the SoTA?} \begin{table*}[t!] \begin{center} \begin{tabular}{ c|ccc } \backslashbox{vision}{vl} & no VLP & \shortstack{$\textsc{Oscar}_\text{B}$ \\ \small{\cite{li2020oscar}}} & \shortstack{\textsc{Oscar+}$_{\text{B}}${} \\ \small{(ours)}} \\ \hline R101-C4~\cite{anderson2018bottom} & 68.52 \small{$\pm$0.11} & 72.38 & 72.46\small{$\pm$0.05} \\ VinVL (ours) & 71.34 \small{$\pm$0.17} & -- & 74.90\small{$\pm$0.05} \\ \end{tabular} \end{center} \vspace{-3mm} \caption{Effects of vision (V) and vision-language (VL) pre-training on VQA.} \label{tab:pretrain_ablation} \end{table*} \label{subsec:oscar_ablation} Table~\ref{tab:pretrain_ablation} shows the VQA results with different vision models, i.e., R101-C4 model from \cite{anderson2018bottom} and our X152-C4 model pre-trained with 4 datasets (VinVL), and with different VLP methods, i.e., no VLP, \textsc{Oscar}~\cite{li2020oscar} and our \textsc{Oscar+}. Taking the $\textsc{Oscar}_\text{B}$ model with R101-C4 features as the baseline, the \textsc{Oscar+}$_{\text{B}}${} model with our X152-C4 features improves the absolute accuracy from 72.38 to 74.90, in which the \textsc{Oscar+}{} pre-training contributes 5\% of the gain (i.e., $72.38\rightarrow 72.46$) and the vision pre-training (improved visual features) 95\% (i.e., $72.46\rightarrow 74.90$). This demonstrates that vision representations matter significantly in VLP and downstream tasks. Taking the ``no VLP'' model with R101-C4 features as the baseline, Table~\ref{tab:pretrain_ablation} shows that the gains of VinVL ($71.34-68.52 = 2.82$) and VLP ($72.46-68.52 = 3.94$) are additive ($74.90-68.52 \approx 2.82 + 3.94$). This is intuitive because vision pre-training and VLP improve the Vision model $\mathbf{Vision}(Img)$ and VL model $\mathbf{VL}(\boldsymbol{w}, \qv, \boldsymbol{v})$ separately. This also indicates that our pre-trained vision model can be utilized in any VL models by directly replacing their vision models, such as R101-C4 \cite{anderson2018bottom}, with ours. \paragraph{How much do data and model sizes matter to the new vision model?} The improvement of VQA from R101-C4~\cite{anderson2018bottom} to VinVL (ours) in Table~\ref{tab:pretrain_ablation} is a compound effect of increasing model size (from R101-C4 to X152-C4) and data size (from VG to our merged four OD datasets). Table~\ref{tab:model_data_size} shows the ablation of the two factors without VLP. Although VG's large object and attribute vocabulary allows to learn rich semantic concepts, VG does \emph{not} contain large amounts of annotations for effective training of deep models. Vision models trained using the merged four OD datasets perform much better than VG-only-trained models, and the improvement is larger with the increase of the model size.\footnote{The R101-C4 model in Table~\ref{tab:model_data_size} is exactly the VG-pre-pretrained model from \cite{anderson2018bottom}. We do not train this model on our merged OD dataset because this model architecture is old-fashioned and is slow to train.} \paragraph{How much does OD model architecture matter?} The choice of model architecture affects the VQA performance. Table~\ref{tab:model_data_size} shows that R50-FPN under-performs R50-C5 when they are trained only on VG; but the performance gap diminishes when both are trained on the merged dataset (4Sets). A detailed comparison between FPN and C4 architectures is presented in Appendix~\ref{app:c4vsfpn}. \begin{table}[t!] \begin{center} \begin{tabular}{ c|cccc } \backslashbox{data}{model} & R50-FPN & R50-C4 & R101-C4~\cite{anderson2018bottom} & X152-C4 \\ \hline VG & 67.35\small{$\pm$0.26} & 67.86\small{$\pm$0.31} & 68.52 \small{$\pm$0.11} & 69.10\small{$\pm$0.06} \\ 4Sets$\rightarrow$VG & 68.3\small{$\pm$0.11} & 68.39\small{$\pm$0.16} & -- & 71.34 \small{$\pm$0.17} \\ \end{tabular} \end{center} \vspace{-4mm} \caption{Ablation of model size and data size on training vision models.} \label{tab:model_data_size} \vspace{-1mm} \end{table} \begin{table*}[t] \begin{center} \begin{threeparttable} \begin{tabular}{ c|cc|cc|cc} Model & \multicolumn{2}{c|}{R50-FPN} & \multicolumn{2}{c|}{R50-C4} & \multicolumn{2}{c}{X152-C4} \\ Pre-training dataset & ImageNet & 4Sets & ImageNet & 4Sets & ImageNet5k & 4Sets \\ \midrule COCO $mAP$ & 40.2~\cite{wu2019detectron2} & 44.78\tnote{*} & 38.4~\cite{wu2019detectron2} & 42.4 & 42.17 & 50.51 \\ \hline \shortstack{VG obj $mAP^{50}$ \\ attr $mAP$ with gt boxes} & \shortstack{9.6\\5.4} & \shortstack{11.3\\5.5} & \shortstack{9.6\\6.3} & \shortstack{12.1 \\ 6.1} & \shortstack{11.2 \\ 6.6} & \shortstack{13.8 \\ 7.1} \\ \bottomrule \end{tabular} \begin{tablenotes} \item[*] Since our four pre-training datasets contain Objects365, it is not surprising that we obtain better results than 42.3 $mAP^{50}$ in \cite{shao2019objects365}, which is obtained by pre-training on Objects365. \end{tablenotes} \end{threeparttable} \end{center} \vspace{-4mm} \caption{Effect of vision pre-training on object detection tasks.} \label{tab:odtasks} \end{table*} \paragraph{How much does OD pre-training matter for object detection tasks?} Table~\ref{tab:odtasks} presents the object detection results on COCO and the object-attribute detection results on VG (1594 object classes, 524 attribute classes). The results show that OD pre-training benefits the object detection tasks. Note that the mAP on VG is much lower than that on typical OD datasets (such as COCO) due to two reasons: (1) VG contains a large number of object classes with limited and extremely unbalanced annotations, (2) there are many missing annotations in the VG evaluation data.\footnote{As a reference, the R101-C4 model from \cite{anderson2018bottom} on VG with 1600 objects and 400 attributes has mAP of 8.7/7.8 evaluated in our code, whereas it was reported as 10.2/7.8 due to differences in OD evaluation pipeline.} Although the mAP numbers are low, the detection result using X152-C4 is reasonably good; see Appendix~\ref{app:visionqa} for more visualizations. We also see that FPN models perform consistently worse in attribute detection than C4 models, neither do FPN models show any advantage in object detection on VG. This contributes to the inferior performance of FPN, compared to C4, on downstream VL tasks, as discussed in Section~\ref{subsec:vision_pretrain}. \paragraph{How much does the diversity of visual concepts, i.e., object and attribute vocabularies, matter?} \begin{table*}[t!] \begin{center} \begin{tabular}{ c|c|cccc|c} Dataset name & ImageNet & VG-obj & VG w/o attr & VG~\cite{anderson2018bottom} & VG & 4Sets$\rightarrow$VG \\ \#obj \& \#attr & 1000 \& 0 & 317 \& 0 & 1594 \& 0 & 1600 \& 400 & 1594 \& 524 & 1848 \& 524 \\ \midrule R50-C4 + BERT$_{B}$ & 66.13\small{$\pm$0.04} & 64.25\small{$\pm$0.16} & 66.51\small{$\pm$0.11} & 67.63\small{$\pm$0.25} & 67.86\small{$\pm$0.31} & 68.39\small{$\pm$0.16} \\ \end{tabular} \end{center} \vspace{-4mm} \caption{Effect of object-attribute vocabulary. We use all grid features (maximal 273) for the ImageNet classification model (first column), and maximal 50 region features for OD models (other columns).} \label{tab:od_objattr} \end{table*} We directly train vision models on different datasets, including (1) standard ImageNet with 1K classes (ImageNet), (2) Visual Genome with 317 object classes (VG-obj) that are shared with COCO 80 classes and OpenImagesV5 500 classes, (3) VG with all 1594 object classes (VG w/o attr), (4) VG with 1594 object classes and 524 attribute classes (VG), and (5) the merged OD dataset (4Sets) for pre-training and VG for fine-tuning. For all the OD models (the last four columns in Table~\ref{tab:od_objattr}), we initialize the OD training with an ImageNet-pre-trained classification model, and use maximal 50 \textit{region} features per image as input to the VL fusion module. For the ImageNet pre-trained classification model (the second column in Table~\ref{tab:od_objattr}), we use all the \textit{grid} features (maximal 273) for each image\footnote{Our use of grid feature follows PixelBert~\cite{huang2020pixel}. See Appendix~\ref{appsec:gridfeature} for details.}. The results show that \begin{itemize}[noitemsep,leftmargin=*,topsep=2pt] \item In general, vocabularies with richer objects lead to better VQA results: VG-obj $<$ ImageNet $<$ VG w/o attr. The VG-obj vocabulary contains 79 of 80 COCO classes (only missing \texttt{potted plant}) and 313 of 500 OpenImagesV5 classes, and is a good approximation of common object classes of typical OD tasks. However, our results show that this vocabulary is not rich enough for VL tasks because it misses many important visual concepts (e.g., \texttt{sky}, \texttt{water}, \texttt{mountain}, etc.) which are crucial for VL tasks, as also illustrated by the comparison of detected regions in Figure~\ref{fig:pretrain_finetune}. \footnote{Using the same training procedure on VG, we trained an R50-C4 model on the OpenImagesV5 dataset (500 classes). Using the region features produced by this model, the VQA performance is 63.55$\pm$0.14. The result is slightly worse than that of VG-obj because both VG and VQA images are from the COCO dataset but OpenImages images are not. }. \item Attribute information is crucial to VL tasks: models trained with attributes (VG and 4Sets$\rightarrow$VG) are significantly better than those without attributes. \item Even for the small vision model R50-C4, vision pre-training improves visual features for VQA, i.e., 4Sets$\rightarrow$VG is the best performer. \end{itemize} In Table~\ref{tab:region_effect}, we use different kinds of region proposals to extract image features. COCO groundtruth object regions (GT-Obj, 80 classes) and object-stuff regions (GT-Obj\&Stuff, 171 classes) are perfect in terms of localization, but their vocabulary sizes are limited. Regions proposed by VG-trained models ([2] and VinVL) are imperfect in localization but using a larger vocabulary. For the VQA task, COCO GT boxes are much worse than the proposals generated by VG-trained models. The result demonstrates the difference between the typical OD tasks and the OD tasks in VL: OD in VL requires much richer visual semantics to align with the rich semantics in the language modality. This further echoes our claim that an image understanding module trained using richer vocabularies performs better for VL tasks. \begin{table}[ht] \begin{center} {\begin{tabular}{ c|cccc } \backslashbox{model}{region} & GT-Obj & GT-Obj\&Stuff & \shortstack{Anderson \\ et al. [2]} & VinVL (ours) \\ \hline \shortstack{Anderson \\ et al. [2]} & 63.81 {$\pm$0.94} & 66.68 {$\pm$0.16} & 68.52 {$\pm$0.11} & 69.05 {$\pm$0.06} \\ VinVL (ours) & 65.60 {$\pm$0.21} & 68.13 {$\pm$0.26} & 70.25 {$\pm$0.05} & 71.34 {$\pm$0.17} \\ \end{tabular}} \end{center} \vspace{-4mm} \caption{Effect of different region proposals on VQA.} \label{tab:region_effect} \vspace{-4mm} \end{table} \begin{comment} \paragraph{Inference speed.} We report the end-to-end inference times of different VQA models on a Titan-X GPU in Table~\ref{tab:model_efficiency_gpu} and on CPU with a single thread in Table~\ref{tab:model_efficiency_cpu} in Appendix~\ref{appsec:gridfeature}. The input image size is $800\times 1333$, and we run the inference with batch size 1 (one image-question pair per batch). We can see that (1) although our X152-C4 model has more parameters than the popular R101-C4~\cite{anderson2018bottom} model, their inference speed is nearly the same because we replace the slow dilation-2 layers in R101-C4~\cite{anderson2018bottom} with more efficient dilation-1 layers; (2) with the class-agnostic NMS during inference (Region-fast), region-feature models are greatly sped up and their inference time can be brought to within 3 times of that of grid-feature models; (3) vision models dominate the inference time, especially for large models; (4) models based on grid-feature are faster than those based on region feature. \begin{table*}[ht!] \begin{center} \begin{tabular}{ l|cc|cc|cc } \multirow{2}{*}{Model} & \multicolumn{2}{c|}{R50-C4} & \multicolumn{2}{c|}{R101-C4~\cite{anderson2018bottom}} & \multicolumn{2}{c}{X152-C4} \\ & $\mathbf{Vision}$ & $\mathbf{VL}$ & $\mathbf{Vision}$ & $\mathbf{VL}$ & $\mathbf{Vision}$ & $\mathbf{VL}$ \\ \hline Grid-273 & 0.056\small{$\pm$0.005} & 0.027\small{$\pm$0.002} & 0.082\small{$\pm$0.022} & 0.034\small{$\pm$0.001} & 0.344\small{$\pm$0.036} & 0.037\small{$\pm$0.004} \\ Region & 0.373\small{$\pm$0.040} & 0.031\small{$\pm$0.005} & 0.663\small{$\pm$0.042} & 0.034\small{$\pm$0.003} & 0.687\small{$\pm$0.064} & 0.036\small{$\pm$0.005} \\ Region-fast & 0.165\small{$\pm$0.029} & 0.029\small{$\pm$0.002} & 0.442\small{$\pm$0.119} & 0.036\small{$\pm$0.003} & 0.475\small{$\pm$0.049} & 0.037\small{$\pm$0.005} \\ \end{tabular} \end{center} \caption{End-to-end inference speed on VQA. For the SoTA number obtained with the X152-C4 region features, the performance {\it keeps the same} when changing to class-agnostic NMS to extract the feature (region-fast) while the speed greatly improves.} \label{tab:model_efficiency_gpu} \end{table*} \end{comment} \section{Conclusion} \label{sec:con} In this paper we have presented a new recipe to pre-train an OD model for VL tasks. Compared to the most widely used \emph{bottom-up and top-down} model \cite{anderson2018bottom}, the new model is bigger, better-designed for VL tasks, and pre-trained on much larger text-image corpora, and thus can generate visual features for a richer collection of visual objects and concepts that are crucial for VL tasks. We validate the new model via a comprehensive empirical study where we feed the visual features to a VL fusion model which is pre-trained on a large-scale paired text-image corpus and then fine-tuned on seven VL tasks. Our results show that the new OD model can substantially uplift the SoTA results on all seven VL tasks across multiple public benchmarks. Our ablation study shows that the improvement is mainly attributed to our design choices regarding diversity of object categories, visual attribute training, training data scale, model size, and model architecture. \section*{Acknowledgement} We thank Xi Yin for her contributions to this project while she was in Microsoft. We thank Xiyang Dai for his conjecture that C4 arch is better than FPN because C4 arch makes better use of ImageNet initialization weights. \section{Qualitative study of three pre-trained vision models} \label{app:visionqa} \begin{figure*}[t!] \includegraphics[width=0.99\textwidth]{vinvl_figs/OI_X152FPN.PNG} \caption{Predictions from X152-FPN trained on OpenImages. Test image: COCO\_test2015\_000000028839} \label{fig:oi_pretrain_finetune} \end{figure*} \begin{figure*}[t!] \centering \includegraphics[width=0.89\textwidth]{vinvl_figs/Panderson_R101C4.PNG}\\ \includegraphics[width=0.89\textwidth]{vinvl_figs/VinVL_X152C4.PNG} \caption{Predictions from R101-C4 trained on VG from~\cite{anderson2018bottom} (top), X152-C4 pre-trained on 4 OD datasets and finetuned on VG (bottom). Test image: COCO\_test2015\_000000028839} \label{fig:vg_pretrain_finetune} \end{figure*} We apply three (pre-trained) object detection models on the image in Figure \ref{fig:pretrain_finetune} and list their detection results for a more detailed comparison. Detections from X152-FPN trained on Open Images V5. See Figure \ref{fig:oi_pretrain_finetune}:\\ \texttt{Surfboard; Surfboard; Surfboard; Surfboard; Man; Human leg; Human leg; \\ Swimwear; Swimwear; Shorts; Shorts; Boy; Human arm}. Detections from R101-C4 trained on VG by Anderson \etal ~\cite{anderson2018bottom}. There are obviously wrong detections, marked in \textcolor{red}{red}. See Figure \ref{fig:vg_pretrain_finetune} (top):\\ \texttt{black shorts; young, shirtless, standing, barefoot, surfing, little, \\playing boy; shirtless, standing, barefoot, walking, wet, surfing, young man; tan, bare, shirtless back; blue, clear, cloudy, hazy, light blue sky; young, shirtless, standing, surfing, barefoot, little boy; brown, short, wet, blond hair; brown, short, wet, blond hair; small, crashing wave; \\ white, wet surfboard; white, crashing, big, rolling wave; \\ wet, tan surfboard; green, blue fin; blue, calm, choppy, wavy, ocean, \\splashing, foamy, water, rough, sandy, wet ocean; wet, calm, sandy, \\splashing, wavy water; white, wet surfboard; bare, wet foot; \\blue, colorful, multi colored, floral shorts; calm, choppy, water, rough, foamy, wavy water; distant, rocky, hazy mountains; standing, shirtless, \\young, barefoot, wet, surfing, walking, smiling boy; calm ocean; distant, rocky mountain; white, bare, wet surfboard; wet, sandy, calm, tan beach; \textcolor{red}{gray, big rock}; \textcolor{red}{blue, calm background}; wet, brown, tan, sandy sand; \\wet shadow; blue, colorful, floral, multi colored swim trunks; \\ \textcolor{red}{yellow, plastic hand}}. Detections from our pre-trained X152-C4 model pre-trained on four datasets and fine-tuned on VG. There are some repetitive detections, but no obvious wrong detections. See Figure \ref{fig:vg_pretrain_finetune} (bottom): \\ \texttt{blue, green fin; young, barefoot, shirtless, standing, surfing, smiling, little, playing, looking, blond boy; young, barefoot, standing, shirtless, smiling, surfing, blond, playing, looking, little, walking, riding boy; \\ shirtless, barefoot, standing, young, smiling, surfing, walking, wet, playing man; bare, wet foot; black, white surfboard; small, large, white, crashing, big, water, rolling, splashing, rough, foamy wave; bare, wet foot; dark, black, wet, cast shadow; blue, clear, hazy, cloudy, cloudless sky; black, gray, white, raised surfboard; black, wet, short short; brown, short, blond, wet, curly, wavy hair; distant, brown, large, rocky, hazy, big mountain; brown, short, dark, blond, wet hair; blue, white, calm, wavy, choppy, ocean, splashing, water, rough, clear, shallow water; bare, tan, light, beige back; black, blue, wet surfboard; small, dark, water, crashing, rolling, splashing, big wave; wet, white, sandy, tan surfboard; blue, colorful, floral, multi colored, patterned trunk; wet, brown, sandy, tan sand; white, blue, calm, foamy, choppy, splashing, wavy, ocean, rough, water, clear, shallow water; wet, brown, sandy, calm, tan, shallow, smooth, muddy, rough beach; black, white, young board; shirtless, young, standing, barefoot, smiling, surfing, looking, walking, playing boy; blue, calm, choppy, wavy, ocean, clear, rough, splashing, water, foamy, shallow, rippled ocean; yellow, gold bracelet; white, silver, black logo; wet, bare, bent, tan, crossed, hairy, short, skinny, back, muscular, extended, outstretched leg; black, gray, white board; brown, distant, large, rocky, big hill; brown, short, blond, wet, curly head; red, black logo; bare, raised, extended, holding, open, up, bent, outstretched hand; black, wet swim trunks; bare, wet, bent, tan, crossed, skinny, short, back, muscular leg; wet, brown, muddy, sandy, tan, shallow reflection}. \section{\textsc{Oscar+}{} pre-training} \subsection{Pre-training Corpus} \begin{table*}[ht!] \begin{center} \resizebox{\linewidth}{!}{ \begin{tabular}{c|c|c|c|c|c|c|c|c} \toprule Small & \multicolumn{5}{c|}{0.22M Images, 2.5M QAs, 0.7M captions} \\ \midrule Medium & \multicolumn{6}{c|}{ 1.89M Images, 2.5M QAs, 0.7M captions, 1.67M pseudo-captions} \\ \midrule Large & \multicolumn{8}{c}{ 5.65M Images, 2.5M QAs, 4.68M captions, 1.67M pseudo-captions} \\ \midrule \multirow{2}{*}{Source} & VQA & GQA & VG-QA & COCO & Flicker30k & OpenImages & CC & SBU \\ & (train) & (bal-train) & (train) & (train) & (train) & (od train) & (train) & (all) \\ \midrule Image/Text & 83k/545k & 79k/1026k & 87k/931k & 112k/559k & 29k/145k & 1.67M/1.67M & 3.1M/3.1M & 875k/875k \\ \midrule $\boldsymbol{w},\qv,\boldsymbol{v}$ & \multicolumn{3}{c|}{ Question, Answer, ImageFeatures} & \multicolumn{5}{c}{(Generated) Caption, (Generated) ImageTags, ImageFeatures} \\ \bottomrule \end{tabular}} \end{center} \caption{Statistics of the pre-training corpus.} \label{tab:pretrain_corpus} \end{table*} Table~\ref{tab:pretrain_corpus} shows the statistics of image and text of the pre-training corpora. In our ablation study, we use corpora of three different sizes: `Small', `Medium', `Large'. Different from \textsc{Oscar}~\cite{li2020oscar}, we make use of image tagging datasets OpenImages, by generating captions using \textsc{Oscar}'s image captioning model to form triplets of (generated caption, image tags, image features) for \textsc{Oscar+}{} pre-training. By self-training technique, our pre-training corpora can be scaled to a much larger amount by making use of large-scale image tagging datasets, e.g., OpenImages (9M) and YFCC (92M). \subsection{\textsc{Oscar+}{} pre-training objectives} \label{app:oscarlosses} \paragraph{Masked Token Loss: A Loss Mimics Image Captioning.} The word tokens of image captions (questions) $\boldsymbol{w}$ and word tokens of object tags (answers) $\qv$ share the same linguistic semantic space, and the Masked Token Loss (MTL) is applied on tokens of both $\boldsymbol{w}$ and $\qv$. We define the {\it discrete token sequence} as $\hv \triangleq [\boldsymbol{w}, \qv]$, and apply the Masked Token Loss (MTL) for pre-training. At each iteration, we randomly mask each input token in $\hv$ with probability $15\%$, and replace the masked one $h_i$ with a special token $\mathtt{[MASK]}$. The goal of training is to predict these masked tokens based on their surrounding tokens $\hv_{\backslash i}$ and image features $\boldsymbol{v}$ by minimizing the negative log-likelihood: \begin{align} \hspace{-0mm} \mathcal{L}_{\text{MTL}} = -\mathbb{E}_{ (\boldsymbol{v}, \hv) \sim \mathcal{D} } \log p( h_i | \hv_{\backslash i}, \boldsymbol{v} ) \label{eq_attend_mlm} \end{align} This is the same MTL as in \textsc{Oscar}~\cite{li2020oscar} and similar to the masked language model used by BERT. The masked word or tag needs to be recovered from its surrounding context, with additional image information to help ground the learned word embeddings in the vision context. \begin{figure*}[t!] \centering \includegraphics[width=0.8\textwidth]{vinvl_figs/selftraining_ablation.png} \caption{Effect of \textsc{Oscar+}{} pre-training corpus size and effect of self-training by making use of tagging data in \textsc{Oscar+}{}. Each curve, with legend ``VLP, Corpus; VisionFeature'', denotes a VLP experiment where the VLP method is either \textsc{Oscar} \, or \textsc{Oscar+}{}, the VLP pre-training Corpus is Small/Medium/Large (defined in Table~\ref{tab:pretrain_corpus}), and VisionFeature is either our new vision features (VinVL for short) or those from \cite{anderson2018bottom} (\cite{anderson2018bottom} for short). X-axis denotes the pre-training iterations of \textsc{Oscar+}{} checkpoints. Y-axix is the vqa-dev accuracy of a VQA model initialized from the corresponding pre-training checkpoint and fine-tuned with a fixed scheme. Compared with ``\textsc{Oscar+}{}, Small; VinVL" (green), ``\textsc{Oscar+}{}, Medium; VinVL" (yellow) adds the 1.7M OpenImages Tagging data into the pre-training and its performance gets improved significantly, demonstrating the effect of self-training by making use of tagging data. The ``\textsc{Oscar+}{}, Large; VinVL" (blue) further scales up the pre-training corpus by adding Google Conceptual Captions and SBU datasets with generated tags and its performance gets further improved, demonstrating the effect of \textsc{Oscar+}{} pre-training corpus size. As baselines, we also provide performance of \textsc{Oscar}\, and \textsc{Oscar+}{} with image features from \cite{anderson2018bottom}, which clearly demonstrates that our new image features (VinVL) matter significantly in the VL pre-training and VL downstream tasks.} \label{fig:selftraining_ablation} \end{figure*} \paragraph{3-way Contrastive Loss: A Loss Mimics Text-Image Retrieval and Visual Question Answering Simultaneously.} We present our 3-way contrastive loss in Section~\ref{subsec:oscarobjective} in the main paper. \subsection{Ablation of the two new techniques} \paragraph{Effect of self-training: Leveraging Image Tagging data.} In Figure~\ref{fig:selftraining_ablation}, we show the effect of self-training by making use of tagging data in \textsc{Oscar+}{}, by fine-tuning \textsc{Oscar+}{} pre-training checkpoints on VQA. Compared with ``\textsc{Oscar+}{}, Small; VinVL" (green), ``\textsc{Oscar+}{}, Medium; VinVL" (yellow) adds the 1.7M OpenImages Tagging data into pre-training and its performance gets improved significantly, demonstrating the effect of self-training by making use of tagging data. As baselines, we also provide performance of \textsc{Oscar}\, and \textsc{Oscar+}{} with image features from \cite{anderson2018bottom}, which clearly demonstrates that the new image features pre-trained by VinVL matter significantly in the VL pre-training and VL downstream tasks. \paragraph{Effect of the new 3-way contrastive loss.} As illustrated in Table~\ref{tab:contrastive}, with the new 3-way contrastive loss, the VQA performance is the same as the \textsc{Oscar} \ pre-training, while the Text-Image Retrieval performance improves significantly compared with the \textsc{Oscar} \ pre-training. \paragraph{Overall improvement from \textsc{Oscar} ~to \textsc{Oscar+}{}.} We point out that the improvement from \textsc{Oscar} ~to \textsc{Oscar+}{} with image features from \cite{anderson2018bottom} is minor, because (1) we only add 1.7M OpenImages' tagging data to enlarge the pre-training corpus, which is a small portion compared with \textsc{Oscar}'s original pre-training corpus (i.e., Large$\backslash$OI, 3.98M images and 7.18M image-caption pairs), and (2) the new 3-way contrastive loss has more significant improvements in Text-Image Retrieval tasks than that in the VQA task, as illustrated in Table~\ref{tab:contrastive}. We would expect much more significant improvements when we scale up the \textsc{Oscar+}{}'s pre-training corpus to a much larger scale by adding large scale image tagging datasets, e.g., OpenImages (9M) and YFCC (92M). \section{Downstream Tasks Fine-tuning} \label{sec:downstreams} We follow the downstream task fine-tuning recipes in \textsc{Oscar}~\cite{li2020oscar}. \subsection{VQA} Given an image and a question, the task is to select the correct answer from a multi-choice list, it requires the model to answer natural language questions based on an image. Here we conduct experiments on the widely-used VQA v2.0 dataset~\cite{goyal2017making}, which is built on the MSCOCO~\cite{lin2014microsoft} images. Following~\cite{anderson2018bottom}, for each question, the model picks the corresponding answer from a shared set of $3,129$ candidates. When fine-tuning on the VQA task, the input sequence contains the concatenation of a given question, object tags and object region features, and then the $\mathtt{[CLS]}$ output from \textsc{Oscar+}{} is fed to a task-specific linear classifier for answer prediction. Similarly as the literature~\cite{anderson2018bottom}, we treat VQA as a multi-label classification problem – assigning a soft target score to each answer based on its relevancy to the human answer responses, and then we fine-tune the model by minimizing the cross-entropy loss computed using the predicted scores and the soft target scores. During inference, we simply use Softmax for answer prediction. For VQA training, we random sample a set of 2k images from the MS COCO validation set as our validation set, the rest of images in the training and validation are used in the VQA fine-tuning. For the \textsc{Oscar+}$_{\text{B}}${} model, we fine-tune for $25$ epochs with a learning rate of $5e^{-5}$ and a batch size of $128$. For the \textsc{Oscar+}$_{\text{L}}${} model, we fine-tune for $25$ epochs with a learning rate of $3e^{-5}$ and a batch size of $96$. \subsection{GQA} Similarly as VQA, GQA tests the reasoning capability of the model to answer a question. We conduct experiments on the public GQA dataset~\cite{hudson2019gqa}. For each question, the model chooses an answer from a shared set of $1,852$ candidates. Our fine-tuning procedure is following Oscar~\cite{li2020oscar,chen2019meta}, which first fine-tunes the model on unbalanced ``all-split'' for $5$ epochs with a learning rate of $5e^{-5}$ and a batch size of $128$, and then fine-tuned on the ``balanced-split'' for $2$ epochs. \subsection{Image Captioning} An image captioning model generates a natural language description for a given image. To enable sentence generation, we fine-tune \textsc{Oscar+}{} using the seq2seq objective. The input samples are processed to triples consisting of image region features, captions, and object tags, in the same way as that during the pre-training. We randomly mask out $15\%$ of the caption tokens and use the corresponding output representations to perform classification to predict the token ids. Similar to previous works~\cite{li2020oscar,zhou2019unified}, the self-attention mask is constrained such that a caption token can only attend to the tokens before its position to simulate a uni-directional generation process. Note that all caption tokens will have full attentions to image regions and object tags but not the other way around. During inference, we first encode the image regions, object tags, and a special token $\mathtt{[CLS]}$ as input. Then the model starts the generation by feeding in a $\mathtt{[MASK]}$ token and selecting a token from the vocabulary based on the likelihood output. Next, the $\mathtt{[MASK]}$ token in the previous input sequence is replaced with the selected token and a new $\mathtt{[MASK]}$ is appended for the next word prediction. The generation process terminates when the model outputs the $\mathtt{[SEP]}$ token. We use beam search (\ie beam size = 5)~\cite{anderson2018bottom} in our experiments and report our results on the COCO image captioning dataset. Though the training objective (\ie seq2seq) for image captioning is different from that used in pre-training (\ie bidirectional attention-based masked token loss), we directly fine-tune \textsc{Oscar+}{} for image captioning on COCO without additional pre-training on Conceptual Captions~\cite{sharma2018conceptual}. This is to validate the generalization ability of the \textsc{Oscar+}{} models for generation tasks. We use the same Karpathy split~\cite{karpathy2015deep}. For the \textsc{Oscar+}$_{\text{B}}${} model, we fine-tune with cross-entropy loss for $30$ epochs with a batch size of $256$ and an initial learning rate of $1e^{-5}$ and then with CIDEr optimization~\cite{rennie2017self} for $10$ epochs with a batch size of $128$ and initial learning rate of $2e^{-6}$. We compare with several existing methods, including BUTD~\cite{anderson2018bottom}, VLP~\cite{zhou2019unified}, AoANet~\cite{huang2019attention}, OSCAR~\cite{li2020oscar}. \subsection{NoCaps} Novel Object Captioning~\cite{agrawal2019nocaps} extends the image captioning task, is to test models' capability of describing novel objects from the Open Images dataset~\cite{kuznetsova2018open} which are not seen in the training corpus. Following the restriction guideline of NoCaps, we train \textsc{Oscar+}{} on COCO without the initialization from pre-training, so no additional image-text pairs are used for training except COCO. Since NoCaps images are collected from Open Images, we train an object detector using the Open Images training set and apply it to generate the tags. We conduct experiments from BERT model directly without pre-training as required by the task guidelines. For the \textsc{Oscar+}$_{\text{B}}${} model, we train $30$ epochs with a batch size of $256$ and learning rate $1e^{-4}$; further we perform CIDEr optimization with learning rate $5e^{-6}$ and batch size $112$ for $10$ epochs. During inference, we use constrained beam search for decoding. We compare \textsc{Oscar+}{} with OSCAR~\cite{li2020oscar} on this task. \subsection{Image-Text Retrieval} There are two sub-tasks: {\it image retrieval} and {\it text retrieval}, depending on which modality is used as the retrieved target. Both tasks calculate a similarity score between an image and a sentence, which heavily relies on the cross-modal representations. Following Oscar~\cite{li2020oscar}, we formulate the retrieval as a binary classification problem, where given an aligned image-text pair, we randomly select a different image or a different sentence to form an unaligned pair. The final representation of $\mathtt{[CLS]}$ is used as the input to the classifier to predict whether the given pair is aligned or not. In the testing stage, the probability score is used to rank the given image-text pairs of a query. Following~\cite{li2019unicoder}, we report the top-$K$ retrieval results on both the $1$K and $5$K COCO test sets. We adopt the widely used Karpathy split~\cite{karpathy2015deep} on the COCO caption dataset~\cite{lin2014microsoft} to conduct our experiments. Specifically, the dataset consists of $113,287$ images for training, $5,000$ images for validation, and $5,000$ images for testing. Each image is associated with $5$ human-generated captions. For the \textsc{Oscar+}$_{\text{B}}${} model, we fine-tune with a batch size of $256$ for $40$ epochs. The initial learning rate is set to $2e^{-5}$ and linearly decreases. For the \textsc{Oscar+}$_{\text{L}}${} model, we fine-tune with a batch size of $128$ for $40$ epochs. The initial learning rate is set to $1e^{-5}$ and linearly decreases. We use the validation set for parameter tuning. We compare with several existing methods, including DVSA~\cite{karpathy2015deep}, VSE++~\cite{faghri2017vse++}, DPC~\cite{zheng2017dual}, CAMP~\cite{wang2019camp}, SCAN~\cite{lee2018stacked}, SCG~\cite{shi2019knowledge}, PFAN~\cite{wang2019position}, Unicoder-VL~\cite{li2019unicoder}, 12-in-1~\cite{lu201912}, UNITER~\cite{chen2019uniter}. \subsection{NLVR2} Given a pair of images and a natural language, the goal of NLVR2~\cite{suhr2018corpus} is to determine whether the natural language statement is true about the image pair. For NLVR2 fine-tuning, we first construct two input sequences, each containing the concatenation of the given sentence (the natural language description) and one image, and then two $\mathtt{[CLS]}$ outputs from \textsc{Oscar+}{} are concatenated as the joint input for a binary classifier, implemented by an MLP. For the \textsc{Oscar+}$_{\text{B}}${} model, we fine-tune for $20$ epochs with learning rate \{$2e^{-5}$, $3e^{-5}$, $5e^{-5}$\} and a batch size of $72$. For the \textsc{Oscar+}$_{\text{L}}${} model, we fine-tune for $20$ epochs with learning rate of \{$2e^{-5}$, $3e^{-5}$\} and a batch size of $48$. \begin{figure}[t!] \centering \includegraphics[width=0.7\columnwidth]{vinvl_figs/vinvl-fig2_v3.PNG} \caption{Overall comparison of vocabulary effect on VQA. X-axis: how the R50-C4 model is trained; Y-axis: how the feature is extracted (grid or region features, different kinds of boxes to extract region features). All region features have maximal 50 regions. The top row ``Mean'' is the average over all rows, showing the overall quality of different vision models. The far-right column ``Mean'' is the average over all columns, showing the overall quality of different feature extraction methods.} \label{fig:vocab_overall} \end{figure} \begin{figure*}[t!] \centering \includegraphics[width=0.49\textwidth]{vinvl_figs/vocab_modelckpts_v3.png} \includegraphics[width=0.49\textwidth]{vinvl_figs/vocab_boxtypes_v3.png} \caption{Left: comparison of object vocab and attribute vocab, average over all types of bounding boxes. Right: comparison of feature extraction methods, average over all types of pre-trained vision models. X-axis is the number of iterations when we take the checkpoint for evaluation. Y-axis is the VQA accuracy on our vqa-dev.} \label{fig:vocab_boxtypes} \end{figure*} \section{More on the Effect of the Object-Attribute Vocabulary Size: disentangling the effects of region proposals and model weights} In Section~\ref{subsec:vision_ablation}, we demonstrate that the more diverse the visual concepts (object and attribute vocabularies) are, the better the visual region features for VL tasks. The better performance may come from the more diverse proposed regions where the region features are extracted (see the comparison in Figure~\ref{fig:pretrain_finetune}, ``region" for short), or from the better model weights that can produce better high-dimensional region representation even for the same region (``model" for short). In this section, we disentangle effects of region proposals and model weights, by performing synthetic experiments in which we use region proposals from one vision model and model weights from another vision model. Our results show that both the region proposals and model weights matter for VL tasks. \subsection{Disentangling the effects of region proposals and model weights on R50-C4} As in Section~\ref{subsec:vision_ablation}, We train vision models $\boldsymbol{v} = \mathbf{Vision}(Img)$ on different datasets, i.e., OpenImages with 500 object classes (OI:O500), standard ImageNet with 1K classes (ImageNet:O1000), Visual Genome with 317 object classes (VG-obj), Visual Genome with 1594 object classes (VG:O1594), VG with 1594 object classes and 524 attribute classes (VG:O1594A524), pretrain on the merged 4 datasets and finetune on VG:O1594A524 (4Sets$\rightarrow$VG:O1594A524). For {\it each} model, we also try different ways to extract features: (1) \textit{region} features from different models' proposed regions (same notations with models) where each image has maximal 50 region features, and (2) \textit{grid} features where we use all grid features (Grid-273) or randomly sampled 50 grid features (Grid-50) for each image. We present the results of these model-region cross-combination experiments in Figure~\ref{fig:vocab_overall}. We also present the mean accuracy over all box types to obtain a robust ranking of different checkpoints and the mean accuracy over all checkpoints to obtain a robust ranking of different box types. We have the following observations: \begin{itemize}[noitemsep,leftmargin=*,topsep=2pt] \item The richer the object vocabulary is, the better for VQA: OI:500 $\approx$ VG-obj:O317 $<$ ImageNet:O1000 $<$ VG:O1594. \item Attribute information is crucial to VL tasks: all features trained with attributes (Columns with VG:O1594A524) are significantly better than those without attributes. \item Even for small vision backbone R50, vision pre-training makes vision features better: Column \\ ``4Sets$\rightarrow$VG:O1594A524" are better than all other columns. Notice that the vision pre-training improves both the region features and the grid features. \item It is crucial to extract features from semantically diverse regions: regions from OI and VG-obj are significantly worse than all other regions, and is even worse than grid features. \item Grid features perform worse than region features with regions proposed by VG models. By comparing Row ``Grid-273'' with rows with VG regions, it seems hopeful to close this gap while paying more hardware memory and computational cost in cross-modal models $\mathbf{VL}$. It is three times slower to {\bf train} the ``Grid-273'' models than training models with region features. \end{itemize} In Figure~\ref{fig:vocab_boxtypes}, instead of just showing one final number, we provide the {\it mean evaluation curves along training trajectories} to demonstrate the ranking, as an even more robust evidence. These results further confirm the conclusions we draw in Section~\ref{subsec:vision_ablation}. \subsection{Disentangling the effects of region proposals and model weights on the SoTA model} In Table~\ref{tab:regionmodel_ablation}, we alternate the combination of region proposals and model weights, and evaluate them on VQA. As we can see, the improvement of using boxes from the R101-C4 model~\cite{anderson2018bottom} to extract features from our X152-C4 model is much bigger than that of using boxes from our X152-C4 model to extract features from the R101-C4 model~\cite{anderson2018bottom}, indicating pre-trained model weights are more important than regions. Inspired by this analysis, we propose the class-agnostic NMS for region selection in the box head of the OD model, which does not sacrifice any VQA performance but greatly improves the model's inference speed. This analysis also suggests that large-scale OD pre-training should improve performance for grid-feature based VL models, as supported by more results in Appendix~\ref{appsec:gridfeature}. In Table~\ref{tab:regionmodel_ablation}, We also report VQA results with COCO groundtruth object regions (GT-Obj, 80 classes) and object-stuff regions (GT-Obj\&Stuff, 171 classes). For VQA task, COCO GT boxes are much worse than proposals from VG trained models. This shows the difference between typical OD tasks and OD in VL: OD in VL requires much richer visual semantics to align with the rich semantics in the language modality. This further echoes with our claim that an image understanding module trained with rich semantics is crucial for VL tasks. \begin{table}[ht] \begin{center} {\begin{tabular}{ c|cccc } \backslashbox{model}{region} & GT-Obj & GT-Obj\&Stuff & \shortstack{Anderson \\ et al. [2]} & VinVL (ours) \\ \hline \shortstack{Anderson \\ et al. [2]} & 63.81 {$\pm$0.94} & 66.68 {$\pm$0.16} & 68.52 {$\pm$0.11} & 69.05 {$\pm$0.06} \\ VinVL (ours) & 65.60 {$\pm$0.21} & 68.13 {$\pm$0.26} & 70.25 {$\pm$0.05} & 71.34 {$\pm$0.17} \\ \end{tabular}} \end{center} \vspace{-4mm} \caption{Ablation of region and model on VQA.} \label{tab:regionmodel_ablation} \vspace{-4mm} \end{table} \section{More on FPN and Comparison of C4 and FPN} \label{app:c4vsfpn} \subsection{Two reasons why FPN performs worse than C4 on VL tasks.} \begin{table*}[t!] \begin{center} \resizebox{\linewidth}{!}{ \begin{tabular}{ c|cccccc } & \shortstack{no image feature \\ {\small $\boldsymbol{w}$}} & \shortstack{R50-C4 {\small w/ box head} \\ {\small randomly initialized}} & R50-FPN & R50-C4 & 4Sets$\rightarrow$ R50-FPN & 4Sets$\rightarrow$R50-C4 \\ \hline VG-trained & -- & 67.6 \small{$\pm 0.13$} & 67.6\small{$\pm 0.30$} & 68.0\small{$\pm 0.16$} & 68.3\small{$\pm 0.11$} & 68.2\small{$\pm 0.05$} \\ Initial & 55.5\small{$\pm 0.50$} & 61.8 \small{$\pm 0.47$} & 57.6\small{$\pm 0.16$} & 64.8\small{$\pm 0.44$} & 66.1\small{$\pm 0.23$} & 66.8\small{$\pm 0.21$} \\ \end{tabular} } \end{center} \caption{C4 vs FPN architecture on VQA. Boxes used to extract features $\boldsymbol{v}$ and tags $\qv$ used in $\mathbf{VL}$ model are the same with those used in \textsc{Oscar}~\cite{li2020oscar}. Row ``Initial'' means using the initialization model without VG training for feature extraction.} \label{tab:c4vsfpn} \end{table*} Our experimental results confirm the conclusion of \cite{jiang2020defense} that the FPN model does not provide better region features for VL tasks than the C4 model (Columns ``R50C4'' vs. ``R50FPN'' in Table~\ref{tab:c4vsfpn}). Our analysis reveals two reasons. First of all, all layers involved in feature extraction in the C4 model have been pre-trained using ImageNet while the MLP head of FPN does not. It turns out that the VG dataset is still small to train a good visual features for VL tasks and using ImageNet-pre-trained weights is beneficial. This can be verified by two experiments: (1) When the R50-C4 model is trained on VG with its box head randomly initialized (VG-trained - R50C4 w/ box head randomly initialized), the C4 model's performance is the same as FPN; and (2) C4 and FPN achieve the same performance after vision pre-training on 4 datasets (68.3 vs. 68.2). The second reason is due the network architecture (CNN vs. MLP) of the box head in the OD model. The convolutional head in C4 has a better inductive bias in encoding visual information than the MLP head in FPN. This can be verified by the fact that when vision features from randomly initialized models are used (Row ``Initial'' in Table~\ref{tab:c4vsfpn}), R50-C4 performs much better than R50-FPN, indicating that the initial C4 features encode much more useful visual information than the inital FPN features. The ``random'' C4 features nearly match the feature from ImageNet pre-trained model (Row ``Initial'' Column ``R50C4''), while ``random'' FPN features are close to the performance without visual features as input (Row ``Initial'' Column ``no image feature $\boldsymbol{w}$''). \subsection{Effect of pooling methods in FPN on VQA performance.} Different from C4 models that extract region features from a single scale (the end of C4 block), FPN models extract region features from multiple scales adaptively based on the area of the region. Therefore, there is some in-homogeneity in FPN's region features since they may come from different scales. In Figure~\ref{fig:fpn_feature_pooltype_seed42}, we show that this is not the cause of FPN's worse performance than C4 on the VQA task. More specifically, we experiment with 4 pooling methods for FPN architecture. (1) adapt: the original FPN's pooling method that extract features adaptively from different scales; (2) max: extract features from all scales and then do a max-pool; (3) avg: extract features from all scales and then do an average-pool; (4) concat: extract features from all scales and then concatenate them together. We also train multiple FPN models on VG with these pooling methods, with or without pre-training on the Objects365 dataset. We experiment on all possible combinations (in total $8 \times 4$) of 8 vision models and 4 pooling methods on the VQA task. When there is a parameter dimension mis-match, e.g., non-concat FPN models but use concat pooling methods in VQA and vice versa, we specify those parameter randomly with PyTorch's default initialization method. The results in Figure~\ref{fig:fpn_feature_pooltype_seed42} shows that (1) there is no obvious difference in different pooling methods, with the default ``adapt'' and the ``concat'' methods perform slightly better than ``max'' and ``avg''; (2) (without surprise) the performance is significantly worse when there is a parameter dimension mismatch between vision models and VL task feature extraction methods, i.e., non-concat FPN models but use concat pooling methods in VQA and vice versa. These results show that the pooling method (no matter in vision model training or in VL task feature extraction) is not the root cause of FPN's worse performance than C4 on the VQA task. \begin{figure*}[t!] \centering \includegraphics[width=0.49\textwidth]{vinvl_figs/fpn_feature_pooltype_seed42.png} \includegraphics[width=0.49\textwidth]{vinvl_figs/fpn_feature_pooltype_seed88.png} \caption{Pooling methods in FPN feature extraction are not the root cause of FPN's worse performance than C4. X-axis: the pooling method when extracting features for VL tasks; Y-axis: the pooling method (vision model) when pre-training the visual feature extraction model. All experiments are using regions from the Bottum-up Top-down model~\cite{anderson2018bottom}. Each combination is experimented twice with two random seeds, i.e. seed=42 on the left and seed=88 on the right. The results from two random seeds are consistent.} \label{fig:fpn_feature_pooltype_seed42} \end{figure*} \begin{figure*}[t!] \centering \includegraphics[width=0.49\textwidth]{vinvl_figs/4sets_cocostuff2.PNG} \includegraphics[width=0.49\textwidth]{vinvl_figs/4sets_objects3652.PNG} \\ \includegraphics[width=0.49\textwidth]{vinvl_figs/4sets_oi2.PNG} \includegraphics[width=0.49\textwidth]{vinvl_figs/4sets_vg2.PNG} \caption{Checkpoints' $mAP^{50}$ on 4 validation sets: COCO with stuff (top left), Objects365 (top right), OpenImages (bottom left) and Visual Genome (1594 object classes, bottom right). For R50 models, the R50-FPN model is slightly better than C4 on COCO and Objects365 but slightly worse than C4 on Visual Genome. For R152 models, the R152-FPN model is consistently worse than the R152-C4 model on all 4 different datasets.} \label{fig:4setsmap_fpnvsc4} \end{figure*} \begin{table*}[t!] \begin{center} \begin{threeparttable} \begin{tabular}{ c|cccc } \toprule & \shortstack{ImageNet-5k \\ {\cite{wu2019detectron2}}} & 4Sets & VG with Attr & 4Sets$\rightarrow$VG \\ \hline grid feature (273) & 68.3\small{$\pm 0.29$} & 65.2\small{$\pm 2.47$} & 67.5\small{$\pm 0.20$} & 69.4\tnote{*} \\ region feature (50) & 67.7\small{$\pm 0.16$} & 68.5\small{$\pm 0.13$} & 69.8\small{$\pm 0.23$} & 70.6\small{$\pm 0.13$} \\ \bottomrule \end{tabular} \begin{tablenotes} \item[*] The other run failed and thus there is no std for this experiment. \end{tablenotes} \end{threeparttable} \end{center} \caption{Ablation study of X152 models on VQA. Vision models in the last three columns are trained with initialization from the ImageNet-5k checkpoint in the first column. All the region features are extracted with boxes proposed by our best X152-C4 model (pre-trained on 4Sets and fine-tuned on VG). By comparing the first column and the last column, we see that our proposed vision pre-training (first on 4 sets and then on VG with attributes) improves performance for both the grid-feature based model and the region-feature based model. Since the X152 backbone is much larger than the R50 backbone in Figure~\ref{fig:vocab_overall}, the larger model can make better use of the large pre-training datasets and thus have more significant improvements.} \label{tab:X152C4_ablation} \end{table*} \subsection{Large-scale object-detection pre-training of C4 and FPN models} In this paper, we have trained R50-C4, R50-FPN, R152-C4 and R152-FPN models on the merged object detection datasets described in Table~\ref{tab:vision_pretrain_corpus}. In Figure~\ref{fig:4setsmap_fpnvsc4}, we report the $mAP^{50}$ of checkpoints from these 4 experiments on 4 validation sets: COCO with stuff (top left), Objects365 (top right), OpenImages (bottom left) and Visual Genome (1594 object classes, bottom right). For R50 models, the R50-FPN model is slightly better than C4 on COCO and Objects365 but slightly worse than C4 on Visual Genome. For R152 models, the R152-FPN model is consistently worse than the R152-C4 model on all 4 different datasets. Therefore, we finally use the R152-C4 model for downstream vision-language tasks. \section{Grid feature} \label{appsec:gridfeature} In Table~\ref{tab:X152C4_ablation}, we train grid-feature based and region-feature based X152 models for VQA, with the vision models pre-trained on different vision datasets, i.e., ``ImageNet-5k'' from \cite{wu2019detectron2}, our 4-dataset merged OD dataset~\ref{tab:vision_pretrain_corpus} (4Sets), our VG dataset with 1594 object classes and 524 attribute classes (VG with Attr), and first 4Sets and then VG (4Sets$\rightarrow$VG). Vision models in the last three cases are trained with initialization from the same ImageNet-5k checkpoint from \cite{wu2019detectron2}. All the region features are extracted with boxes proposed by our best X152-C4 model (pre-trained on 4Sets and fine-tuned on VG). By comparing ``ImageNet-5k'' and ``4Sets$\rightarrow$VG'', we see that our proposed vision pre-training improves performance for both the grid-feature based model and the region-feature based model. Since the X152 backbone is much larger than the R50 backbone in Figure~\ref{fig:vocab_overall}, the larger model makes better use of the large pre-training datasets and thus has more significant improvements. It is interesting to see that for grid-feature based models, the ``ImageNet-5k'' model performs better than the ``4Sets'' model and the ``VG with Attr'', while it is not the case for region-feature based models. This may indicate that how the vision model is trained (grid-feature wise or region-feature wise) may have big impact on the downstream VL tasks. \begin{table*}[ht!] \begin{center} \begin{tabular}{ l|cc|cc|cc } \multirow{2}{*}{Model} & \multicolumn{2}{c|}{R50-C4} & \multicolumn{2}{c|}{R101-C4~\cite{anderson2018bottom}} & \multicolumn{2}{c}{X152-C4} \\ & $\mathbf{Vision}$ & $\mathbf{VL}$ & $\mathbf{Vision}$ & $\mathbf{VL}$ & $\mathbf{Vision}$ & $\mathbf{VL}$ \\ \hline Grid-50 & 0.059$\pm$\tiny{0.018} & 0.029$\pm$\tiny{0.002} & 0.083$\pm$\tiny{0.025} & 0.030$\pm$\tiny{0.003} & 0.355$\pm$\tiny{0.022} & 0.031$\pm$\tiny{0.003} \\ Grid-273 & 0.056$\pm$\tiny{0.005} & 0.027$\pm$\tiny{0.002} & 0.082$\pm$\tiny{0.022} & 0.034$\pm$\tiny{0.001} & 0.344$\pm$\tiny{0.036} & 0.037$\pm$\tiny{0.004} \\ Object & 0.373$\pm$\tiny{0.040} & 0.031$\pm$\tiny{0.005} & 0.663$\pm$\tiny{0.042} & 0.034$\pm$\tiny{0.003} & 0.687$\pm$\tiny{0.064} & 0.036$\pm$\tiny{0.005} \\ Object-eff & 0.165$\pm$\tiny{0.029} & 0.029$\pm$\tiny{0.002} & 0.442$\pm$\tiny{0.119} & 0.036$\pm$\tiny{0.003} & 0.475$\pm$\tiny{0.049} & 0.037$\pm$\tiny{0.005} \\ \midrule Grid-50 (cpu) & 1.943$\pm$\tiny{0.244} & 0.480$\pm$\tiny{0.042} & 4.050$\pm$\tiny{0.398} & 0.469$\pm$\tiny{0.046} & 17.765$\pm$\tiny{1.693} & 0.501$\pm$\tiny{0.047} \\ Grid-273 (cpu) & 2.032$\pm$\tiny{0.230} & 1.368$\pm$\tiny{0.056} & 4.052$\pm$\tiny{0.372} & 1.283$\pm$\tiny{0.067} & 17.664$\pm$\tiny{1.713} & 1.326$\pm$\tiny{0.053} \\ Object (cpu) & 11.808$\pm$\tiny{1.322} & 0.500$\pm$\tiny{0.045} & 31.863$\pm$\tiny{7.932} & 0.585$\pm$\tiny{0.044} & 29.641$\pm$\tiny{3.097} & 0.565$\pm$\tiny{0.044} \\ Object-eff (cpu) & 11.729$\pm$\tiny{1.280} & 0.510$\pm$\tiny{0.044} & 31.791$\pm$\tiny{8.027} & 0.587$\pm$\tiny{0.043} & 29.687$\pm$\tiny{3.011} & 0.574$\pm$\tiny{0.036} \\ \end{tabular} \end{center} \caption{Time cost of end-to-end inference on VQA. All cross-modal models are BERT-Base. On the SOTA number obtained with X152-C4 region features, the performance {\it keeps the same} when changing to the efficient way to extract the feature while the efficiency greatly improves on GPU. The efficient version does not lead to time saving on CPU, because nearly all inference time is taken by the backbone and C4 head and the time from NMS operations is nearly ignorable on CPU.} \label{tab:model_efficiency_cpu} \end{table*} \section{End-to-end inference efficiency} \label{app:efficiency} We report the end-to-end inference time of different VQA models on a Titan-X GPU and a Xeon E5 CPU in Table~\ref{tab:model_efficiency_cpu}. For CPU evaluation, we force that the inference use only one CPU thread. The input image size is $800\times 1333$, and we run the inference with batch size 1 (one image-question pair per batch). We can see that (1) vision models dominate the inference time, especially for large models; (2) models based on grid-feature are faster than those based on region feature; (3) with our proposed fast inference trick, region-feature models are greatly sped up and their inference time can be brought to within 3 times of that of grid-feature models on GPU. We find that on CPU with a single thread, our class-agnostic trick does not lead to time saving, because nearly all inference time is taken by the backbone and C4 head and the time from NMS operations is nearly ignorable on CPU.
{'timestamp': '2021-03-11T02:07:29', 'yymm': '2101', 'arxiv_id': '2101.00529', 'language': 'en', 'url': 'https://arxiv.org/abs/2101.00529'}
arxiv
\section{Introduction} Climate change is expected to drive increases in the intensity of tropical cyclones \citep{knutson_tropical_2019} and increase the occurrence of ‘blue sky’ flooding \citep{moftakhari_increased_2015}. Despite these hazards, coastal populations \citep{neumann_future_2015}, and investments in the coastal built environment \citep{lazarus_building_2018} are likely to grow. Understanding the impact of extreme storms and climate change on coastal communities requires pervasive environmental sensing. Beyond the collection of environmental data streams such as river gages, wave buoys, and tidal stations, internet connected devices such as mobile phones allow for the creation of real-time crowd-sourced information during extreme events. A key area of research is understanding how to use streaming social media information during extreme events --- to detect disasters, provide situation awareness, understand the range of impacts, and guide disaster relief and rescue efforts \citep[e.g.][]{de_longueville_omg_2009, sakaki_earthquake_2010,tyshchuk_social_2012,middleton_real-time_2014,muralidharan_hope_2011,imran2020rapid, niles2019social}. Twitter -- with approximately 600 million tweet posts every day \citep{livestats_internet_2014} and programmatic access to messages -- has become one of the most popular social media platforms, and a common data source for research on extreme events \citep[e.g.][]{de_bruijn_global_2019,kryvasheyeu2016rapid, pourebrahim_understanding_2019}. In addition to text, a subset of messages shared across Twitter contain images captured by its users (20 - 25\% of messages contain images / videos \citep{leetaru_visualizing_2019}). A key hurdle for studying these aspects of extreme events with Twitter is the data are both large and considerably noisier than curated sources such as dedicated streams of information (e.g., dedicated environmental sensors). Posts on Twitter during disasters might also be irrelevant, or provide mis- or dis- information \citep[e.g.,][]{gupta2013faking,laylavi_event_2017}, highlighting the importance of filtering and subsetting social media data when used during disaster events. Therefore a key step in all work with Twitter data is to filter and subset the data stream. Previous work has addressed filtering and subsetting Twitter data during hazards and other extreme events. Techniques have included relying on specific hashtags \citep[e.g.,][]{murzintcev2017disaster}, semantic filtering \citep{abel_semantics_2012}, keyword-based filtering \citep{laylavi_event_2017}, as well as natural language processing (NLP) and text classification that use machine learning algorithms \citep{laylavi_event_2017,liu_assessing_2019}. Classifiers such as support vector machine and Naive Bayes classifiers have been used to differentiate between real-world event messages and non-event messages \cite{becker_beyond_2011}, and to extract valuable ``information nuggets'' from Twitter text messages\cite{imran_extracting_2013}. The tweets’ length and textual features can also used to filter emergency-related tweets \cite{imran_extracting_2013}. Tweets have been scored against classes of event-specific words (term-classes) to aid in filtering \cite{laylavi_event_2017}. Previous work have filtered and subset tweets using expert-defined features of the tweet \citep{zahra2020automatic}. Images have also been used to subset tweets based on the presence/absence of visible damage \citep{ilyas2014microfilters}. Filtering can also be understood by the extensive work on determining the relevance of tweets for a given event — see recent work and reviews \citep{kaufhold2020rapid, sit2019identifying,imran2020using}. In the context of this paper, we view filtering as any generic process that subsets tweets, even beyond the binary class division of relevance. A few studies have identified the significance of adding spatial features and external sources for a better assessment of tweets’ relevance for disaster events. For example, \cite{spinsanti_automated_2013} enriched their model with geographic data to identify relevant information. Previous work has used spatio-temporal data to determine tweet relevance \cite{liu_assessing_2019}, or linked geolocated tweets to other environmental data streams \citep[e.g.,][]{de2015geographic, de2020improving}. As observed from prior work, capturing situational awareness information from social media data involves a hierarchical filtering approach \citep{landwehr2014social}. Specifically, researchers/interested stakeholders filter down the data from the noisy social media data stream to fit their specific use cases (such as, type of image - destruction, damage, flooding; type of text - damage, donation, resource request/offer; spread of information, etc). A key component in such an approach is the quality of baseline data capture. Towards this our study proposes a novel approach towards quality gating the data capture from the social media data streams using developed threshold measures. This baseline filtering methodology that can be used to find relevant tweets and refining the data capture routines. Specifically, the goal of our study is to explore a multi-modal filtering approach which can be used to provide situational awareness from social media data during disaster events. We develop an initial prototype using tweets from Florida, USA during Hurricane Irma. The filtering routine allows users to adjust four separate models to filter Twitter messages: a geospatial model, an image model, a user model, and a text model. All four models are tested separately, and can be operated independently or in tandem. This is a design feature as we envision the sorting and filtering thresholds will be different for different users, for different events, and for different locations. We work through each model and discuss the combined model in the following sections. \section{Methodology} \subsection{Hurricane Irma} Hurricane Irma (Figure~\ref{fig:irma}) was the first category 5 hurricane in the 2017 Atlantic hurricane season \citep{cangialosi_hurricane_2018}. Hurricane Irma formed on August 31st, 2017, impacting many islands of the Caribbean, and finally dissipating over the continental United States \citep{cangialosi_hurricane_2018}. Here we focus on the Twitter record of Irma specifically in Florida, USA. Irma made landfall in Florida Keys on 09/10/2017 as a category 4 hurricane and dissipated shortly after 09/13/2017. 134 fatalities were recorded as a result of the hurricane, with an estimated loss of \$64.76 billion \citep{nguyen_forecasting_2019}, making it one of the costliest hurricanes in the history of the United States \citep{united_states_national_hurricane_center_costliest_2018}. \begin{figure}[ht!] \centering \includegraphics[width=\textwidth]{./figures/Irma_2.pdf} \caption{The path of Hurricane Irma in September 2017 (orange line), the extent of tropical storm force winds (pink outline), and the location for all 784K geolocated tweets used as the basis for this study (black dots).} \label{fig:irma} \end{figure} \subsection{Data collection and preprocessing} \subsubsection{Twitter data} We used the Twitter Application Programming Interface (API) to collect tweets located in the geospatial bounding box that captured the state boundary of Florida. Tweets were recorded for the period of 09/01/2017 to 10/10/2017, and resulted in the collection of 784K tweets from 96K users during the time period. Our work is focused on 72 hours (09/10/2017 - 09/12/2017) when Hurricane Irma was near or over Florida. Therefore we subset the data and use 54,383 tweets from 16,598 users during this 72hr window. Figure 1 highlights the locations of the Twitter messages, along with the path of Hurricane Irma, and the extent of tropical Storm force winds. Each tweet from the Twitter API has 31 distinct metadata attributes \citep{twitter_introduction_2019} that can conceptually be grouped into three categories: 1) Spatio-temporal (time of creation and geolocation [latitude, longitude]), 2) Tweet content (tweet text, weblinks, hashtags, and images), and 3) Tweet source (account age, friends count, followers count, statuses count, and if verified). Geolocated tweets can have one of two types of location data — Places or Coordinates. Coordinates are exact locations with latitude and longitude attributes, while Places are locations within a Bounding Box or a Polygon designating a geospatial area in which the tweet is recorded \citep{twitter_geo_2019}. For tweets with Places attributes, we transform the area representation to a single point by selecting the centroid of the Polygon as the location represented by the tweet. Within our study 42.58\% (23,157) of the tweets had Coordinate locations and 57.42\% (31,226) had Place locations. \subsubsection{Geospatial data} \label{sec:geomodel} We collected meteorological sensor data, wind speed (in mph) and precipitation (in inches), for each county in Florida for the 72 hours (09/10/2017 - 09/12/2017). The hourly wind speeds was collected from the NOAA National Centers for Environmental Information (NCEI). Hourly precipitation values were obtained from the United States Geological Survey’s Geo Data Portal (USGS GDP) of the United States Stage IV Quantitative Precipitation Archive. Precipitation values from the closest weather station were used due to difficulty in obtaining reliable data for all weather stations. In addition to meteorological forcing, we collected data consisted of location of the hurricane’s eye, category of the hurricane, pressure and wind speed (NOAA National Hurricane Center). This data were discretized into hourly windows for the 72 hours. \subsubsection{Data pre-processing} We aligned the 72hrs of Twitter data and the corresponding 72hrs of meteorological forcing data. Wind and precipitation values at the geolocation of a tweet was calculated using Inverse Distance Weighting (IDW). IDW is an interpolation method that calculates a value at a certain point using values of other known points: \begin{equation} W_p = \frac{\sum_{i=1}^{n}{\frac{W_i}{D_{i}^{k}}}}{\sum_{i=1}^{n}{\frac{1}{D_{i}^{k}}}} \end{equation}{} where, $W_p$ is the wind speed to be interpolated at point $p$, $W_i$ is the wind speed at point $i$, $D_i$ is the distance between point $p$ and $i$, and $k$ is a power function that reduces the effect of distant points as it goes up. IDW has been widely used to interpolate climatic data \citep{tomczak1998spatial}. The method has demonstrated accurate results when compared to other interpolation methods especially in regions characterized by strong local variations \citep{yang2015spatial}. IDW, for example, assumes that any measurement taken at a fixed location (e.g., weather station) has local influence on surrounding area, and the influence decreases with increasing distance. Within our study we chose IDW as our interpolation method as meteorological factors in a hurricane are highly influenced by local variations. Furthermore, each tweet was also annotated with the corresponding temporal hurricane conditions data. Specifically, for each hourly time window, a tweet was associated with its distance from the eye of the hurricane and its conditions (i.e., pressure, max wind speed) during that window. \subsection{Multimodal scoring of tweet relevance} Our goal is to develop a single model for tweet relevance based on four sub models — 1) the relevance of the tweet based on \textit{geospatial} attributes (i.e., the Tweets location relative to the forcing conditions of the hurricane, 2) the relevance of tweet \textit{images} (when media is included in the tweet), 3) a score for the reliability of the \textit{user} (i.e., network attributes to predict if a user is ‘verified’ by Twitter), and 4) the relevance of the tweet \textit{text}. The methods used to construct of each of these models, and the results of models (submodels and the combined model) in are discussed in Section 3. \subsubsection{Geospatial model} Our goal in designing a geospatial relevance model was to search for thresholds in forcing conditions where tweets were likely to be related to Hurricane Irma, as opposed to background social media discussions. Specifically, we posit that the messages which are in close geospatial and temporal proximity to the disaster event will have more relevant situational awareness information than those which are not. Furthermore, such an approach can be used in real-time during the occurrence of an event where meteorological data can provide key information about disaster's impact at different locations. There are many meteorological conditions that can be used as proxies for extreme disaster conditions. We focus here on searching for modeling functions relating wind speed ($w$), precipitation ($p$), and distance from hurricane eye ($d$). We acknowledge that other factors could be used in addition to these three attributes. For example, rainfall during a given interval could be quantified in several ways, such as mean rainfall rate, max rainfall rate, total rainfall in a given interval. Similarly Wind metrics could include mean wind speed, max wind speed, metrics based on wind gusts, etc.. For locations nearby the coast, metrics could include tide elevations, or storm surge elevations, and locations near streams could include stage and discharge data. Ultimately we chose Wind speed, precipitation and distance from the hurricane eye as these factors are available everywhere (vs metrics that are only applicable along streams and rivers) and because they are commonly available and collected by even basic meteorological stations. Nine different functions, --- 1) $\frac{wind\ *\ rain}{distance}$, 2) $\frac{rain}{distance}$, 3) $\frac{wind}{distance}$, 4) $\frac{wind\ *\ rain}{\sqrt[]{distance}}$, 5) $\frac{rain}{\sqrt[]{distance}}$, 6) $\frac{wind}{\sqrt[]{distance}}$, 7) $\frac{wind\ *\ rain}{\sqrt[3]{distance}}$, 8) $\frac{rain}{\sqrt[3]{distance}}$, and 9) $\frac{wind}{\sqrt[3]{distance}}$, combining the geospatial attributes were compared to identify the best suited model towards creating a relevance score for the tweets. In each of the models, wind speed and precipitation acted as numerators (individually or combined), where as distance was used as a denominator — this was a heuristic method, as tweets are likely more relevant if forcing conditions are more severe (Higher wind, more precipitation, closer distance to hurricane) Approximately 19,000 tweets from the Irma dataset were hand labeled by human coders as “Irma related” or “non-Irma related” based on the tweet content. The performance of each geospatial function was evaluated by comparing the ratio of Irma related tweets to total number of tweets during each time window. The ratios obtained from each formula was normalised using three different approaches - Min-max scaling, Log ($log_{10}()$), and Box-Cox transformations. Ranking of Shapiro-Wilk (SW) test statistics was used to assess normality. In addition, multiple observed statistics of mean, standard deviations, and percentage of values within 1, 2, and 3 standard deviations from the mean were calculated to evaluate normality. The goal of this normalization procedure was to establish a comparative scoring range for each of the models. The scores enable development of a combined overall model for filtering tweets relevant to the hurricane (as described in Section~\ref{sec:overall}. Apart from the ratio, we also evaluated the F1-score ($F1 = 2\frac{precision*recall}{precision + recall}$) for the model, where $precision = \frac{TP}{TP + FP}$, $recall = \frac{TP}{TP + FN}$, and $TP$, $FP$, $TN$, and $FN$ represent the number of true positives, false positives, true negatives, and false negatives, respectively. \subsubsection{Image model} Supervised machine learning models were used to develop automated image classification of images in the Twitter dataset. The goal of this model is two fold: 1) to develop, a binary classifier capable of distinguishing hurricane-related images from the non-related ones, and 2) to then develop a multi-label annotator capable of classifying the hurricane-related images into one or more of three incident categories --- 1) Flood, 2) Wind, and 3) Destruction. A key hurdle in the approach was the lack of available labeled training data for supervised classification. We developed a web platform for image labeling for annotation by human coders. The platform took unlabeled images, and displayed them on a browser for human coders to annotate. Within the browser, the coder was asked the question of --- \textit{Does this image have any of the following --- 1) Flooding, 2) Windy, and 3) Destruction?} An image is considered ``Flooding'' if there is water accumulation in an area of the image. An image is considered ``Windy'' if there are visual elements in the picture which show tree branches are moving in a direction or some objects that are flying or heavy rain visible in the image. An image is considered to have ``Destruction'' if there is damage to property, vehicles, roads, or permanent structures. An image can be in one or more of the previous classes. If an image has one of the codified classes, it is labelled as Irma \textit{related} and if it does not have any of them the image is labelled as \textit{not related}. For the dataset, approximately 7,000 images were labeled by 3 human coders/raters where the data was divided equally between them. Following codification resulting dataset had the following distribution --- Related: 817 / Not-Related: 6081 images, and Wind: 120 images; Flooding: 266 images; Destruction: 571 images. We also evaluated the inter-rater reliability using Light's Kappa \citep{light1971measures} for 100 sampled images (with balanced distribution of related and not-related classes) that were labeled by all three coders. Agreement between all three coders for related versus not-related was at $0.77$, and across tags Flooding - $0.88$; Windy $0.27$; and Destruction $0.78$. This shows significant agreement among the coders on the labeling \citep{mchugh2012interrater} other than the Windy tag (poor/chance agreement). This annotated dataset was used to train deep learning models based on convolutional neural network (CNN) architectures. Convolutional networks have been widely used in large-scale image and video recognition \citep{simonyan_very_2014}. CNN architecture consists of an input layer, an output layer, and several hidden layers in between. A hidden layer can be a convolutional layer, a pooling layer (e.g. max, min, or average), a fully connected layer, a normalization layer, or a concatenation layer. Within our approach, we evaluated three modern CNN architectures --- 1)VGGNet, 2)ResNet, and 3)Inception-v3, and compared the performance of each model to its counterparts. In VGGNet \citep{simonyan_very_2014}, the image is passed through a stack of CNN layers, where filters with a very small receptive field is used. Spatial pooling is done by five max-pooling layers, which is followed by convolution layers. The limitation of VGGNet is its large number of parameters, which makes it challenging to handle. Residual Neural Network (ResNet) \citep{he_deep_2015} was developed with fewer filters and in turn has lower complexity than VGGNet. While the baseline architecture of ResNet was mainly inspired by VGGNet, a shortcut connection was added to each pair of filters in the model. In comparison, Inception-v3 \citep{szegedy_rethinking_2015} uses convolutional and pooling layers which are concatenated to create a time/memory efficient architecture. After the last concatenation, a dropout layer is used to drop some features to prevent overfitting before proceeding with final result. The architecture is quite versatile, where it can be used with both low-resolution images and high-resolution images, and can distinguish any size of a pattern, from a small detail to the whole image. This makes it useful in our application as the quality and type of image can vary widely due to disparate smart devices used by the Twitter population. The pre-trained Inception-V3 is trained on the Imagenet \citep{krizhevsky_imagenet_2012} dataset which consists of hundreds of thousands of images in over one thousand categories. The weights of this model are used as a starting point for training and fine tuned using our sample images. The approach takes advantage of transfer learning \citep{oquab_learning_2014}, where the classifier is able to initially learn features of physical objects in a wide variety of scenarios and then trained on specific observations within our data. This enables a more accurate and generalizable model. Data augmentation methods were used to expand the number of training samples and therefore improve model accuracy. For example, additional training images are generated by rotating and scaling of the original images. This was done to balance the number of images of Irma related to the un-related ones. The resulting dataset consisted of approximately 6,000 images in each class for the binary classifier, and approximately 2,000 images in each class for the annotator model. The models were trained and testing using a 70-30 split on the dataset. For each model, performance scores (precision, recall, and F1) was recorded. Probability scores for each tweet image were then recorded for every class, which was further normalized using log-transform and re-scaled using min-max scaling to be used in the overall model. \subsubsection{User model} It is essential to quantify the authenticity of user accounts which have posted messages and images during a disaster event. For the purpose, our goal was to develop a scoring model which can provide continuous probabilistic measures of account authenticity. Manually annotating user reliability in a large dataset such as Twitter is not practical. As we did not have a labeled dataset, our starting point was to consider the user ``Verified'' attribute within the tweets. The ``Verified'' attribute is annotated to user accounts which Twitter defines to be of public interest \citep{twitterverified}. Within our dataset we had 94,445 non-verified users and 1,692 verified users. Since Twitter’s methodology for finding verified accounts is not public, we aim to develop a proxy automated model. The aim here is to create a model which can help identify users who are also likely to be accounts of public interest and authentic, but remain unverified. This can be used in conjunction with the Twitter ``Verified'' accounts to provide a comprehensive source of authentic accounts during a disaster event. Specifically, our approach provides the adjust the authenticity thresholds based on the continuous probabilistic scores of the model, which enables collection information from accounts which have not yet been verified by Twitter but have similar properties to that of a ``Verified'' account. The automated model was developed based on supervised machine learning. Specifically, machine learning models \citep{kotsiantis_supervised_2007} were developed for binary classification machine to predict the label user ``Verified'' (true/false) based on the features of tweets content (weblinks, hashtags) and its creator (account age, friends count, followers count, statuses count). Random Forest (RF) \citep{liaw_classication_2002}, Gradient Boosted (GB) \citep{ye_stochastic_2009}, and Logistic Regression (LR) \citep{kleinbaum_logistic_2010} classifiers were used to train and test the model. RF is an ensemble model which consists of multiple decision trees trained on the data and their voting to determine the label class of an observation based on the features. A decision tree has a set of rules, when evaluated on an input, it returns a prediction of a class or a value. RF also returns the ratios of votes for each class it is trained on. A Gradient Boosted (GB) is also an ensemble model which builds decision trees leveraging gradient descent to minimize information loss. Similar to RF, GB also uses weighted majority vote of all of the decision trees for classification. In comparison, Logistic Regression (LR) is a non-parametric model which tries to find the best linear model to describe the relationship between independent variables and a binary outcome for classification. The output of each of the trained binary models is a classifier capable of predicting if a user can be verified or not. The performance of the resulting model was evaluated using a 10-fold cross validation \citep{domingos_few_2012}, with a 70-30 train test split used in each fold. Furthermore, grid search \citep{bergstra_random_2012} was used on the best performing model for hyper-parameter optimization. Grid search takes in a set of values for each hyperparameter (e.g. number of trees in a forest, max depth of a tree, sample splits, max number of leaf nodes, etc.), folds number, and conducts a search using each possible combination of hyperparameters by evaluating them on a scoring metric such as F1-score. The final output of this model is a min-maxed log-transformed value of the probability scores. This was done to reduce the skewness in score distribution needed for the overall model (described later). \subsubsection{Text model} \label{sec:textmodel} The goal of the text model was to delineate tweets with Irma related text from those addressing other topics. While generic search term such as the ``Hurricane Irma'' can provide a starting point, prior research \citep{yarowsky_unsupervised_1995,marco_clustering_2013,arora_linear_2018} in the domain has shown that content organically develops to other words. An automated system trained on a large corpus to recognize context may improve the results, but this suffers from two significant pitfalls. First, training a learner on large bodies of text is costly from the perspective of computational overhead \citep{imran_twitter_2016}. Second, the dynamic nature of discussions during a disaster, especially in a format as compact as Twitter, can alter the most likely interpretation of a word’s meaning, resulting in false positives in the captured tweets \citep{de_boom_semantics-driven_2015}. In order to address the issues we developed a dynamic word embedding model which utilizes online learning to update its learned context. Specifically, we use a neural network based word embedding architecture - Word2Vec \citep{mikolov_efficient_2013,goldberg_word2vec_2014}, which captures the semantic and syntactic relationships between the words present in tweets corpora. In the Word2Vec module, each word is evaluated based upon its placement among other words within a tweet. This target word, combined with its neighboring words before and after its occurrence in a given tweet, is then given to a neural network whose hidden layer weights correspond with the vector representing the target word. Once the vectors for each word are generated, the vectors can be compared based upon their cosine similarity. As two words get closer in similarity, the vectors representing those words will become closer within vector space; the angle internal to the vector will get smaller; and the cosine of this angle will get closer to, but not exceed, 1. As a result, the similarity in context between a word and its neighbors in vector space can be compared numerically by looking at the cosine of the internal angle formed by two word vectors \citep{ozdikis_semantic_2012}. Within our approach, tweets were parsed and grouped into 24-hour segments, with primary testing done on the time period immediately before and after the initial landfall. Prior to training the model, tweets were first cleaned to eliminate punctuation, numbers, and extraneous/stop words. Each tweet temporally isolated and parsed into token words, to create input vectors for training and testing of Word2Vec module. Four different formulas - 1) Cosine Similarity of Tweet Vector Sum (CSTVS) $1 - \frac{\alpha \cdot \sum_{i=1}^k \tau_i}{\lVert \alpha \rVert \lVert \sum_{i=1}^k \tau_i \rVert}$, 2) Dot Product of Search Term Vector and Tweet Vector Sum (DP) $\lVert \alpha \rVert \times \lVert\sum\limits_{i=1}^n \tau_i\rVert \times \cos{\theta}$, 3) Mean Cosine Similarity (MCS) $\frac{1}{n}\sum\limits_{i=1}^n \cos(\theta_{\alpha}^{\tau_i})$, 4) Sum of Cosine Similarity over Square Root of Token Count (SCSSC) $\frac{1}{\sqrt{n}}\sum\limits_{i=1}^n \cos(\theta_{\alpha}^{\tau_i})$, were employed to score a tweet based upon its component word vectors. CSTVS is a programmatic implementation of the cosine distance formula \citep{salton_extended_1983} allows an efficient calculation of cosine distance. Cosine Similarity can be calculated by subtracting this value from 1. DP treats the sum of the vectors in a tweet as a vector itself ($\sum_{i=1}^k \tau_i$), and calculating the dot product of this interpreted vector and the vector for the search term ($\alpha$) returns a value that is proportional to the cosine similarity. MCS is the mean cosine similarity of the search term to all terms in a tweet, where $n$ is the number of terms in the tweet. SCSSC is similar in function to the MCS, where it reduces the impact of a shorter tweet by dividing by the square root of the count of tokens in a tweet ($n$). All formulas return a scalar score for a tweet - search term similarity match. In order to evaluate the model, the codified data set of 19,000 tweets were used. The codification was done by a single human coder and a sampled set of tweets (100 with balanced distribution) was verified by two additional coders to access the inter-rater reliability. Tweets were labelled to be Irma \textit{related} if matched the following criterion --- 1) \textit{Explicitly contains references to ``Irma'' or ``Hurricane''}; 2) \textit{Contains current meteorological data, such as wind speed, rainfall levels, etc.}; 3) \textit{Refers to weather events such as storm, flood(ing) and rising water, rainfall, tornado, etc.}; 4) \textit{Describes the aftermath of extreme weather: trees down, power out, damage to buildings or construction, etc.}; 5) \textit{contains references to emotional states exacerbated by the weather: worrying about shelter, concerns for safety, pleas for help, etc.}; 6) \textit{Lists availability or absence of necessities: shelter, water, food, power, etc}. A message was labelled \textit{not related} if it met following criterion --- 1) \textit{mentioning a location absent any of the above content}; 2)\textit{Containing an attached picture that may be Irma related, but no additional text}; 3) \textit{Expressing emotions about the state of an event, but its connection to weather is ambiguous, i.e. a sporting event canceled, but no explanation as to why;} 4) \textit{Expressing emotions about a person’s condition, but its connection to weather is ambiguous: for ex: ``I hope \text{@abc123} gets better soon!''.} The resulting dataset had 8,296 tweets related to the Irma and 10,792 tweets not related. The inter-rater reliability of the codified messages using Light's Kappa metric was at $.69$, suggesting significant agreement between coders \cite{light1971measures, mchugh2012interrater}. This dataset was then used to evaluate the aforementioned formulas for different thresholds of the scores by analyzing the ratio of correctly classified tweets by the model. Hyper-parameters of the Word2Vec model were also tuned using the labeled tweets. The parameters selected for testing were context word window sizes from 1 to 10 words on either side of the target word; hidden layer dimensionality in 50D increments from 50D to 500D; minimum word occurrence from 0 to 9; negative sampling from 0 to 9 words. The cross product of the values contained in these ranges were used as the testing set of tuples for the training operations. For each set of parameters, the NN was trained through varying epochs, and the resultant word embeddings used in conjunction with the four scalar formulas to calculate scores for each tweet. The scores for each iteration were min-max scaled for the time delta, and the AU-ROC calculated based upon the thresholds of the scores in relation to the human-coded tweets. \subsection{Overall model} \label{sec:overall} \begin{figure}[ht!] \centering \includegraphics[width=\textwidth]{./figures/Irma_3.pdf} \caption{Overall information flow model. The Metadata Extraction stage develops variables from the raw Twitter data, Filtering stage utilizes the developed 1) Geospatial, 2) User, 3) Image, and 4) Text analysis modules to score tweets, and the Visualization stage is used to observe the at location posted image along with Google Street View} \label{fig:overall_mod} \end{figure} Following the creation of individual models, we combined the results of each into a single overall model (Figure~\ref{fig:overall_mod}) which consists of three distinct stages - 1) Metadata extraction, 2) Filtering, and 3) Visualization of filtered tweets. For the first stage, the input is a tweet as a data-point. The metadata extraction stage mines the relevant attributes (image, geolocation, user, text) needed for the individual models of 1) Geospatial, 2) User, 3) Image, and 4) Text analysis. The results of the individual models are then combined in the second stage of filtering, where the normalized scores (decision score ranging from 0-100) for each models are combined at different thresholds to filter the relevant Twitter messages for Hurricane Irma. Any tweets without images are assigned an $imgScore = 0$, this allows users to view messages which contain images by setting the threshold to be $imgScore > 0$. The flexibility of the approach is in its ability to select different thresholds for respective models. This allows for a more generalizable model where a user can choose different set of thresholds for disparate disaster events. A logical $AND$ operation is used to obtain messages which pass all of the thresholds for each of the individual models. Specifically, a datapoint can only pass the filtering stage if all of its individual model scores are greater than or equal to the thresholds set. The filtered data are then stored in a database (Scored Tweets), where each datapoint can then be viewed on a visualization platform. The visualization platform extracts the location information from each datapoint (Geolocation), which is then cross-referenced with Google Maps API to provide three attributes --- 1) Google Street View \citep{anguelov2010google, rundle2011using}, 2) Physical address, and 3) A 2D top down view of the map at the location. These attributes (Street View - Map) along with the Tweet Data (text of the tweet, date-time, user, image, etc) and Score \& Annotation information ($\mathsf{P}(Related/Not-Related)$ and $\mathsf{P}(Tag)$, where $\mathsf{P}$ is the probability and $Tag \in \{Flooding, Windy, Destruction\}$) is then displayed on a web viewer. This presents an easy to use interface to view and visualize the messages for situational awareness. \section{Results} \subsection{Geospatial} \begin{figure}[ht!] \centering \includegraphics[width=\textwidth]{./figures/fig1.eps} \caption{Precipitation and wind speed in relation to the distance from Hurricane Irma’s eye.} \label{fig:rainwind} \end{figure} \begin{figure}[ht!] \centering \subfigure[Min-Max Normalization Scores.]{ \resizebox*{5.75cm}{!}{\includegraphics{./figures/fig2_1_updated.eps}}} \subfigure[$log_{10}()$ Transformed Scores.]{ \resizebox*{5.75cm}{!}{\includegraphics{./figures/fig2_2_updated.eps}}} \subfigure[Box-Cox Transformed Scores.]{ \resizebox*{5.75cm}{!}{\includegraphics{./figures/fig2_3_updated.eps}}} \caption{Cumulative Distribution Function (CDF) for Min-Max Normalization, Log, and Box-Cox transformed geospatial scores for the nine models. The common legend of all three figures is shown in Figure c.} \label{fig:cdf_plots} \end{figure} Preliminary exploration of the sensor readings for precipitation and wind speed with relative distance from the eye of the hurricane are shown in Figure~\ref{fig:cdf_plots}. Precipitation decreases exponentially farther away from the eye of the hurricane, measuring 5 - 20 inches. Median wind speeds have their peak around 300 miles from the eye of the hurricane. \begin{table}[ht!] \centering \caption{Shapiro-Wilk statistics value for all the models . Top 5 values highlighted.} { \begin{tabular}{cc|l|l} \toprule & \multicolumn{3}{c}{\textbf{Normalization method}} \\ \cmidrule{2-4} \textbf{Model} & $\frac{X-\min(X)}{\max(X)-\min(X)}$ & \textbf{$log_{10}()$} & $\gamma()$ \\ \midrule $\frac{wind\ *\ rain}{distance}$ & $0.07$ & $\boldsymbol{0.99}$ & $0.99$ \\[0.75ex] \hline $\frac{rain}{distance}$ & $0.06$ & $0.92$ & $0.93$ \\[0.75ex] \hline $\frac{wind}{distance}$ & $0.13$ & $0.95$ & $0.97$ \\[0.75ex] \hline $\frac{wind\ *\ rain}{\sqrt[]{distance}}$ & $0.53$ & $\boldsymbol{0.98}$ & $\boldsymbol{0.98}$ \\[0.75ex] \hline $\frac{rain}{\sqrt[]{distance}}$ & $0.51$ & $0.88$ & $0.89$ \\[0.75ex] \hline $\frac{wind}{\sqrt[]{distance}}$ & $0.88$ & $0.88$ & $\boldsymbol{0.98}$ \\[0.75ex] \hline $\frac{wind\ *\ rain}{\sqrt[3]{distance}}$ & $0.65$ & $\boldsymbol{0.98}$& $\boldsymbol{0.98}$ \\[0.75ex] \hline $\frac{rain}{\sqrt[3]{distance}}$ & $0.65$ & $0.85$& $0.86$ \\[0.75ex] \hline $\frac{wind}{\sqrt[3]{distance}}$ & $0.96$ & $0.85$& $\boldsymbol{0.99}$ \\[0.75ex] \bottomrule \end{tabular}} \label{tab:geomodel1} \end{table} Nine different geospatial models were developed and compared for their performance to filter Irma related tweets. Specifically, for each model the results calculated ratio of Irma related tweets, i.e. number of Irma related tweets / total number of tweets, at different thresholds between 0 and 1 (all values were min-maxed for normalization). Irma related tweets were identified by codification of 19,000 messages by human coder (annotation criteria described in Section \ref{sec:textmodel}). Figure 3, compares the cumulative distribution function (CDF) plots between the each of the functions within a subplot. The plots (a, b, c) further compare the results between - a. Min-Max Normalization, b. Log ($\log_{10}()$), and c. Box-Cox ($\gamma()$)) transformation scores. As observed, the results of the Log and Box-Cox transformations show a wider distribution of the ratio in comparison to the Min-Max normalized values, across the different thresholds. The results are also confirmed by the Shapiro-Wilks test (Table~\ref{tab:geomodel2}) where the Log and Box-Cox transformed models have higher scores, suggesting a more normal distribution of the results than the non-transformed ones. Based on the test the top five functions identified were - ($\gamma(\frac{wind}{\sqrt[3]{distance}})$, $\gamma(\frac{wind\ *\ rain}{distance})$, $log_{10}(\frac{wind\ *\ rain}{distance})$, $\gamma(\frac{wind\ *\ rain}{\sqrt[]{distance}})$, and $log_{10}(\frac{wind\ *\ rain}{\sqrt[]{distance}})$. Each of the models were in very close proximity to the scores observed in the test. \begin{figure}[ht!] \centering \subfigure[CDF Scores.]{ \resizebox*{8cm}{!}{\includegraphics{./figures/fig3_updated.eps}}} \subfigure[F1 Scores.]{ \resizebox*{8cm}{!}{\includegraphics{./figures/fig_gis_f1.eps}}} \caption{Cumulative Distribution Function (CDF) and F1-Scores for the top five \textit{geospatial} models.} \label{fig:cdfgeo} \end{figure} Additional analysis was conducted to observe the statistical properties of the top five models. Figure~\ref{fig:cdfgeo} shows the CDF and F1-Scores for each of these functions. Table~\ref{tab:geomodel2}, show the general statistical properties. Out of the five, $log_{10}(\frac{wind\ *\ rain}{\sqrt[]{distance}})$ was chosen as a final model function, based on its mean being the closest to 0.5. \begin{table}[ht!] \centering \caption{General data statistics for top 5 models. $log_{10}(\frac{wind\ *\ rain}{\sqrt{distance}})$ was selected as the normalization model for geospatial analysis as its distribution mean was closest to $0.5$} { \begin{tabular}{cc|c|c|c} \toprule & \multicolumn{4}{c}{\textbf{Data Statistics}} \\ \cmidrule{2-5} \textbf{Model} & Shapiro-Wilks & \multirow{2}{*}{\makecell{Standard \\ Deviation ($\sigma$)}} & \multirow{2}{*}{\makecell{Mean \\ $\mu$}} & \multirow{2}{*}{\makecell{\% of Data within \\ $-1 \leq \sigma \leq 1$}} \\[3ex] \midrule $\gamma(\frac{wind}{\sqrt[3]{distance}})$ & $0.99$ & $0.12$ & $0.28$ & $0.66$ \\[0.75ex] \hline $\gamma(\frac{wind\ *\ rain}{distance})$ & $0.99$ & $0.14$ & $0.38$ & $0.65$ \\[0.75ex] \hline $log_{10}(\frac{wind\ *\ rain}{distance})$ & $0.99$ & $0.14$ & $0.39$ & $0.65$ \\[0.75ex] \hline $\gamma(\frac{wind\ *\ rain}{\sqrt{distance}})$ & $0.98$ & $0.16$ & $0.43$ & $0.64$ \\[0.75ex] \hline $\boldsymbol{log_{10}(\frac{wind\ *\ rain}{\sqrt{distance}})}$ & $\boldsymbol{0.98}$ & $\boldsymbol{0.16}$ & $\boldsymbol{0.46}$ & $\boldsymbol{0.64}$ \\[0.75ex] \hline \end{tabular}} \label{tab:geomodel2} \end{table} \subsection{Image classification} The performance of various image classifiers are shown in Table~\ref{tab:imgmodel}. In the first stage of classification, which uses a binary classifier distinguish hurricane and non-hurricane related images, the Tuned Inception V3 architecture performed the best with an overall F1-score of 0.962. Figure~\ref{fig:binaryauroc}, shows the comparative AU-ROC curves for the different models. Between the classes, the Tuned Inception V3 model also performed well with an F1-score of 0.959 for class 1 (hurricane related) and 0.965 for class 0 (non-hurricane related) images. \begin{figure}[ht!] \centering \includegraphics[width=.6\textwidth]{./figures/fig4.eps} \caption{Area Under - Receiver Operating Characteristics (AU-ROC) Curves for V3, VGG net, ResNet architecture and Tuned Inception V3 models for binary classification of \textit{images} (hurricane related versus non-hurricane related).} \label{fig:binaryauroc} \end{figure} \begin{table}[ht!] \centering \caption{Performance comparison of deep-learning models (Inception-V3, VGGNet, ResNet, and Tuned Inception-V3) for binary classification and multi-label annotation.} { \begin{tabular}{cc|c|c|c|c|c} \toprule \multirow{4}{*}{\textbf{Model}} & \multicolumn{6}{c}{\textbf{Performance Measures}} \\ \cmidrule{2-7} & \multicolumn{3}{|c|}{\textbf{Binary Classifier}} & \multicolumn{3}{c|}{\textbf{Multi-Label Annotator}} \\ \cmidrule{2-7} & \multicolumn{1}{|c}{Precision} & Recall & F1-Score & Precision & Recall & \multicolumn{1}{c|}{F1-Score} \\[0.75ex] \midrule VGGNet & $0.88$ & $0.87$ & $0.88$ & $0.70$ & $0.60$ & $0.64$\\[0.75ex] \hline ResNet & $0.88$ & $0.89$ & $0.89$ & $0.68$ & $0.61$ & $0.64$\\[0.75ex] \hline Inception-V3 & $0.89$ & $0.88$ & $0.88$ & $0.75$ & $0.72$ & $0.73$\\[0.75ex] \hline \multirow{2}{*}{\makecell{\textbf{Tuned} \\\textbf{Inception-V3}}} & \multirow{2}{*}{$\boldsymbol{0.96}$} & \multirow{2}{*}{$\boldsymbol{0.95}$} & \multirow{2}{*}{$\boldsymbol{0.95}$} & \multirow{2}{*}{$\boldsymbol{0.90}$} & \multirow{2}{*}{$\boldsymbol{0.92}$} & \multirow{2}{*}{$\boldsymbol{0.91}$}\\[3.2ex] \hline \end{tabular}} \label{tab:imgmodel} \end{table} \begin{figure}[ht!] \centering \includegraphics[width=.6\textwidth]{./figures/fig5.eps} \caption{Area Under - Receiver Operating Characteristics (AU-ROC) Curves for Tuned Inception V3 model for multi-label annotation for \textit{images} - 1) 'Flood', 2) 'Wind', and 3) 'Destruction'.} \label{fig:multiauroc} \end{figure} The hurricane related images were then fed through a second round of classification trained on multi-label annotation of - 1) flood, 2) wind, and 3) destruction. Table~\ref{tab:imgmodel} also compares the results of the analysis, where the Tuned Inception V3 architecture outperformed the other models, with an average F1-score of 0.896. Within the classes, the F1-scores were well distributed with class 1) as 0.821, 2) as 0.888, and 3) 0.941. Figure~\ref{fig:multiauroc} shows the AU-ROC curves for the different annotations performed on the images by the Tuned Inception V3 architecture. Analyzing the cutoff thresholds of the probability scores for the Tuned Inception V3 model, shows a distribution with a mean of 0.63, a median of 0.75, and a standard deviation of 35.07. The values show a wide distribution of probability scores, which is useful in having a wider range in the cutoff thresholds used for filtering the images. \subsection{User} \begin{figure}[ht!] \centering \includegraphics[width=.6\textwidth]{./figures/fig6.eps} \caption{AU-ROC Curves for Random Forest, Gradient Boosted, and Logistic Regression Classifiers in predicting Verified \textit{users}.} \label{fig:userauroc} \end{figure} The F1-score of the Random Forest (RF), Gradient Boosted (GB), and Logistic Regression (LR) models of the models trained on predicting user verification were recorded at 0.97, 0.92, and 0.88 respectively. Figure~\ref{fig:userauroc} shows the comparative AU-ROC scores of the different models, where the RF classifier is able to outperform the rest of the models. The best performing RF model was developed by using a grid search approach, where multiple model parameters (number of estimators, depth, leaf splits, etc.) were evaluated. The resulting model had a precision, recall, and AU-ROC were observed to be 0.96, 0.98, and 0.99 respectively. The classifier was balanced in its prediction accuracy in both verified (class 1) versus non-verified (class 0) users (Figure~\ref{fig:user_randomf}). The output probability values of the binary model were further min-maxed to a threshold score between 0 and 100. The resulting normal distribution had a mean of 50.56, a median of 66.26, and a standard deviation of 39.69. \subsection{Text} The results of the text analysis module were based on the binary categorization of the tweets codified as ‘irma related’ (class 0) or ‘non irma related’ (class 1). Evaluation of the four different resulted in the F1-scores of .6553 - MCS, .7824 - DP, .7049 - CSTVS, and .7347 - SCSSC. We observe the dot product between search term vector and tweet vector sum (DP) gives us the best result. Figure~\ref{fig:text_auc} shows the AU-ROC curves comparing the different formula performance in the analysis. \begin{figure}[ht!] \centering \includegraphics[width=.6\textwidth]{./figures/text_auroc_paper.eps} \caption{AU-ROC Curves for \textit{text} --- 1) Cosine Similarity of Tweet Vector Sum (CSTVS) , 2) Dot Product of Search Term Vector and Tweet Vector Sum (DP) , 3) Mean Cosine Similarity (MCS), 4) Sum of Cosine Similarity over Square Root of Token Count (SCSSC).} \label{fig:text_auc} \end{figure} Each model was further evaluated to identify the best set of parameters. Within the analysis we found the DP formula was still the best performing with a word window size of 1, hidden layer dimensionality of 150, a minimum word count of 5, a negative sampling value of 1, and training the Word2Vec model through 25 epochs. The resulting normal distribution had a mean of 24.73, a median of 21.64, and a standard deviation of 14.05. \section{Discussion} We address each individual model separately before discussing the final combined model and providing limitations/ future directions for this work. \subsection{Individual models} \subsubsection{Geospatial} The geospatial models developed in the study provide a measure of relevance to a tweet by including the forcing sensor data (wind speed, precipitation, and distance from the eye of the hurricane). The best performing function of $log_{10}(\frac{wind\ *\ rain}{\sqrt[]{distance}})$ combines the values into a single normalized score which can be used to weight a geographic/sensor relevancy factor for any tweet. More specifically, the function helps us identify Twitter messages at locations which are in close proximity to the hurricane forcing and have observed increased amount of precipitation and wind speed. As seen in the results, the chosen $log_{10}(\frac{wind\ *\ rain}{\sqrt[]{distance}})$ was the closest to a normally distributed function. This allows for a greater granularity on threshold cutoff points in comparison to other functions, leading to a fine-grained control over filtering based on the geographic relevance of the tweets. The statistical properties of the function also enables analysis of confidence intervals which can be used to ascertain the reliability of a message within the context of sensor data. In other words, tweets with anomalous sensor readings can be easily identified, leading to more reliable mining of messages related to the disaster event. We envision that filtering tweets using their geospatial information relative to storm position and also environmental factors can help isolate tweets from heavily impacted locations. By examining locations close to the storm, with high wind gusts, or heavy precipitation allows users to quickly examine locations that might be expected to show the most severe imapcts from storm events. \subsubsection{Image} Comparing the performance of the CNN architectures (Inception V3, VGG, ResNet, and Tuned Inception V3) for binary classification (hurricane and non-hurricane related), we observe that the Tuned Inception V3 model (F1-score 0.95) has almost a 6-7\% accuracy gain over others. In comparison to the VGG and ResNet architectures, the Tuned Inception V3 larger number of parameters which can be trained to observe the nuances between the images. While the base Inception V3 classifier contains the same number of parameters, re-tuning the weights to our training sample of images improved its accuracy considerably for the binary classification. This can be attributed to the pre-training and transfer learning of the model, where it already had prior weights based on classification of physical objects, and our image data tuned it further for disambiguating physical and non-physical scenes. We do observe a slight performance decrease (F1-score 0.91) of the architecture trained on the multi-label annotation of the images. This can be attributed to the limited number of training samples that were available to the classifier. The complexity of the images in the samples further degrades the performance, for example, images of lakes and sea water are not much different from images of flooding. Prior research in the area of automating image analysis (using machine learning) from social media has primarily focused on quantifying the level of damage in disaster situations \citep{lagerstrom_image_2016,nguyen_damage_2017,li_localizing_2018}. Our approach uses a dual stage model, where the first stage is responsible for increasing the quality of images by filtering out the non-relevant / non-physical images. The output is then fed into the second stage for categorization into different groups based on situational conditions (flooding, wind, and destruction). While prior studies have looked at disambiguating “fake/altered” images \citep{gupta_faking_2013,marra_detection_2018}, they are based on analyzing the content of the tweet along with user reliability measures for training machine learning models. Within our approach we only utilize the image features for the training our models. The output is image scores are based on normalized probability values, which can be used for threshold cutoffs, where setting a high threshold will only mine the most hurricane related images. The second stage then annotates the images for further filtering of images based on the needs of the domain.Filtering images permits users to quickly focus on a small subset of visual information that is presumed to be most valuable for storm impact assessment, compared to needing to scroll through many images to find useful information. \subsubsection{User} Prior studies \citep{buntain_automatically_2017,zhou_fake_2018,masood_spammer_2019,del_vicario_polarization_2018} focused on identifying incorrect/fake/altered information in social media have established the source of information (social media user) as a key component. A large proportion of the studies \citep{hutchison_detecting_2010,subrahmanian_darpa_2016,efthimion_supervised_2018,sahoo_hybrid_2019} have been based on developing machine learning approaches towards detection of “bots” or fake user accounts \citep{ferrara_rise_2016} on social media. For example, \cite{karami_twitter_2019} identify the credibility of the user as an important element in mining good quality situational awareness information from social media. Within our approach, we leverage prior work done in the field by identifying the user features of account age, status count, number of followers, number of friends, existence of url links, number of hashtags, existence of images, retweets, geolocation, and message frequency in training our machine learning models. \begin{figure}[ht!] \centering \subfigure[Confusion matrix of non-verified (class 0) versus verified (class 1) user prediction with Random Forest Classifier.]{ \resizebox*{6.5cm}{!}{\includegraphics{./figures/fig9.eps}}}\hspace{5pt} \subfigure[Relative importance between features (using information gain) for prediction verified users using Random Forest Classifier.]{ \resizebox*{6.5cm}{!}{\includegraphics{./figures/fig7.eps}}} \caption{Performance of the \textit{user} Random Forest Classifier in the binary classes and feature importance metrics. } \label{fig:user_randomf} \end{figure} Comparing the results between the parametric (Logistic Regression) and the non-parametric ensemble models (Random Forest and Gradient Boosting), we observe the ensemble models are able to outperform by a margin of 4-7\%. The developed Random Forest model has a very high accuracy (F1-score 0.97, AU-ROC 0.99) in disambiguating between verified and non-verified users. While the ratio of the number of verified versus non-verified users was imbalanced (approximately 1:100) in our data, the developed RF model is able to accurately distinguish between the classes as shown by the confusion matrix (Figure 8). Further analyzing the RF model, we calculated the average decrease in Gini impurity/information gain (entropy) among all estimators to observe the importance of features. Specifically, as estimators are developed on a subset of features, the decrease in information gain across a subset of features can be used to infer the relative importance of features. Figure 9, shows the relative importance of four features (rest where too low to observe), where the number of followers, status, and friends, along with the account age are the top features which affect the decision of the model towards the credibility of a Twitter user in our data. The analysis of features within our model shows similar feature importance measures to that used in prior research to identify reliable information sources \cite{karami_twitter_2019}. However, our approach provides a more generalized model where a thresholding on probability scores can be used to select user sources based on needs of a specific event. The approach is also dynamic where a model can be quickly retrained using the available ''Verified'' tags instead of manually re-annotating accounts. This prevents temporal dilation of features where a model trained on an older labeled dataset cannot perform as well due to the changes in account statistics over time. \subsubsection{Text} With the observed dot-product based model performing the best with the F1-score analysis, we applied the model towards an hourly aggregated corpus within our data. Specifically, when the corpus was confined to the tweets from a single hour, the vector representations of word embeddings were only influenced by the contexts derived from that hour. Words would have a unique vectorization specific to that hour, and relationships between words were dependent on the context interpretations within that time. The cosine similarity of two terms could be calculated for this duration, and words with the highest scoring cosine similarity to a term would indicate an observed relationship that was finite within the timeframe. In short, two words could be similar in one hour, and completely different the next, depending on the content of the tweets at the time. Table~\ref{tab:words} shows the output of the DP model for the hourly aggregated tweets. Prior to landfall (time 13:00), we observe mentions of the ``storm'', ``wind'', ``eye'', ``ese'' (East-South-East), ``e'' (East), etc, having prominence in the top 20 words as identified by the DP model to be semantically similar to search term ``irma''. There is consistency in the thematic representation where these words did occur across the 6 hours prior to the hurricane. During the window of the hurricane Irma’s landfall we observe ``shelter'', ``\#hurricaneirma'', ``eye'', ``landfall'', ``help'', ``plea'', etc., as the most related terms to ``irma''. After the hurricane the context of the ``irma'' changes to reflect more help/rescue/concern words where ``shelter'', ``safe'', ``check'', ``food'', ``power'', etc. become the most prominent words. \definecolor{dk-before}{HTML}{ffb399} \definecolor{md-before}{HTML}{C04C5C} \definecolor{lt-before}{HTML}{D3828D} \definecolor{dk-during}{HTML}{95711E} \definecolor{md-during}{HTML}{BB9337} \definecolor{lt-during}{HTML}{CFB373} \definecolor{dk-after}{HTML}{ace600} \definecolor{md-after}{HTML}{5A7DB4} \definecolor{lt-after}{HTML}{8BA4CA} \begin{table}[ht!] \centering \caption{Hourly aggregate of top 20 semantically related to terms to “Irma”, for six hours prior and after landfall. The words have been stemmed to their root. \#hirma denotes the hashtag \#hurricaneirma used in the tweet. Colors indicate similar terms across the different time windows of the hurricane.} { \resizebox{\textwidth}{!}{ \begin{tabular}{clllllllllllll}\toprule \multirow{3}{*}{\makecell{\textbf{Word} \\ \textbf{Rank}}} & \multicolumn{13}{|c|}{\textbf{Time}} \\ \cmidrule{2-14} & \multicolumn{1}{|l}{\textbf{7:00}} & \textbf{8:00} & \textbf{9:00} & \textbf{10:00} & \textbf{11:00} & \textbf{12:00} & \multirow{2}{*}{\makecell{\textbf{13:00} \\ \textbf{Irma Landfall} }} & \textbf{14:00} & \textbf{15:00} & \textbf{16:00} & \textbf{17:00} & \textbf{18:00} & \multicolumn{1}{l|}{\textbf{19:00}} \\ [3ex] \cmidrule{1-14} 1. & sleep & last & \cellcolor{md-before}ese & \cellcolor{md-before}ese & tampa & tampa & \cellcolor{dk-during}\textbf{shelter} & \cellcolor{dk-during}shelter & \cellcolor{dk-during}shelter & \cellcolor{dk-during}shelter & \#hirma & \cellcolor{lt-before}hit & tampa \\ 2. & offici & outsid & outsid & tri & yet & time & \textbf{first} & whole & tampa & want & outsid & \cellcolor{dk-after}safe & \cellcolor{lt-during}eye \\ 3. & need & sleep & moder & help & time & \cellcolor{lt-after}check & \textbf{wait} & tampa & beauti & time & food & outsid & bay \\ 4. & \cellcolor{md-before}ese & \cellcolor{md-before}ese & beauti & yet & see & good & \textbf{get} & open & first \\ 5. & want & \cellcolor{md-before}e & sleep & outsid & \cellcolor{lt-during}eye & tri & \textbf{tri} & \cellcolor{lt-after}check & \#hirma & tampa & \cellcolor{dk-after}safe & updat & time \\ 6. & \cellcolor{lt-before}hit & \#key & nation & \cellcolor{lt-during}eye & friend & might & \textbf{make} & open & prep & get & watch & hurrican & wait \\ 7. & \#key & wind & \cellcolor{md-before}e & moder & first & night & \textbf{could} & \cellcolor{lt-before}hit & food & guess & time & make & \cellcolor{lt-before}hit \\ 8. & wind & tropic & need & sleep & night & first & \textbf{made} & get & come & hurrican & peopl & prayer & outsid \\ 9. & tropic & good & wind & heavi & last & close & \textbf{see} & friend & watch & last & know & first & \#hirma2017 \\ 10. & see & beach & fuck & wellington & close & coffe & \cellcolor{lt-during}\textbf{eye} & read & yet & \cellcolor{lt-after}check & see & get & make \\ 11. & much & \#irma & \#sfltraffic & wind & \#traffic & friend & \textbf{\#hirma} & world & time & \cellcolor{lt-before}hit & love & wait & food \\ 12. & \#irma & florida & pleas & fuck & strong & help & \textbf{world} & \cellcolor{dk-after}safe & sleep & peopl & power & everyon & us \\ 13. & beach & \cellcolor{dk-before}storm & \cellcolor{dk-before}storm & tropic & outsid & last & \textbf{night} & good & ride & come & gonna & \cellcolor{lt-after}check & \cellcolor{dk-during}shelter \\ 14. & florida & \#mfl & beach & good & make & follow & \textbf{peopl} & time & first & \cellcolor{lt-during}eye & \#irma & see & get \\ 15. & \cellcolor{dk-before}storm & aso & peopl & see & well & outsid & \textbf{close} & come & get & friend & still & home & last \\ 16. & know & lauderdal & \#irma & pleas & want & make & \textbf{outsid} & make & \cellcolor{lt-after}check & food & hurrican & power & point \\ 17. & \#mfl & power & florida & \cellcolor{dk-before}storm & phone & sleep & \textbf{help} & first & go & day & \#nfl & \#hirma & \cellcolor{dk-after}safe \\ 18. & power & mesonet & f & flood & sleep & strong & \cellcolor{dk-before}\textbf{landfal} & beauti & know & see & make & okay & open \\ 19. & call & rain & rain & beach & \cellcolor{lt-before}hit & \#irmageddon & \textbf{come} & wait & open & make & home & watch & alway \\ 20. & aso & \cellcolor{dk-after}safe & mesonet & rain & florida & open & \textbf{pleas} & home & tri & way & want & yet & video \\ \hline \end{tabular}}} \label{tab:words} \end{table} The results show that the word embedding based dot product model is capable of identifying tweets which are most relevant to the search/seed term. This is highlighted by the example of the term ``ese'', which when taken by itself, might reference an informal Spanish colloquialism for ``man''. When interpreted within the hourly-divided corpora within this dataset, it takes on a different semantic interpretation. For the tweets occurring within each of the four hours immediately preceding landfall, ``ese'' is in the top twenty most related terms to ``irma'', and does not appear in the hourly lists following. Looking at the terms related to ``ese'' it can be determined that this refers to the abbreviation for East-South-East, likely referencing the direction from which the hurricane approached. After landfall, this term was no longer as relevant, and therefore less likely to appear as a related term. \subsection{Overall model} \begin{figure}[ht!] \centering \includegraphics[width=.9\textwidth]{./figures/fig8.eps} \caption{CDF of Overall Model and percentage of tweets passing different model thresholds.} \label{fig:overall_cdf} \end{figure} In the overall model, the number of possible combinations for the thresholds is large (at $100^4$), where each of the four models can have a value ranging from 0-100. A cumulative distribution plot (CDF) was used to analyze the percentage of data-points passing the thresholds set for each of the models. Figure~\ref{fig:overall_cdf} shows the comparative analysis of each of the model, where the curves are inversely proportional to the thresholds indicating a decrease in the percentage of tweets passing higher thresholds. Within the analysis, low thresholds are representative of more reliable sources and related contents, resulting in a low percentage of overall tweets passing through the filter. Similarly, at the threshold of 100, all tweets pass the filter providing complete access to all data. The CDF plot also highlights the comparative performance of various models, where the text based filter includes a higher percentage of tweets at lower thresholds while the user verification filter includes most users at higher thresholds. Image classification also results in a similar performance to user verification (including most users at higher thresholds), whereas filtering based on geospatial scores filters more linearly. We observe high quality results (low false positives) at a likelihood occurrence of $0.6$. by setting initial thresholds to $30$ for text, $50$ for geospatial, and $85$ for both image and user scores. These recommended thresholds for Hurricane Irma provide a baseline for comparison with different events , and for hurricanes in different locations. \subsection{Limitations and Future Work} Our current work explores the utilization of multiple modalities present in social media data to filter hazard event related information. We acknowledge certain limitations of this approach. Our approach is to cumulatively evaluate the operation of all sub-models in capturing the messages. As a result, we focused in this work on tweets that have all attributes: geolocation, text, and image (note all tweets have user attributes). However a smaller overall model with specific combinations of the sub-models can be used in certain conditions. For example, researchers who are interested in just messages with text can use an overall model that excludes the image sub-model and subsequently not filter based on a threshold for images. Furthermore, our models are evaluated using the data from a single event — (Hurricane Irma) and a single location (Florida, USA). As a part of our future effort we plan to extend this framework to other hurricane events (and locations), such as, Maria, Harvey, and Florence, along with application of the approach to other disaster scenarios, such as fires, earthquakes, floods, etc. to aid in understanding the filtering step and thresholds in other contexts. Each event will likely have different specifications on the quality of data that needs to be extracted, for which we need to cross evaluate the approach against various events to provide recommendations for thresholds to be used for different disaster categories. Our approach can operate as a primary filtering mechanism for additional anlysis to extracting information during a disaster event. Additional models which help with categorization of messages, such as, disaster damage quantification, information, requests of help, resources offerings, organizing efforts, etc., can be implemented to extract higher level information from the data. \section{Conclusion} In this study, a multimodal filtering approach was developed and evaluated to extract and subset geocoded images posted on Twitter within the context of Hurricane Irma. Our prototype model consisted of four sub-models: geospatial, image classification, user credibility, and text analysis. Each sub-model returned a score in the range of 0-100 and allowed for user-defined filtering based on bespoke thresholds. Each of the four models aim to filter information about reliability, information consistency, and overall usefulness of the message. This single combined model shows potential for application in disaster and emergency contexts, allowing users to quickly search and filter for relevant geolocated tweets. \section{Acknowledgments} The authors would like to thank UNCG undergraduate students Kaitlyn Jessee and Elaina Kauzlarich for classifying the images associated with the tweets. This study was supported in part by the National Science Foundation (Awards\# CMMI-1541136 and \# SES-1823633), the Eunice Kennedy Shriver National Institute of Child Health and Human Development (Award \# P2C HD041025), DoD/DARPA (R0011836623/HR001118200064), seed grant initiatives from UNC Greensboro and Penn State's Social Science Research Institute, Population Research Institute, and Institute for CyberScience, and an Early-Career Research Fellowship from the Gulf Research Program of the National Academies of Sciences, Engineering, and Medicine. The content is solely the responsibility of the authors and does not necessarily represent the official views of the Gulf Research Program of the National Academies of Sciences, Engineering, and Medicine. \section{Data and codes availability statement} The data and the codes used in the research are available on Figshare: \url{https://figshare.com/s/235146fc2d6de33654f3} \citep{datacite} \section{References}
{'timestamp': '2021-01-05T02:18:52', 'yymm': '2101', 'arxiv_id': '2101.00480', 'language': 'en', 'url': 'https://arxiv.org/abs/2101.00480'}
arxiv
\section{INTRODUCTION} The duty of a receptionist is to assist people in a friendly and pleasing manner. Nevertheless, human receptionists are unable to maintain their composure, focus and efficiency at a consistent level at all times. As a result, the quality of service provided by human receptionists can deteriorate due to many factors including service time and the number of service requests. Moreover, the job of a receptionist can sometimes be dull and monotonous, which leads them to fall asleep on their desks. Furthermore, many additional factors such as down-times (breaks, vacations) need to be considered when employing human receptionists. To address the above issues and to improve the quality of service provided by receptionists, we can introduce robotic receptionist systems. Robot receptionists can introduce excitement and memorable experience for the interacting humans. A robot receptionist can be considered as a Socially Assistive Robot (SAR), since its objective is to assist human users through human interaction~\cite{feil2005defining}, or it can be considered as a Socially Interactive Robot (SIR)---a robot equipped with social interaction skills, as defined by Fong et al.~\cite{fong2003survey}. Both SAR and SIR belong to the social robotics category. One of the key goals of social robotics is to implement an intelligent system with functional social interactive capabilities. Extensive research is being carried out in this domain and sophisticated humanoid robotic systems with advanced capabilities such as Sophia~\cite{weller2017meet} can be identified as the state-of-the-art. However, almost all existing innovations are high-priced and are barely suitable for public or commercial use. Furthermore, it is also time consuming to develop custom solutions for each specific application, since there does not exist any open-source or commercial intelligence cores/platforms for developing receptionist robots, to the best of our knowledge.\par Consequently, the main objective of this work is to develop a low-cost, user-friendly receptionist robot with an open-source intelligence core, which can assist human users in a friendly manner. Our solution: DEVI is the first ever human-like robot receptionist in Sri Lanka and the first open-source intelligence core specifically aimed at robot receptionists. Our robot has the following functionalities and features.\par \begin{itemize} \item Face identification (of known people) \item Face memorization and re-identification (of unknown/ new people) \item Speech recognition and synthesis \item Conversational chatbot \item Direction guidance with physical hand gestures \item 180-degree person proximity sensing and interaction with a rotatable head unit \end{itemize} The rest of the paper is organized as follows: section~\ref{RELATED WORK} describes related work; section~\ref{SYSTEM ARCHITECTURE AND DESIGN} explains the overview and design criteria of the proposed system; achieved results of the proposed system are given in section~\ref{RESULTS}; finally, in section~\ref{CONCLUSION}, important conclusions on the proposed robot receptionist system are made, while suggesting possible future improvements. \par \section{RELATED WORK} \label{RELATED WORK} Pepper~\cite{lafaye2014linear} is a personal assistant robot introduced in 2014, which has been adopted by many users to replace human receptionists. Pepper is popular in countries like Japan, UK and Belgium and costs around \$22,000~\cite{pepperprice} for purchase. It is capable of detecting human emotions, performing hand, neck and several body motions. Nevertheless, Pepper has a more machine-like appearance and is considered to be expensive to be adopted for small and medium scale establishments. The intelligence core of Pepper is not disclosed to developers to create custom solutions for different application scenarios. \par Sofia~\cite{weller2017meet} is a revolutionary humanoid robot introduced by Hanson Robotics as a social humanoid robot in 2015 with advanced potential to closely mimic a human. It has the capability of displaying more than 50 expressions and it consists of an offline AI core. Experts who have reviewed the open-source code of the Sophia robot state that Sophia is best categorized as a chatbot with a face~\cite{gershgorn2017inside}. Aiko Chihira is a humanoid robot assistant deployed to work as a department store receptionist~\cite{aiko}. She is capable of performing acts such as greeting and providing information to the customers. She is also designed with advanced technology to mimic human appearance and facial expressions. Nadine~\cite{thalmann2017nadine} can be identified as another social humanoid robot, which is modeled after Professor Nadia Magnenat Thalmann. Nadine is currently deployed as a receptionist. \par The proposed robot receptionist system, DEVI, is motivated and inspired by the aforementioned receptionist systems of varying complexities and cost. The main objective of this proposed work is to design and develop an open-source, low-cost, user-friendly, customizable receptionist intelligence with a human-like appearance, mainly to be utilized at small and medium scale establishments. It is also intended as the initial step of a research platform that can capture human interactions for future study. \section{SYSTEM ARCHITECTURE AND DESIGN} \label{SYSTEM ARCHITECTURE AND DESIGN} \begin{figure}[tb] \begin{center} \includegraphics[width=\columnwidth]{architecture.jpg} \caption{\label{architecture} System architecture of DEVI} \end{center} \end{figure} \begin{figure}[tb] \begin{center} \includegraphics[width=\columnwidth]{systemflow.jpg} \caption{\label{systemflow} DEVI interactive processes: (a) Main Process 1- Person detection and identification (b) Main Process 2- User query services} \end{center} \end{figure} The overall system architecture of the DEVI robot receptionist is shown in Figure~\ref{architecture}. DEVI system consists of a loosely coupled modular architecture, which isolates modular failures without causing a total system crash. Furthermore, this modular architecture also facilitates the addition of new features to the design easily. DEVI's physical structure is designed using a mannequin, to ensure a human-like appearance. DEVI's system flow diagram can be explained in two main processes as shown in Figure~\ref{systemflow}. A novel feature, which highlights DEVI from existing robot receptionists, is the proximity sensing necklace. This proximity detection unit generates a proximity map with a 180-degree field of view of the robot's surrounding. Using the proximity map, DEVI is able to accurately turn its head to interact with people approaching from different directions. The proximity map also helps in controlling the execution of facial recognition process to reduce processor utilization. The facial recognition process is triggered only when a person is in close proximity to the robot. DEVI analyses three possible scenarios for human interaction initiation: known-person identification, unknown person detection and a false detection. In a known-person identification scenario, DEVI will greet the person using the speech synthesis and limb actuator system. In an unknown-person detection scenario, DEVI will ask for the name of the person and store the person's face in a dynamic database with the person's consent, so that it can detect his/her face in future encounters. In a false detection scenario, DEVI will return to the initial idle state. False positives are identified when a face is not detected within a predefined timeout. Currently, DEVI only supports the English language for speech recognition and synthesis. A touch display is provided with the robot, as an auxiliary interface, to assist people who may fail to speak in the standard English accent. DEVI system design is explained in the following sections. \par \subsection{Hardware Layer} The proximity detection unit detects people within a specified maximum range, creates a proximity map and triggers the face detection system accordingly. The neck-motion control unit is responsible for controlling the direction of the robot's head by turning the neck, based on the detection angle of the user (the relative orientation of the user, with respect to the robot). The detection angle is extracted from the proximity map, which is generated by the proximity detection unit. The limb actuator control system controls the hands of the robot to give directional guidance using physical hand gestures. The touch display, camera, mic array and the speakers are connected to the Linux host computer, while the proximity detection unit and the motor controller for limb and neck actuators are interfaced with the robot's main controller, implemented using an ATmega2560 microcontroller. The main controller and the Linux host maintains a serial communication link, using a custom packet structure. \subsubsection{Person Proximity Detection Unit} This unit comprises five VL53L0X time-of-flight (TOF) sensors~\cite{c7}, each with a field of view of 25-degrees and they are placed with a gap of 45-degrees between two sensors; the circular arrangement appears as a necklace on DEVI. The unit can sense within a radius of 110\,cm with a 180-degree field of view. Whenever users appear in the proximity map, the proximity detection unit will register all these events using a First-In, First-Out (FIFO) data structure. In the presence of many users, the ATmega2560 controller has the ability of prioritizing regions in the proximity map generated by the proximity detection unit. Each time a conversation is finished, the main interface will dequeue the next element of the FIFO queue, which corresponds to the region where the next user has arrived, and thereby the robot will service the corresponding person. \subsubsection{Limb Actuator Control System} \begin{figure}[t] \begin{center} \includegraphics[width=\columnwidth]{joints4.png} \caption{\label{arms} Elbow and shoulder joints of DEVI} \end{center} \end{figure} This system is responsible for the control of two degrees of freedom in each hand: shoulder joint and elbow joint. It comprises two CM-785HB (Hitec) servo motors~\cite{c8} with external gear reducers for shoulders and two SpringRC SR811 servo motors~\cite{c9} for elbows. The elbow and shoulder joints are shown in Figure~\ref{arms}. All the motors in the system are controlled by a Micro Maestro 6-Channel USB Servo Controller~\cite{c10}, which is interfaced with the ATmega2560 microcontroller that communicates with the Linux host system through serial communication. \subsubsection{Neck-motion Control Unit} The neck motion is achieved by a single degree of freedom at the neck joint. A TowerPro MG945 servo motor~\cite{c19} is fixed inside the head of the robot to rotate the head. It enables DEVI to rotate its head towards the user, based on the input from the person proximity detection unit. This unit only rotates the robot's head, keeping the orientation of the proximity detection unit fixed. \subsection{Robot Intelligence Core} DEVI's intelligence core comprises three main units: face recognition unit, chatbot and the human-machine interface (HMI). Deep learning based face recognition system allows DEVI to recognize people who have been previously encountered. The chatbot facilitates the acquisition of the identities (name, face image) of unknown people to maintain a dynamic database. Later, DEVI can retrain her face recognition neural network periodically during idle times, using this dynamic database. The speech recognition, synthesis and natural language processing (NLP) components within the chatbot system assist DEVI to further enhance her social skills and answer user queries. The HMI comprises two main units: the auxiliary touch display and the integrated Google assistant. \subsubsection{Face Recognition System with Dynamic Database} \begin{figure}[tb] \begin{center} \includegraphics[width=\columnwidth]{faceflow.png} \caption{\label{face} Flow diagram of the face recognition system} \end{center} \end{figure} The main execution loop of the face detection and recognition design include the following sequence of steps. \begin{itemize} \item Receive and sample input video stream \item Detect the presence of one or more faces \item Recognize faces, if the faces are found within database \item Add to the database if faces are not recognized \end{itemize} Face detection and face recognition tasks are activated only when the proximity sensor readings indicate the presence of an object. In this event, the live video feed from the camera is fed to the face recognition system. In the absence of a face being detected by the face detection algorithm, the robot will move back to the initial idle state.\par If a face is detected, the robot will attempt to recognize the person, and if the person is recognized, DEVI will proceed to greet the person by his/her name. However, if the person is not recognized, he/she will be greeted and requested to enter the name, in order to be registered in the robot's dynamic database of users. When the user is willing to get registered with the system, facial images of the user will be saved in the database along with the name. However, if the user has not consented to be registered, the robot will directly service the user's queries. Figure~\ref{face} illustrates the flow of the face recognition process. The robot has a local database implemented using `mongoDB'~\cite{c11} database management software, which stores the name of each person, number of instances the person has been recognized by the robot and the last recognized date and time.\par The face detection and recognition unit is implemented using a deep residual network implementation (Resnet-29)~\cite{c12,c13} provided by `dlib'~\cite{c14} and a k-nearest neighbors (KNN) classifier. Face detection is carried out using a Histogram of Gradient (HoG) based feature detector available in `dlib'. This system is capable of detecting faces which are of 40$\times$40 pixel size or higher. In comparison with the convolutional neural network (CNN) based feature detector, this approach is much faster. The KNN classifier is used to compare several face poses of the same person. We utilize 10 images of each person accumulated over time when the person approaches the robot in several occasions. This threshold can be changed, and more faces would result in higher accuracy but longer training cycles to generate the KNN model. The face recognition algorithm executes in less than 67\,ms. In order to improve the recognition accuracy, multiple sample frames are fed through the algorithm iteratively.\par \subsubsection{Speech Recognition, Synthesis and NLP System} \begin{figure}[tb] \begin{center} \includegraphics[width=\columnwidth]{speechoverview2.JPG} \caption{\label{speech} Overview of the DEVI chatbot} \end{center} \end{figure} Speech recognition, synthesis and NLP systems are used to greet people, get to know their identities, maintain a conversation by responding to basic questions and etiquettes, and give directional guidance for known places. The NLP also features intent mapping, where the user can deliver the same query in different wordings; formal, informal or partially complete.\par The speech recognition module has 2 modes of operation: Auto-detection Enabled and Disabled (Figure~\ref{systemflow}). If auto-detection is enabled, voice clips exceeding a specified amplitude threshold will be extracted and processed using ReSpeaker Mic Array V2.0 \cite{mic}. If autodetection is disabled, then the user can choose either audio mode or text mode. In audio mode, the user can send his/her queries in audio clips of 5 seconds, which will be converted to text using the speech-to-text converter, and then will be passed to the NLP module. The output from the NLP module will be given to the text-to-speech converter and to the speaker embedded within the head of DEVI robot. If the text mode is selected, the process will skip the speech-to-text conversion and the original text query will be directly sent to the NLP module. Figure~\ref{speech} illustrates the inner workings of the DEVI chatbot. The audio queries are processed and converted to text queries using Google Cloud API. The text queries are directed to the agent hosted in the Dialogflow~\cite{c15} cloud-based platform, where NLP is carried out for the trained data. The output from the NLP module is subjected to the text-to-speech conversion, in which Pyttsx~\cite{manaswi2018speech} Python package is utilized. The intermediate text output from the NLP module will be displayed in the touch display for user convenience. For this specific application, DEVI's NLP model has been re-trained using an existing generic NLP model, also to give directional guidance to places inside the Department of electronic and Telecommunication Engineering of University of Moratuwa. However, the user can use their own Dialogflow model re-trained for their specifications and use the core platform of DEVI easily, due to the customizability of the proposed core platform.\par \subsubsection{Human-Machine Interface} \begin{figure}[tb] \begin{center} \includegraphics[width=\columnwidth]{gui4.png} \caption{\label{welcome}(a)~The main page of DEVI GUI (b)~Page to access DEVI chatbot in audio or text modes} \end{center} \end{figure} The intelligence core's HMI consists of a graphical user interface (GUI) and an integration to the Google Assistant. \par DEVI's display application is designed using Python Tkinter~\cite{lundh1999introduction} for the auxiliary touch display (GUI). As a socially assistive robot, DEVI also serves people with speech disorders by interacting through the provided touch display. The display application also acts as an alternative for speech interaction when the user is unable to communicate in a standard English accent with the robot. The GUI application has the following main controls: enter user name, access chatbot in audio/text mode, activate audio autodetection, test the gestures of DEVI and give a self-introduction of DEVI. Functions such as selecting modes either text or audio query are operated using the GUI application. Figure~\ref{welcome} shows two screenshots of the DEVI GUI. \par Apart from the GUI, we also have integrated the speech recognition module with Google assistant~\cite{forrest2017essential} in order to collect robot data from an offsite location. The chatbot is integrated with Google assistant and is capable of communicating through any Android smart phone with authorized access. Hence, we utilize 3 methods to interact with the robot: Google assistant, speech queries and text queries from display application.\par \section{EXPERIMENTS AND RESULTS} \label{RESULTS} This section describes the experiments and corresponding results obtained for the proposed system. Figure~\ref{DEVI} and accompanying videos~\cite{youtube} \cite{video} show the actual implementation of DEVI, the robot receptionist. The code base of DEVI is openly available in the given GitHub repository~\cite{devigit}.\par \subsection{General Specifications} \begin{figure}[t] \begin{center} \includegraphics[width=\columnwidth]{devi.png} \caption{\label{DEVI} DEVI, the robot receptionist} \end{center} \end{figure} \begin{itemize} \item Robot weight: 9.9\,kg (including the platform) \item Robot height: 110\,cm \item Max current consumption: 1.32\,A \item Idle current consumption: 0.18\,A \item Robot operating voltage: 24\,V \end{itemize} \subsection{Actuator Control System} The results of the actuator control system are given in Table~\ref{table:actuator-control-sys}. \begin{table}[b] \caption{Results of the actuator control system} \label{table:actuator-control-sys} \begin{center} \begin{tabular}{|c|c|c|}\hline Joint & Rotating angle & Speed \\ & (degrees) & (degrees/second) \\\hline Shoulders (2) & 180 & 36.5 \\\hline Elbows (2) & 110 & 69 \\\hline Head & 170 & 23.3 \\\hline \end{tabular} \end{center} \end{table} \begin{table}[tb] \caption{Statistics of sample TOF data sets} \label{table:tof} \begin{center} \begin{tabular}{|c|c|c|}\hline Smoothing & Mean & Standard \\ Factor & (mm) & Deviation (mm) \\\hline 1 & 1014.47 & 5.94 \\\hline 0.1 & 1015.61 & 2.07 \\\hline 0.3 & 1016.85 & 3.34 \\\hline 0.5 & 1020.71 & 3.87 \\\hline 0.7 & 1019.95 & 4.41 \\\hline 0.9 & 1016.70 & 5.69 \\\hline \end{tabular} \end{center} \end{table} \subsection{Person Proximity Detection Unit} A simple linear recursive exponential filter is used to smooth out the noisy distance measurements obtained from the TOF sensors. The comparison of results obtained for a data set of 500 TOF readings at a distance of 1\,m with a varying smoothing factor is given in Table~\ref{table:tof}. Thus, the optimum smoothing factor of 0.1 with the lowest standard deviation was selected.\par \subsection{Face Recognition System} This section presents the implementation and test results of the face recognition system of the DEVI robot.\par Figure~\ref{facescreenshots} shows few recognition instances from the face recognition system. Images were obtained using a camera with a 1.3\,Megapixel image sensor (1280$\times$1024 line resolution) and a 30-frames per second frame rate. The video feed is sampled by the face recognition module at a frequency of 15\,Hz. The measured overall performance accuracy of the face recognition system is 97.7\% against faces from the people available in ‘Faces in the Wild’ dataset~\cite{c20}. The performance results of face detection and feature extraction are presented in Table~\ref{table:faceperformance}. \par \begin{figure}[tb] \begin{center} \includegraphics[width=\columnwidth]{faces4.png} \caption{\label{facescreenshots} Recognition instances of users (a)~Known user (b)~Unknown user} \end{center} \end{figure} \begin{table}[tb] \caption{Performance of face detection and feature extraction steps} \label{table:faceperformance} \begin{center} \begin{tabular}{|p{5cm}|p{1.7cm}|}\hline Performance measure & Time (s) \\\hline Average time for face detection & 0.02 \\\hline Average time for feature extraction using the Resnet-29 model & 0.37 \\\hline \end{tabular} \end{center} \end{table} \subsection{Speech recognition, synthesis and NLP} \begin{table}[t] \caption{Results of speech recognition, NLP and synthesis} \label{table:NLP} \begin{center} \begin{tabular}{|p{3cm}|p{0.7cm}|p{3cm}|}\hline Conditions & Accu & Comments\\ &racy&\\\hline Responses to different variations of intents & 91.7\% & Text queries \\\hline Responses to different users & 77\% & Speech queries with different users in an environment with less noise \\\hline Responses of the chatbot in a noisy environment & ~50\% & Accuracy varies in a large range \\\hline NLP server response time & \textless2s & Depends on network speed \\\hline Audio response time & ~6.5s & Depends on network speed \\\hline \end{tabular} \end{center} \end{table} The results of speech recognition, synthesis and NLP are tabulated in Table~\ref{table:NLP}. When operated in text mode, the NLP module has an accuracy of 91.7\% and the accuracy can be improved with further training. However, when operated in audio mode, accuracy varies in a wide range from 77\% to ~50\%, due to the effect of ambient noise. In a noisy environment, it is difficult for the speech-to-text converter to transcribe the audio query to text. Using improved noise-cancellation algorithms or dedicated noise-cancelling hardware for audio processing can minimize this issue.\par \section{CONCLUSION} \label{CONCLUSION} \subsection{Summary} DEVI is a humanoid robot receptionist equipped with social interaction skills. DEVI's human-robot interface consists of an intelligence core and a hardware layer with 5 degrees-of-freedom. It has the capability to detect and recognize faces, register new people in the memory through conversation and maintain a database of people, greet them, respond to basic questions using an NLP platform and show directions with hands. It is a low cost solution, due to its low resource consumption and open-source core.\par Instead of continuously executing the face recognition algorithm, we are using a hardware level proximity map to trigger the execution of face recognition in order to reduce CPU load and power consumption, which can be considered as a novel feature. Furthermore, other notable features are the ability to recognize new people, collect their information via conversation and maintain a dynamic database of users, which removes the need for having a pre-trained fixed dataset for face recognition.\par \subsection{Future Work} Future developments of DEVI are planned in the aspects of adding more degrees-of-freedom to allow natural movements, deploy improved noise-cancelling mechanisms, decrease the latency of speech queries and adding additional actuators, in order to mobilize DEVI robot. Furthermore, face recognition system can be integrated with a data analytic system which could hold valuable information about people known to the system such as their availability at the premises, last arrival details. DEVI's core could be connected with other sensor systems to incorporate additional functionalities like directing people to the reception area. Thus, the open-source intelligence core of the DEVI system has the potential to become a solution to the increasing demand for socially assistive robots and socially interactive robots. {\small
{'timestamp': '2021-01-05T02:18:50', 'yymm': '2101', 'arxiv_id': '2101.00479', 'language': 'en', 'url': 'https://arxiv.org/abs/2101.00479'}
arxiv
\section{Introduction} Statistical inference methods for population process models are required to understand the dynamics of disease outbreaks such as the current COVID-19 global pandemic \citep{chen2020mathematical,he2020seir,mwalili2020seir}. Markov population models are commonly used to model disease dynamics in small to moderate sized populations \citep{sun2015parameter, allen2017primer, fricks2018stochastic} but simulation and inference can be computationally burdensome. In this work, we construct an approximate joint Gaussian likelihood for Markov population models that helps facilitate inference and simulation. This approximation, which we call the joint Gaussian deterministic limiting approximation (JGDLA) makes inference on Markov population models easier as the joint likelihood of all time-referenced observations can be computed using only the solution to a system of ordinary differential equations (ODEs). This removes the need of for stochastic infill, as is commonly needed for inference on Markov population models. A common framework for inference on Markov population models is to consider a Gaussian approximation of the Markov population model using the functional central limit theorem (FCLT). This approximates the Markov population model as a system of linear stochastic differential equations (SDEs). Except in a few specific cases, systems of linear SDEs with time-varying coefficients do not have analytical solutions. In the absence of an analytic solution, numerical methods are required to solve the system of SDEs. The Euler-Maruyama scheme is the most commonly used numerical method for performing inference on SDE models \citep{sun2015parameter,allen2017primer,eisenhauer2020lattice}. The Euler-Maruyama scheme relies on a fixed length time-lag that requires stochastic infill estimates to perform inference or predict at unobserved locations leading to computational bottlenecks. The main novel contribution of this work is the construction of the JGDLA model, which is built on the premise that the joint distribution of an It\'o diffusion approximation to the Markov population model can be fully constructed from the solution to a system of ODEs. The result is an approximate inference method for Markov population models which does not require stochastic infill and offers inference familiar to ODE modeling. This is not the first presentation of such a model: \cite{kurtz1978strong,kurtz1981approximation} introduced the mathematical framework needed to justify converge of the approximation, and \cite{baxendale2011sustained} used the approximation technique to investigate the behavior of stochastic population models through simulation. However, previous work only considers simulation and exploration of this approximation. In this work, we develop methods for statistical inference using the JGDLA. The population models considered in this work have a direct application in the field of epidemiology \citep{allen2003comparison}. We demonstrate that JGDLA outperforms a Euler-Maruyama scheme on simulated susceptible-infected-recovered (SIR) data sets of varying population sizes in terms of mean absolute prediction error at infill locations. The results of this simulation study show that JGDLA offers inference that only relies on solving an ODE system, does not require stochastic infill for predictions and inference, and provides an improved model fit in comparison to Euler-Maruyama, the most common approximation method as a framework for statistical inference. The remainder of the manuscript is organized as follows. In Section \ref{section::Markov Population Models} we introduce Markov population models as the sum of Poisson processes with stochastic rates. In Section \ref{section:Diffusion Approximaitons} we use the FCLT to form a system of linear SDEs for approximating Markov population models. We discuss the Euler-Maruyama scheme for approximate inference on Markov population models in Section \ref{section::Euler-Maruyama Approximation}. In Section \ref{section::Approximation by Limiting Deterministic Sytstem}, we introduce the JGDLA in the statistical framework. We compare JGDLA and the Euler-Maruyama approximation on simulated SIR data sets in Section \ref{section::Simulation Study}. In Section \ref{section::Covid Data Example}, we use the JGDLA to fit a stochastic SEIR model to the Princess Diamond Cruise COVID-19 data set. We conclude with a discussion in Section \ref{section::Discussion}. \section{Markov Population Models} \label{section::Markov Population Models} Deterministic population models are widely used in fields such as chemistry, ecology, and epidemiology to model large scale population dynamics such as disease outbreaks \citep{keeling2011modeling,fricks2018stochastic}. While deterministic models work well for very large populations, stochastic methods are needed to capture fine scale dynamics for populations with few individuals \citep{fricks2018stochastic}. In this section we formulate the Markov population model in terms of stochastic reactions and rates. Our treatment follows the formulation of \cite{kurtz1978strong} and \cite{fricks2018stochastic}. Let $\boldsymbol{X}(t) = \left(X_1(t),X_2(t),...,X_d(t)\right)^{\prime}$ be a d-dimensional random vector on the non-negative integers. $X_j(t)$ represents the number of individuals in a population of size $N$ belonging to subpopulation $j$ at time $t$ (e.g. number of infected individuals in a population). A population reaction occurs when one individual moves from one class to another. There are $n$ possible reactions for any given model, and $d$ subpopulations or classes. We let $\boldsymbol{R}_i$ be a d-dimensional vector denoting the $i^{th}$ reaction. For example, if an individual can move from class 1 to 3, the reaction vector will contain $-1$ as the first element, 1 as the third element, and 0 for all other $d-2$ elements. Each individual reaction is assumed to occur at a stochastic rate which depends on the current state $\boldsymbol{X}(t)$ and unknown rate parameters $\boldsymbol{\theta}$. We denote the reaction rate corresponding to $\boldsymbol{R}_i$ by $\lambda^{i}_{\boldsymbol{\theta}}\left(\boldsymbol{X}(t)\right)$. Let $Y_i(\lambda(\cdot))$ be an independent Poisson process with rate $\lambda(\cdot)$. We define the stochastic population model as the sum of Poisson processes in terms of reactions vectors and reaction rates given by \begin{eqnarray} \boldsymbol{X}(t) = \boldsymbol{X}(0) + \sum_{i=1}^{n} \boldsymbol{R}_i Y_i\left( \int_{0}^{t} \lambda^{i}_{\bs{\theta}}\left( \boldsymbol{X}(s) \right) \right). \label{eqn::X PP sum} \end{eqnarray} A classic example of a Markov population model is the stochastic SIR model with a closed population. The SIR model tracks the proportion of susceptible and infected individuals. We let $\boldsymbol{X}_N(t) = \left(S_N(t),I_N(t)\right)^{\prime}$, denote the scaled proportions of susceptible and infected individuals at time t. There are two possible reactions; a susceptible individual becomes infected $\boldsymbol{R}_1 = \left(-1,1\right)^{\prime}$, and an infected recovers $\boldsymbol{R}_2 = (0,-1)^{\prime}$. Susceptible individuals become infected at rate of $\lambda^1_{\boldsymbol{\theta}}\left(\boldsymbol{X}_N(t)\right) = \beta S_N(t) I_N(t)$, and infected individuals recover at a rate of $\lambda^2_{\boldsymbol{\theta}}\left(\boldsymbol{X}_N(t)\right) = \gamma I_N(t)$. We note that $\boldsymbol{\theta} = (\beta,\gamma)$, where $\beta$ is the contact rate, and $\gamma$ is the recovery rate. For fixed values of $\boldsymbol{\theta}$, simulation methods such as the Gillespie algorithm \citep{gillespie1977exact} and tau-leaping \citep{cao2006efficient} can be used to generate stochastic realizations from \eqref{eqn::X PP sum}. The proportions of infected and susceptible individuals from a simulated SIR data set with a population of size $N=100$ are shown in Figure \ref{figure::Markov_Pop_SIR}. \begin{figure}[H] \centering \includegraphics[scale=0.5]{SIR_N_100.pdf} \caption{Plot of the infected $I_N(t)$ (red) and susceptible $S_N(t)$ (blue) proportions for a population of size $N = 100$ generated from the stochastic SIR model with $\beta = 0.50$, $\gamma = 0.15$, $I_N(0) = 0.05$, and $S_N(0) = 0.95$.} \label{figure::Markov_Pop_SIR} \end{figure} \section{Diffusion Approximations} \label{section:Diffusion Approximaitons} Markov population model dynamics are controlled by the rate parameters $\boldsymbol{\theta}$ which are often unknown and need to be estimated from data. The most common approaches for inference on $\boldsymbol{\theta}$ are based on diffusion approximations to \eqref{eqn::X PP sum}. We use the FCLT to construct a system of linear SDEs to help facilitate inference on \eqref{eqn::X PP sum}. Our development follows that of \cite{baxendale2011sustained} and \cite{fricks2018stochastic}. Let $\boldsymbol{X}_N(t) = \frac{1}{N} \boldsymbol{X}(t)$ be the normalized population process. We scale \eqref{eqn::X PP sum} by $N$ to obtain \begin{eqnarray} \boldsymbol{X}_N(t) = \boldsymbol{X}_N(0) + \sum_{i=1}^{n} \boldsymbol{R}_i \frac{1}{N} Y_i\left( N \int_{0}^{t} \lambda^{i}_{\bs{\theta}}\left( \boldsymbol{X}_N(s) \right) ds \right). \label{eqn::X_N scaled PP} \end{eqnarray} We apply the FCLT for Poisson processes (see Appendix \ref{appendix::FCLT for Poisson Processes}) to each scaled Poisson process in \eqref{eqn::X_N scaled PP} to obtain the Gaussian approximation \begin{eqnarray} \boldsymbol{X}_N(t) \approx \boldsymbol{X}_N(t) + \sum_{i=1}^{n} \boldsymbol{R}_i \left( \int_{0}^{t} \lambda^{i}_{\bs{\theta}}\left( \boldsymbol{X}_N(s) \right) ds + \frac{1}{\sqrt{N}}B_i\left( \int_{0}^{t} \lambda^{i}_{\bs{\theta}}\left( \boldsymbol{X}_N(s) \right) ds \right) \right), \label{eqn::X_N approx BM} \end{eqnarray} where $B_i(t)$ are independent Brownian motions with variance $t$. We define \begin{eqnarray} \mathbb{E}\left[\boldsymbol{X}_N(t) | \boldsymbol{\theta} \right] &=& \boldsymbol{\mu}_{\boldsymbol{\theta}}\left(\boldsymbol{X}_N(t) | \bs{\theta} \right) = \sum_{i=1}^{n} \boldsymbol{R}_i \lambda^{i}_{\bs{\theta}}\left(\boldsymbol{X}_N(t)\right), \label{eqn::EM mu} \\ Cov\left(\boldsymbol{X}_N(t) | \bs{\theta} \right) &=& \Sigma_{\bs{\theta}}\left( \boldsymbol{X}_N(t) \right) = \text{G}_{\bs{\theta}}\left(\boldsymbol{X}_N(t)\right)\text{G}_{\bs{\theta}}^{\prime}\left(\boldsymbol{X}_N(t)\right), \label{eqn::EM Cov} \end{eqnarray} and differentiate \eqref{eqn::X_N approx BM} to obtain \begin{eqnarray} d\boldsymbol{X}_N(t) = \boldsymbol{\mu}_{\boldsymbol{\theta}}\left(\boldsymbol{X}_N(t)\right) dt + \text{G}_{\bs{\theta}}\left(\boldsymbol{X}_N(t)\right)d\boldsymbol{B}(t), \label{eqn::X_N linear time-varying SDE} \end{eqnarray} where $d\boldsymbol{B}(t) = \left(dB_1(t),dB_2(t),...,dB_d(t)\right)^{\prime}$ is a d-dimensional vector of differentiated independent Brownian motions $B_i(t)$. In some cases, the system of SDEs in \eqref{eqn::X_N linear time-varying SDE} yields an analytic solution \citep{oksendal2003stochastic}. However, in most cases, numerical methods are needed to provide approximate solutions. The remainder of this work focuses on approximate inference methods for Markov population models that rely on numerical solutions to the system of SDEs in \eqref{eqn::X_N linear time-varying SDE}. In the next section, we highlight the computational bottlenecks of the most commonly used numeric scheme for solving \eqref{eqn::X_N linear time-varying SDE}, Euler-Maruyama. In Section \ref{section::Approximation by Limiting Deterministic Sytstem}, we introduce the JGDLA, which is an approximate joint Gaussian likelihood for \eqref{eqn::X_N linear time-varying SDE} constructed from the solution to a system of ODEs. We then illustrate how to perform inference on \eqref{eqn::X_N linear time-varying SDE} using the JGDLA. \section{Euler-Maruyama Approximation} \label{section::Euler-Maruyama Approximation} In Section \ref{section:Diffusion Approximaitons} we showed that Markov population models can be approximated by the system of SDEs in \eqref{eqn::X_N linear time-varying SDE}. Performing inference on $\boldsymbol{\theta}$ in the absence of an analytic solution consists of two steps; first \eqref{eqn::X_N linear time-varying SDE} is approximated by a numerical method, second an approximate likelihood is constructed from the numerical solution \citep{doucet2009tutorial,kou2012multiresolution}. In this section, we introduce the Euler-Maruyama scheme, which is the most commonly used method for approximating \eqref{eqn::X_N linear time-varying SDE} \citep{sun2015parameter,allen2017primer}. We also highlight the most prominent drawbacks of inference methods that rely on the Euler-Maruyama scheme. The Euler-Maruyama scheme approximates the SDE in \eqref{eqn::X_N linear time-varying SDE} with the difference equation \begin{eqnarray} \boldsymbol{X}_N(t+\triangle t ) \approx \boldsymbol{X}_N(t) + \boldsymbol{\mu}_{\boldsymbol{\theta}}\left(\boldsymbol{X}_N(t) \right) \triangle t + \sqrt{ \triangle t} \text{G}_{\bs{\theta}}{ \left(\boldsymbol{X}_N(t)\right) } \boldsymbol{Z}, \label{eqn::Euler-Maruyama} \end{eqnarray} where $\boldsymbol{Z} = (Z_1,Z_2,...,Z_d)^{\prime} \sim N(\boldsymbol{0},\mathbb{I}_{d \times d})$ and $\triangle t$ is the time lag between sequential observations of $\boldsymbol{X}_N(t)$. From \eqref{eqn::Euler-Maruyama}, we obtain the conditional distributions \begin{eqnarray} \pi{\left( \boldsymbol{X}_N\left(t + \triangle t \right) | \boldsymbol{X}_N\left(t\right), \boldsymbol{\theta} \right) } \sim N\left(\boldsymbol{X}_N(t) + \boldsymbol{\mu}_{\boldsymbol{\theta}}\left(\boldsymbol{X}_N(t) \right) \triangle t, \triangle t \Sigma_{\bs{\theta}}\left( \boldsymbol{X}_N(t) \right) \right), \label{eqn::Conditional Euler} \end{eqnarray} which are used to perform inference in a likelihood framework. Inference with the Euler-Maruyama scheme generally requires stochastic infill \citep{kou2012multiresolution}. To see this note that the likelihoods in \eqref{eqn::Conditional Euler} require $\boldsymbol{X}(t)$ to be observed at all time lags $\triangle t$. Three common reasons Euler-Maruyama requires stochastic infill are; 1) $\boldsymbol{X}(t)$ was observed at irregularly spaced time points, 2) the time lag $\triangle t$ is shrunk to improve inference accuracy, and 3) to predict $\boldsymbol{X}(t)$ at unobserved time points. We return to the simulated SIR data set from Section \ref{section::Markov Population Models} to illustrate the implications of shrinking $\triangle t$. We assume $\boldsymbol{X}(t)$ is observed at time points $t=0,5,10,15,20,25,30$. We could solve the system \eqref{eqn::X_N linear time-varying SDE} with a time step of $\triangle t = 5$, however, we would not be able to predict $\boldsymbol{X}(t)$ at any other time points. We consider reducing $\triangle t$ from 5 to 1 to reduce numerical error and predict at the 24 unobserved time points $t=1,2,3,4,6,7,8,9,...,26,27,28,29$. This results in 48 latent states, 24 latent states for each of the two subpopulations tracked by the the SIR model. There is no clear way to ignore or integrate over the latent infill states produced by Euler-Maruyama. In the next section, we construct the the JGDLA as an alternative method for approximate inference on Markov population models that does not require stochastic infill for inference or predictions. We show that the JGDLA is a joint Gaussian likelihood for the observed time points of $\boldsymbol{X}(t)$ constructed from a deterministic system. The result is a method for approximate inference on Markov population models that relies solely on the solution to a deterministic system. \section{JGDLA} \label{section::Approximation by Limiting Deterministic Sytstem} In this section we construct the joint Gaussian likelihood of the JGDLA. We follow the results of \cite{kurtz1978strong} to show that the SDE approximation of the Markov population model converges to a system of ODEs. We use the result to construct the JGDLA covariance from the solution to the system of ODEs. \subsection{Limiting Deterministic Systems} We summarize the results of \cite{kurtz1978strong} which details the sufficient conditions required for the system of SDEs in \eqref{eqn::X_N linear time-varying SDE} to converge to a deterministic system. Assume that $\boldsymbol{x}$ is an element in some compact subset $K \subset \mathbb{R}^{d}$ and the following conditions hold: \begin{enumerate} \item $\sum_{i=1}^{n} |\boldsymbol{R}_i| \sup \lambda^{i}_{\bs{\theta}}(\boldsymbol{x}) < \infty$, \item $\boldsymbol{F}(\cdot) = \sum_{i=1}^{n} \boldsymbol{R}_i \lambda^{i}_{\bs{\theta}}(\cdot)$ is Lipshitz on $K$, \item $\lim\limits_{n\rightarrow \infty} \boldsymbol{x}_n = \boldsymbol{x}^{\dagger}$. \end{enumerate} Theorem 8.1 of \cite{kurtz1981approximation} states that for each $t>0$, \begin{eqnarray} \lim\limits_{n\rightarrow \infty}\sup_{s\leq t} | \boldsymbol{X}_n(t) - \boldsymbol{X}^{\dagger}(t)| \rightarrow 0, \end{eqnarray} where \begin{eqnarray} \boldsymbol{X}^{\dagger}(t) = \boldsymbol{X}^{\dagger}(0) + \int_{0}^{t} \boldsymbol{F}\left(\boldsymbol{X}^{\dagger}(s)\right)ds, \label{eqn::X det integral} \end{eqnarray} or equivalently \begin{eqnarray} d\boldsymbol{X}^{\dagger}(t) = \boldsymbol{F}(\boldsymbol{X}^{\dagger}(t)) = \sum_{i=1}^{n} \boldsymbol{R}_i\lambda^{i}_{\bs{\theta}}\left(\boldsymbol{X}^{\dagger}(t)\right)dt, \label{eqn::X det diff} \end{eqnarray} with initial state $\boldsymbol{X}^{\dagger}(0)$. That is, the diffusion approximation of the Markov population process converges to a system of ODEs as the population size $N$ tends towards infinity. Scientists in fields such as chemistry, ecology, and epidemiology commonly utilize deterministic population models in the form of \eqref{eqn::X det diff} \citep{keeling2011modeling,fricks2018stochastic}. We defined the Markov population model of Section \ref{section::Markov Population Models} in terms of reaction vectors $\boldsymbol{R}_i$ and rates $\lambda^i_{\bs{\theta}}(\cdot)$. We note that the reaction vectors and rates of the deterministic system in \eqref{eqn::X det diff} are of the same form as the diffusion approximation in \eqref{eqn::X_N linear time-varying SDE}. This allows stochastic population models to be constructed from their deterministic analogues. In the following sections, we derive the distribution of the JGDLA from the solution of \eqref{eqn::X det diff}. \subsection{Approximate Gaussian Processes} \cite{kurtz1978strong} constructed an approximate distribution for the system of SDEs in \eqref{eqn::X_N linear time-varying SDE} from the limiting deterministic system in \eqref{eqn::X det diff}. We present the results of \cite{kurtz1978strong} required to obtain an approximate distribution for \eqref{eqn::X PP sum}. We begin by considering the difference between $\boldsymbol{X}_N(t)$ and its corresponding infinite population limit $\boldsymbol{X}^{\dagger}(t)$. Subtracting equations \eqref{eqn::X_N approx BM} and \eqref{eqn::X det integral} gives \begin{eqnarray} \boldsymbol{X}_N(t) - \boldsymbol{X}^{\dagger}(t) &\approx& \boldsymbol{X}_N(0)-\boldsymbol{X}^{\dagger}(0) + \frac{1}{\sqrt{N}} \sum_{i=1}^{n} \boldsymbol{R}_i B_i\left(\int_{0}^{t} \lambda^{i}_{\bs{\theta}}{ \left(\boldsymbol{X}^{\dagger}(s) \right)} ds \right) \nt \\ & & + \int_{0}^{t} \boldsymbol{F}\left(\boldsymbol{X}_N(s)\right) - \boldsymbol{F}\left(\boldsymbol{X}^{\dagger}(s)\right) ds. \label{eqn::X_N with F} \end{eqnarray} Using a first-order Taylor expansion of $\boldsymbol{F}(\boldsymbol{X}_N(s))$ about $\boldsymbol{F}\left( \boldsymbol{X}^{\dagger}(s) \right)$, \eqref{eqn::X_N with F} becomes \begin{eqnarray} \boldsymbol{X}_N(t) - \boldsymbol{X}^{\dagger}(t) &\approx& \boldsymbol{X}_N(0)-\boldsymbol{X}^{\dagger}(0) + \frac{1}{\sqrt{N}} \sum_{i=1}^{n} \boldsymbol{R}_i B_i\left(\int_{0}^{t} \lambda^{i}_{\bs{\theta}}{ \left(\boldsymbol{X}^{\dagger}(s) \right) }ds \right) \nt \\ & & + \int_{0}^{t} \partial \boldsymbol{F}\left(\boldsymbol{X}^{\dagger}(s)\right)\left(\boldsymbol{X}_N(s)-\boldsymbol{X}^{\dagger}(s)\right) ds. \label{eqn::X_n with taylor F} \end{eqnarray} The FCLT ensures that as the population size $N \rightarrow \infty$, $\sqrt{N}\left(\boldsymbol{X}_N(t) - \boldsymbol{X}^{\dagger}(t)\right)$ converges in distribution to some zero-mean Gaussian process \begin{eqnarray} \boldsymbol{V}(t) &=& \int_{0}^{t} \partial \boldsymbol{F}\left(\boldsymbol{X}^{\dagger}(s)\right)\boldsymbol{V}(s)ds + \sum_{i=1}^{n} \boldsymbol{R}_i B_i\left(\int_{0}^{t} \lambda^{i}_{\bs{\theta}}\left(\boldsymbol{X}^{\dagger}(s)\right) ds \right). \label{eqn::V integral} \end{eqnarray} We define $\text{Q}\left( \boldsymbol{X}^{\dagger}(t) \right)$ to be the $d$ by $n$ matrix with its $i^{th}$ column given by $\boldsymbol{q}_i\left( \boldsymbol{X}^{\dagger}(t) \right) = \boldsymbol{R}_i\sqrt{\lambda^{i}_{\bs{\theta}}\left(\boldsymbol{X}^{\dagger}(t) \right)}$. We differentiate \eqref{eqn::V integral} to obtain the system of linear SDEs with time-varying coefficients \begin{eqnarray} d\boldsymbol{V}(t) = \partial \boldsymbol{F}\left(\boldsymbol{X}^{\dagger}(t)\right)\boldsymbol{V}(t)dt + \text{Q}\left( \boldsymbol{X}^{\dagger}(t) \right) d\boldsymbol{B}(t), \label{eqn::dV Linear Sigma} \end{eqnarray} where $d\boldsymbol{B}(t) = \left(dB_1(t), dB_2(t),...,dB_d(t) \right)^{\prime}$. We then approximate the finite sample process by \begin{eqnarray} \boldsymbol{X}_N(t) \approx \boldsymbol{X}^{\dagger}(t) + \frac{1}{\sqrt{N}} \boldsymbol{V}(t). \label{eqn::Approx X by V} \end{eqnarray} We note that the approximate distribution in \eqref{eqn::Approx X by V}, which was first constructed by \cite{kurtz1978strong}, is centered about the solution to the system of ODEs $\boldsymbol{X}^{\dagger}(t)$ in \eqref{eqn::X det diff} (i.e. $\mathbb{E}\left(\boldsymbol{X}_N(t)\right)=\boldsymbol{X}^{\dagger}(t)$). From \eqref{eqn::dV Linear Sigma}, we observe that $\boldsymbol{V}(t)$ is a zero-mean Gaussian process, whose covariance depends only on the deterministic solution $\boldsymbol{X}^{\dagger}(t)$. All past work on this approximation has focused on simulation rather than inference \citep{kurtz1981approximation,baxendale2011sustained,fricks2018stochastic}. In this work we develop methods for statistical inference on $\boldsymbol{\theta}$ using the approximation \eqref{eqn::Approx X by V}. To this end, we construct the covariance for the JGDLA as a function of the solution to the deterministic system in \eqref{eqn::X det diff}. To our knowledge, we are the first to construct this covariance and use it for statistical inference. \subsection{Deterministic Covariance Structures} \label{section::Cov} Here we define the joint Gaussian likelihood of the JGDLA. To do so, we first solve for the covariance of $\boldsymbol{V}(t)$ by solving \eqref{eqn::dV Linear Sigma}. While this covariance cannot, in general, be obtained analytically, we develop a novel form for the covariance which can easily be approximated numerically. To do so, we propose a separable solution of the form \begin{eqnarray} \boldsymbol{V}(t) = U(t)\boldsymbol{Y}(t), \boldsymbol{V}(0) = \boldsymbol{0}, \label{eqn::V seperable} \end{eqnarray} where $U(t)$ is a $d$ by $d$ matrix and $\boldsymbol{Y}(t)$ is a $d$-dimensional Gaussian process. The solution to \eqref{eqn::V seperable} (see Appendix \ref{appendix::Solving for V(t)} for details) requires \begin{eqnarray} dU(t) &=& \partial \boldsymbol{F}\left(\boldsymbol{X}^{\dagger}(t)\right)U(t), U(0) = \mathbb{I}_{d \times d}, \label{eqn::dU} \\ \boldsymbol{Y}(t) &=& \int_{0}^{t} U^{-1}(s)\text{Q}\left( \boldsymbol{X}^{\dagger}(s) \right) d\boldsymbol{B}(s), \boldsymbol{Y}(0) = \boldsymbol{0}, \label{eqn::Y} \end{eqnarray} where $\partial \boldsymbol{F}\left(\boldsymbol{X}^{\dagger}(t)\right)$ and $Q\left(\boldsymbol{X}^{\dagger}(t)\right)$ are defined in \eqref{eqn::dV Linear Sigma}, and are respectively a $d$ by $d$ matrix of partial derivatives of $\boldsymbol{F}\left(\boldsymbol{X}^{\dagger}(t)\right)$ and a $d$ by $n$ matrix with columns $\boldsymbol{q}_i\left(\boldsymbol{X}^{\dagger}(t)\right) = \boldsymbol{R}_i \sqrt{\lambda_{\boldsymbol{\theta}}^i\left(\boldsymbol{X}^{\dagger}(t)\right)}$. An exact solution to \eqref{eqn::dU} does not exist unless $\partial \boldsymbol{F}\left(\boldsymbol{X}^{\dagger}(t)\right)$ is constant or commutes. For cases in which $\partial \boldsymbol{F}\left(\boldsymbol{X}^{\dagger}(t)\right)$ is not constant and does not commute, \eqref{eqn::dU} is a system of time inhomogeneous linear differential equations that must be solved numerically. We obtain an approximate solution to \eqref{eqn::dU} by first solving the deterministic system in \eqref{eqn::X det diff} for $\boldsymbol{X}^{\dagger}(t)$, then numerically solving for $U(t)$ in \eqref{eqn::dU}. Since $\boldsymbol{V}(t)$ is a zero-mean Gaussian process, the covariance of $\boldsymbol{V}(t)$ is a linear transformation of the covariance of $\boldsymbol{Y}(t)$. We define the covariance of the zero-mean process $\boldsymbol{Y}(t)$ and obtain the covariance of $\boldsymbol{V}(t)$ by matrix multiplication. For each $i = 1,2,...,n$, we define the $d$-dimensional vectors $\boldsymbol{a}_i(t) = \left( a_{i1}(t),a_{i2}(t),...,a_{id}(t) \right)^{\prime} = U^{-1}(t)\boldsymbol{R}_i$. Then from \eqref{eqn::Y}, each component of $\boldsymbol{Y}(t)$ is \begin{eqnarray} Y_j(t) = \sum_{i=1}^{n} \int_{0}^{t} a_{ij}(s) \sqrt{\lambda^{i}_{\bs{\theta}}\left( \boldsymbol{X}^{\dagger}(s) \right) } dB_i(s). \label{eqn::Y_j} \end{eqnarray} It follows from \eqref{eqn::Y_j} that \begin{equation} Cov\left( Y_j(t),Y_k(t) \right) = \begin{cases} \sum_{i=1}^{n} \int_{0}^{t} a_{ij}^2(s) \lambda^{i}_{\bs{\theta}}\left( \boldsymbol{X}^{\dagger}(s) \right)ds, & j = k \\ \sum_{i=1}^{n} \int_{0}^{t} a_{ij}(s)a_{ik}(s) \lambda^{i}_{\bs{\theta}}\left( \boldsymbol{X}^{\dagger}(s) \right)ds, & j \neq k \end{cases}. \label{eqn::Cov Y} \end{equation} The covariance of $\boldsymbol{V}(t)$ is then given by \begin{eqnarray} Cov(\boldsymbol{V}(t)) = Cov(U(t)\boldsymbol{Y}(t)) = U(t) Cov(\boldsymbol{Y}(t)) U^{\prime}(t). \label{eqn::Cov V} \end{eqnarray} It follows from \eqref{eqn::Cov V} that for $s < t$, \begin{eqnarray} Cov\left( \boldsymbol{X}_N(s), \boldsymbol{X}_N(t) \right) = \frac{1}{N} U(s) Cov(\boldsymbol{Y}(s)) U^{\prime}(t). \label{eqn::Cov X_N} \end{eqnarray} We use the approximation in \eqref{eqn::Approx X by V} and \eqref{eqn::Cov X_N} to construct a joint Gaussian likelihood for observed time points $t_1,t_2,t_3,..,t_T$. Define observations of the Markov population model $\boldsymbol{X}_N = \left(\boldsymbol{X}_N(t_1),\boldsymbol{X}_N(t_2),...,\boldsymbol{X}_N(t_T)\right)^{\prime}$ and the ODE solution for a given $\boldsymbol{\theta}$ as $\boldsymbol{X}^{\dagger} = \left(\boldsymbol{X}^{\dagger}(t_1),\boldsymbol{X}^{\dagger}(t_2),...,\boldsymbol{X}^{\dagger}(t_T)\right)^{\prime}$. Let \begin{equation} \Sigma_Y = \begin{bmatrix} Cov(\boldsymbol{Y}(t_1)) & Cov(\boldsymbol{Y}(t_2)) & ... & Cov(\boldsymbol{Y}(t_T)) \\ Cov(\boldsymbol{Y}(t_1)) & Cov(\boldsymbol{Y}(t_2)) & ... & Cov(\boldsymbol{Y}(t_T)) \\ \vdots & \vdots & ... & \vdots \\ Cov(\boldsymbol{Y}(t_1)) & Cov(\boldsymbol{Y}(t_2)) & ... & Cov(\boldsymbol{Y}(t_T)) \end{bmatrix}, \nt \end{equation} and \begin{equation} U = \begin{bmatrix} U(t_1) & U(t_1) & ... & U(t_1) \\ U(t_2) & U(t_2) & ... & U(t_2) \\ \vdots & \vdots & ... & \vdots \\ U(t_T) & U(t_T) & ... & U(t_T) \end{bmatrix}. \nt \end{equation} The resulting JGDLA covariance is \begin{equation} \Sigma^{\dagger}_{\boldsymbol{\theta}} = \frac{1}{N} U * \Sigma_Y * U^{\prime}, \label{eqn::Sigma Dagger} \end{equation} where $``*"$ denotes element-wise multiplication. Our novel JGDLA likelihood is then given by \begin{equation} \pi\left(\boldsymbol{X}_N|\boldsymbol{\theta},\boldsymbol{X}^{\dagger} \right) \sim N\left(\boldsymbol{X}^{\dagger}, \Sigma^{\dagger}_{\boldsymbol{\theta}} \right). \label{eqn::JGDLA likelihood} \end{equation} From \eqref{eqn::JGDLA likelihood}, we see that JGDLA likelihood evaluations rely solely on solutions to a deterministic system. In summary, the JGDLA is obtained by the following procedure. For a set of parameters $\boldsymbol{\theta}$, \begin{enumerate} \item Solve the system of ODEs in \eqref{eqn::X det diff} for $\boldsymbol{X}^{\dagger}(t)$. \item Solve equation \eqref{eqn::dU} for $U(t)$. \item Solve the integrals in \eqref{eqn::Cov Y} at all observed time points to construct $\Sigma_Y$. \item Construct $\Sigma^{\dagger}_{\boldsymbol{\theta}}$ in \eqref{eqn::Sigma Dagger}. \item Evaluate joint likelihood $\pi\left(\boldsymbol{X}_N|\boldsymbol{\theta},\boldsymbol{X}^{\dagger} \right)$ given in \eqref{eqn::JGDLA likelihood}. \end{enumerate} We note that the integrals involved in the algorithm described above are all deterministic. The integrals are solved numerically, but do not require stochastic infill. Further, predictions at unobserved time points can be obtained via conditional predictive normal distributions. Thus, the JGDLA provides a framework for inference based on the approximate joint likelihood \eqref{eqn::JGDLA likelihood} of all observed data which relies solely on the solution to a deterministic system. \section{Simulation Study} \label{section::Simulation Study} In this section we formulate the stochastic SIR model directly from its popular deterministic analogue. We show that the JGDLA offerers improved predictive power in comparison to the Euler-Maruyama scheme of Section \ref{section::Euler-Maruyama Approximation}. \subsection{The Stochastic SIR Model} Deterministic SIR population models are widely used in epidemiology to model disease outbreaks \citep{keeling2011modeling}. The SIR model tracks the deterministic proportions of susceptible $S^{\dagger}(t)$, infected $I^{\dagger}(t)$, and recovered $R^{\dagger}(t)$ individuals in a closed population of size $N$. In large populations, systems of ODEs are commonly used to model disease dynamics \citep{keeling2011modeling}. The differential equations governing the deterministic system are given by \begin{eqnarray} \frac{d}{dt} S^{\dagger}(t) &=& -\beta S^{\dagger}(t)I^{\dagger}(t), \label{eqn::S deterministic} \\ \frac{d}{dt} I^{\dagger}(t) &=& \beta S^{\dagger}(t)I^{\dagger}(t) - \gamma I^{\dagger}(t), \label{eqn::I deterministic} \\ \frac{d}{dt} R^{\dagger}(t) &=& \gamma I^{\dagger}(t), \label{eqn::R deterministic} \end{eqnarray} where $1 = I^{\dagger}(t) + S^{\dagger}(t) + R^{\dagger}(t)$ due to the assumption of a constant population size. Note that since $R^{\dagger}(t) = 1 - I^{\dagger}(t) - S^{\dagger}(t)$, the system can be reduced to equations \eqref{eqn::S deterministic} and \eqref{eqn::I deterministic}. The two unknown parameters $\boldsymbol{\theta} = (\beta,\gamma)$, are the direct transmission rate $\beta \in (0,\infty)$ and the recovery rate $\gamma \in (0,\infty)$. We construct the stochastic SIR model from the system of ODEs by defining the reaction vectors and their corresponding deterministic rates. Recall the two reactions that may occur previously defined in Section \ref{section::Markov Population Models}, a susceptible individual becomes infected $\boldsymbol{R}_1 = (-1, 1)^{\prime}$, or an infected recovers $\boldsymbol{R}_2 = (0, -1)^{\prime}$. We denote the deterministic class proportions $\boldsymbol{X}^{\dagger}(t) = \left(S^{\dagger}(t), I^{\dagger}(t)\right)^{\prime}$, and define the reaction rates \begin{eqnarray} \lambda^{1}_{\bs{\theta}}\left(\boldsymbol{X}^{\dagger}(t)\right) &=& \beta S^{\dagger}(t) I^{\dagger}(t), \label{eqn::Lambda_1 SIR} \\ \lambda^{2}_{\bs{\theta}}\left(\boldsymbol{X}^{\dagger}(t)\right) &=& \gamma I^{\dagger}(t). \label{eqn::Lambda_2 SIR} \end{eqnarray} We let $\boldsymbol{X}_N(t) = \left(S_N(t),I_N(t)\right)^{\prime}$ denote the random proportions of susceptible and infected individuals at time $t$. We obtain the stochastic SIR model by swapping $\boldsymbol{X}_N(t)$ and $\boldsymbol{X}^{\dagger}(t)$ in (\ref{eqn::Lambda_1 SIR}--\ref{eqn::Lambda_2 SIR}). We use the Gillespie algorithm \citep{gillespie1977exact} to generate four datasets with $\beta = 0.50, \gamma = 0.15,$ and initial conditions $S_N(0) = 0.95$, and $I_N(0) = 0.05$ for population sizes $N = 100, 300, 500, 1000$ over the time interval $(0,30]$ (see Figure \ref{figure::SIR_Sim_Data}). We denote the observed times as $T^{obs} = \{5,10,15,20,25,30\}$. We will compare the models in terms on mean absolute prediction error (MAPE) on the proportions of infected for each approximation method at the infill time points $T^{pred} = \{1,2,3,4,6,7,8,9,...,26,27,28,29\}$. Note that our partition is denoted $t_0 = 0, t_1 = 1, t_2 = 2,...,t_{30} = 30$. \begin{figure}[H] \centering \includegraphics{SIR_Sim_Data.pdf} \caption{Plot of the infected $I_N(t)$ (red) and susceptible $S_N(t)$ (blue) proportions for $N = 100, 300, 500$, and $1000$ generated from a stochastic SIR model with $\beta = 0.5, \gamma = 0.15, S_N(0) = 0.95$, and $I_N(0)=0.05$.} \label{figure::SIR_Sim_Data} \end{figure} \subsection{Models and Model Fitting} We first fit the simulated data to the fully deterministic system as a point of comparison for the stochastic models. The fully deterministic model is fit with likelihood given by \begin{eqnarray} \pi{ \left(\boldsymbol{X}^{obs}_N(t) | \boldsymbol{X}^{\dagger}(t),\sigma \right)} \sim N\left( \boldsymbol{X}^{\dagger}(t), \sigma^2 \mathbb{I}_{2 \times 2} \right). \label{eqn::Sim Study Det Model} \end{eqnarray} Maximum likelihood estimates from the deterministic SIR model likelihood in \eqref{eqn::Sim Study Det Model}, with mean $\boldsymbol{X}^{\dagger}(t)$ being the numerical optimization solution of \eqref{eqn::X det diff} and a function of $\boldsymbol{\theta} = (\beta,\gamma)$, which are estimated. We use \textit{ode} from the \textit{deSolve} package in \textit{R} with a time step of 0.1 to solve for $\boldsymbol{X}^{\dagger}(t)$ and obtain maximum likelihood estimates for $(\sigma,\beta,\gamma)$ using the built-in optimizer \textit{optim} in $R$. We follow the summary procedure in Section \ref{section::Cov} to obtain the JGDLA likelihood for $\pi{\left(\boldsymbol{X}^{obs}_N|\boldsymbol{X}^{\dagger},\boldsymbol{\theta}\right)}$, where $\boldsymbol{X}^{obs}_N = \left(\boldsymbol{X}^{obs}_N(5),\boldsymbol{X}^{obs}_N(10),...,\boldsymbol{X}^{obs}_N(30)\right)^{\prime}$ and $\boldsymbol{X}^{\dagger} = \left(\boldsymbol{X}^{\dagger}(5),\boldsymbol{X}^{\dagger}(10),...,\boldsymbol{X}^{\dagger}(30)\right)^{\prime}$. We use \textit{ode} from the \textit{deSolve} package in \textit{R} with a time step of 0.1 to solve all the integrals required to form the JGDLA likelihood. We again obtain maximum likelihood estimates for the JGDLA model \textit{optim} in $R$. Details on the construction of the JGDLA are contained in Appendix \ref{appendix::JGDLA for SIR}. For comparison, we also make inference based on an Euler-Maruyama approximation. We implement the Euler-Maruyama scheme (EM) for the stochastic SIR model with a time-lag of $\triangle t = 1$ by defining \[ \text{G}_{\boldsymbol{\theta}}\left( \boldsymbol{X}_N(t) \right) = \begin{bmatrix} \sqrt{ \frac{\lambda^{1}_{\bs{\theta}}\left(\boldsymbol{X}_N(t)\right)}{N} } & 0 \\ -\sqrt{ \frac{\lambda^{1}_{\bs{\theta}}\left(\boldsymbol{X}_N(t)\right)}{N} } & \sqrt{ \frac{\lambda^{1}_{\bs{\theta}}\left(\boldsymbol{X}_N(t)\right)}{N}+ \frac{\lambda^2_{\bs{\theta}}\left(\boldsymbol{X}_N(t)\right)}{N} } \end{bmatrix}, \] and $\boldsymbol{\mu}_{\boldsymbol{\theta}}\left( \boldsymbol{X}_N(t) \right) = \left(-\lambda^{1}_{\bs{\theta}}\left( \boldsymbol{X}_N(t) \right), \lambda^{1}_{\bs{\theta}}\left( \boldsymbol{X}_N(t) \right) - \lambda^2_{\bs{\theta}}\left(\boldsymbol{X}_N(t)\right) \right)'$ in \eqref{eqn::Conditional Euler} of Section \ref{section::Euler-Maruyama Approximation}. We also consider the independent Euler-Maruyama (EM Ind) model, which is obtained by setting the off-diagonal elements in $\text{G}_{\boldsymbol{\theta}}\left( \boldsymbol{X}_N(t) \right) $ of \eqref{eqn::Conditional Euler} to be zero. Taking $\text{G}_{\boldsymbol{\theta}}\left( \boldsymbol{X}_N(t) \right)$ to be diagonal allows for fast inversions and likelihood evaluations, and is common in some settings \citep{wikle2010general}. Both Euler-Maruyama schemes require 48 latent states to be estimated at $T^{pred}$. We fit both Euler-Maruyama schemes via MCMC. We specify $iid$ half normal scale 1 priors for $\pi{\left( \beta\right)}$ and $\pi{\left( \gamma \right) }$, giving $\pi{\left(\boldsymbol{\theta}\right)} = \pi{\left( \beta\right)} \pi{\left( \gamma \right) }$. Let $\boldsymbol{X}^{pred}$ denote the collection of $\boldsymbol{X}_N(t)$ at infill time points $T^{pred}$. We estimate the latent infill states by drawing all-at-once Metropolis-Hasting samples from the conditional distribution \begin{eqnarray} \pi{\left( \boldsymbol{X}^{pred},\boldsymbol{\theta}|\boldsymbol{X},\boldsymbol{X}_N(0)\right)} \propto \prod_{i=1}^{30} \pi{\left( \boldsymbol{X}_N\left( t_{i}\right) | \boldsymbol{X}_N\left( t_{i-1}\right), \boldsymbol{\theta} \right)} \pi{\left(\boldsymbol{\theta}\right)}, \label{eqn::conditional posterior Euler} \end{eqnarray} where $\pi{\left( \boldsymbol{X}_N\left( t_{i}\right) | \boldsymbol{X}_N\left( t_{i-1}\right), \boldsymbol{\theta} \right)}$ is the conditional normal likelihood obtained from the Euler-Maruyama scheme in \eqref{eqn::Conditional Euler}. We draw 300,000 burn-in states from \eqref{eqn::conditional posterior Euler} to allow for the Markov chain to reach a stationary distribution and store an additional 100,000 post burn-in states to perform the analysis. \subsection{Simulation Study Discussion} These three approaches to inference are all compared in terms of mean absolute prediction error (MAPE) on the predicted infected. The MAPE at the 24 infill time points for the infected is computed as $MAPE = \sum_{t \in T^{pred}} | I_N(t) - I^{truth}_N(t)| / 24 $. To compute the MAPE for the JGDLA, we take the expectation of the conditional predictive multivariate normal distribution for $\boldsymbol{X}^{pred}$ conditioned on $\boldsymbol{X}^{obs}_N$ and the maximum likelihood estimates for $\bs{\theta}$. For the Euler-Maruyama schemes, we compute the MAPE as $\sum_{t \in T^{pred}} \left(\sum_{l=1}^{L} |I_N^{(l)}(t) - I_N^{true}(t)| / L\right)/24$, where $\boldsymbol{X}^{(l)}(t) = \left( S_N^{(l)}(t), I_N^{(l)}(t) \right)^{\prime}$ represents a post burn-in Metropolis hasting sample from the posterior infill distribution. The MAPE for the ODE fit takes the ODE solution $\boldsymbol{X}^{\dagger}(t)$ for the maximum likelihood estimates of $\boldsymbol{\theta}$ as the predicted value at the infill locations. We summarize the MAPE for each approximation method in Table \ref{table::Simulation Study MAPE} and note that all 95\% credible/confidence intervals contained the true value of $\boldsymbol{\theta}$. We see that the JGDLA offers improved predictive power in comparison to both Euler-Maruyama approximations and the deterministic fits. We note that the Euler-Maruyama scheme can be improved by refining the time discretization. However, lattice refinement requires all latent states at new infill locations to be inferred. For example, the Euler-Maruyama scheme required 48 latent states to perform inference with $\triangle t = 1$ in the SIR example. No stochastic infill was required to obtain the JGDLA model fit. The results of this study suggest that the JGDLA offers an improved model fit in comparison to the Euler-Maruyama scheme considered, and does not require latent states to be stochastically estimated. Inference under the JGDLA is straightforward, as it allows for direct evaluation of the joint likelihood of the data. \begin{table}[H] \centering \begin{tabular}{lllll} N & EM & EM Ind & JGDLA & ODE \\ \hline $100$ & 0.02389 & 0.02498 & \textbf{0.01464} & 0.01967\\ $300$ & 0.01484 & 0.01627 & \textbf{0.01252} & 0.02327 \\ $500$ & 0.00863 & 0.00968 & \textbf{0.00612} & 0.00678 \\ $1,000$ & 0.00679 & 0.00758 & \textbf{0.00456} & 0.00868 \end{tabular} \caption{MAPE for the predicted infected proportions for the four models; Euler-Maruyama (EM), Euler-Maruyama with off-diagonal covariance terms set to 0 (EM Ind), JGDLA, and the ODE system fitted to the four simulated data sets with $N=100,300,500,1000$.} \label{table::Simulation Study MAPE} \end{table} \section{Data Analysis: COVID Cruise Ship} \label{section::Covid Data Example} On 5 February 2020 a cruise ship hosting 3711 people docked for a 2-week quarantine in Yokohama, Japan after a passenger tested positive for the coronavirus disease (COVID-19) \citep{mizumoto2020estimating}. Random testing of passengers and crew members began on February $5^{th}$ and continued through February $20^{th}$. We note that on February $11^{th}$ and $14^{th}$ no testing occurred and denote the fourteen observed times $T^{obs} = \{1,2,3,..,6,8,9,11,12,...,16\}$. The number of tests administered per day $n_t$, positive tests per day $y_t$, and total number of individuals remaining on the ship are shown in Table \ref{table::Covid Data}. Once exposed to COVID, susceptible individuals experience an incubation prior to becoming infectious \citep{chen2020mathematical}. To account for the incubation period, we fit a stochastic susceptible-exposed-infected-removed (SEIR) model to the Princess Diamond cruise ship COVID-19 outbreak data set. We use the JGDLA to form a joint distribution for the latent states of the SEIR model. We specify the system of ODEs governing the SEIR model \begin{eqnarray} \frac{d}{dt}S^{\dagger}(t) &=& -\beta I^{\dagger}(t)S^{\dagger}(t) - \mu_S(t)S^{\dagger}(t), \nt \\ \frac{d}{dt}E^{\dagger}(t) &=& \beta I^{\dagger}(t)S^{\dagger}(t) - \alpha E^{\dagger}(t), \nt \\ \frac{d}{dt}I^{\dagger}(t) &=& \alpha E^{\dagger}(t) - \gamma I^{\dagger}(t), \nt \\ \frac{d}{dt}R^{\dagger}(t) &=& \gamma I^{\dagger}(t) + \mu_S(t) S^{\dagger}(t), \nt \end{eqnarray} where $1=I^{\dagger}(t)+S^{\dagger}(t)+E^{\dagger}(t)+R^{\dagger}(t)$. We note that the system contains three compartments $\boldsymbol{X}^{\dagger} = \left(S^{\dagger}(t), E^{\dagger}(t), I^{\dagger}(t)\right)^{\prime}$, since $R^{\dagger}(t) = 1 - S^{\dagger}(t) - E^{\dagger}(t) - I^{\dagger}(t)$. The contact rate $\beta$, incubation rate $\alpha$, and the recovery rate $\gamma$ all have support on the positive reals. Let $\boldsymbol{X}^{\dagger} = \left(\boldsymbol{X}^{\dagger}(1),...,\boldsymbol{X}^{\dagger}(6),\boldsymbol{X}^{\dagger}(8),\boldsymbol{X}^{\dagger}(9),\boldsymbol{X}^{\dagger}(11),...\boldsymbol{X}^{\dagger}(16)\right)^{\prime}$ denote the ODE solution at times $T^{obs}$. We build a joint distribution for the latent proportions $\boldsymbol{X}_N(t) = \left( S_N(t), E_N(t), I_N(t) \right)^{\prime}$ using JGDLA at the fourteen observed time points $\boldsymbol{X}_N = \left(\boldsymbol{X}_N(1),...,\boldsymbol{X}_N(6),\boldsymbol{X}_N(8),\boldsymbol{X}_N(9),\boldsymbol{X}_N(11),...\boldsymbol{X}_N(16)\right)^{\prime}$ centered at $\boldsymbol{X}^{\dagger}$. We estimate $\boldsymbol{\theta} = (\beta,\alpha,\gamma)$ and the initial conditions $\boldsymbol{X}_N(0) = \left( S_N(0), E_N(0), I_N(0) \right)^{\prime}$, where $t=0$ denotes February $4^{th}$. We account for the disembarkment of susceptible passengers with the inclusion of a fixed time-varying rate $\alpha_S(t)$ estimated from passenger records. We model the number of observed seropositive individuals on day \textit{t} as \begin{eqnarray} y_t \sim Binom\left(n_t, P(t) = \frac{I_N(t)}{I_N(t)+S_N(t)+E_N(t)} \right). \label{eqn::Covid Likelihood} \end{eqnarray} We obtain the stochastic model from the deterministic SEIR by defining the four reaction vectors; a susceptible becomes exposed $\boldsymbol{R}_1 = \left(-1, 1, 0 \right)^{\prime}$, a susceptible disembarks from the ship $\boldsymbol{R}_2 = (-1,0,0)^{\prime}$, an exposed individual becomes infected $\boldsymbol{R}_3 = (0,-1,1)^{\prime}$, or an infected individual recovers $\boldsymbol{R}_4 = (0,0,-1)^{\prime}$. We define the corresponding reaction rates $\lambda^1_{\bs{\theta}}\left(\boldsymbol{X}^{\dagger}(t)\right) = \beta I^{\dagger}(t)S^{\dagger}(t)$, $\lambda^2_{\bs{\theta}}\left( \boldsymbol{X}^{\dagger}(t) \right) = \mu_S(t) S^{\dagger}(t)$, $\lambda^3_{\bs{\theta}}\left( \boldsymbol{X}^{\dagger}(t) \right) = \alpha E^{\dagger}(t)$, and $\lambda^4_{\bs{\theta}}\left( \boldsymbol{X}^{\dagger}(t) \right) = \gamma I^{\dagger}(t)$. We elect to take a Bayesian approach to inference and fit the model via MCMC. We place priors of $\beta,\alpha \stackrel{iid}{\sim} TN_{(0,\infty)}\left(0,15^2\right)$, $\gamma \sim TN_{(0,\infty)}\left(0,0.3^2\right)$, $S_N(0) \sim TN_{(0,1)}\left(0,0.3^2\right)$, and $I_N(0) \sim TN_{(0,1)}\left(0,0.1^2\right)$, where $TN_{(a,b)}(c,d)$ denotes a truncated normal distribution with support $(a,b)$, center $c$, and scale parameter $d$. We draw 100,000 all-at-once Metropolis Hastings samples of $\boldsymbol{\theta}$ and $\boldsymbol{X}_N(0)$. We discard 10,000 samples as burn-in states and use the remaining 90,000 samples to perform the analysis. The likelihood in \eqref{eqn::Covid Likelihood} must be approximated due to its dependence on the latent states $\boldsymbol{X}_N$. We perform a Monte Carlo approximation of \eqref{eqn::Covid Likelihood} by drawing 1,000 samples from the JGDLA joint distribution $\boldsymbol{X}_N^{(l)} \sim \pi{\left( \boldsymbol{X}_N | \boldsymbol{\theta},\boldsymbol{X}^{\dagger} \right)}$, assigning $P^{(l)}(t) = I^{(l)}_N(t) / \left( I^{(l)}_N(t)+S^{(l)}_N(t)+E^{(l)}_N(t) \right)$ from the JGDLA samples, then approximating the likelihood \begin{eqnarray} \hat{\pi}{\left(\boldsymbol{y} | \boldsymbol{\theta} \right)} = \frac{1}{1000}\sum_{l=1}^{1000} \prod_{t \in T^{obs}}\pi{\left( y_t | P^{(l)}(t) \right)}. \label{eqn::MC Likelihood} \end{eqnarray} We use the approximate likelihood in \eqref{eqn::MC Likelihood} to draw all-at-once Metropolis-Hasting samples from the posterior conditional distribution $\pi{\left( \boldsymbol{\theta},\boldsymbol{X}_N(0) | \boldsymbol{y} \right)} \propto \hat{\pi}{\left(\boldsymbol{y} | \boldsymbol{\theta} \right)}\pi{\left( \boldsymbol{X}_N(0) \right)}\pi{\left(\boldsymbol{\theta}\right)}$, where $\boldsymbol{y}$ is the vector of $y_t$ at $T^{obs}$. Further details on model fitting are included in Appendix \ref{appendix::JGDLA for SEIR}. From Figure \ref{figure::Covid_Data_Fit}, we see that the posterior mean estimate for the probability of being infected captures the mean of the observed proportions well. All parameter estimates are summarized in Table \ref{table::Covid Param Ests}. We note that $\alpha$ is the rate at which individuals move from exposed to infected. Studies have found that symptoms take roughly five to six days to appear \citep{chen2020mathematical}. Our estimate is most likely lower due to the fact that several tests were administered to a small population (i.e. many were tested positive before symptoms began). We also note that the recovery/removal rate is roughly 1.14 days. This estimate is lower than the known time to recover from SARS-COV2, as individuals on the ship were not tested once found positive, and likely confined to their rooms (i.e. quarantined), and are thus functionally removed from the population, even though they are still infectious. Our stochastic SEIR model, assisted by the use of the JGDLA, allows us to understand the mean behavior of the small population of the Princess Diamond cruise ship. \begin{table}[H] \centering \begin{tabular}{lllll} t & Date (2020) & Number of Tests ($n_t$) & Positive Tests $(y_t)$ & On Ship \\ \hline 1 & 5 Feb & 31 & 10 & 3711 \\ 2 & 6 Feb & 71 & 10 & 3711 \\ 3 & 7 Feb & 171 & 41 & 3711 \\ 4 & 8 Feb & 6 & 3 & 3711 \\ 5 & 9 Feb & 57 & 6 & 3711 \\ 6 & 10 Feb & 103 & 65 & 3711 \\ 7 & 11 Feb & \textit{NA} & \textit{NA} & 3711 \\ 8 & 12 Feb & 53 & 39 & 3711 \\ 9 & 13 Feb & 221 & 44 & 3711 \\ 10 & 14 Feb &\textit{NA} & \textit{NA} & 3451 \\ 11 & 15 Feb & 217 & 67 & 3451 \\ 12 & 16 Feb & 289 & 70 & 3451 \\ 13 & 17 Feb & 504 & 99 & 3183 \\ 14 & 18 Feb & 681 & 88 & 3183 \\ 15 & 19 Feb & 607 & 79 & 3183 \\ 16 & 20 Feb & 52 & 13 & 2213 \end{tabular} \caption{Covid data} \label{table::Covid Data} \end{table} \begin{table}[H] \centering \begin{tabular}{lll} Parameter & Posterior Mean Estimate & 95\% CI \\ \hline $\beta$ & 3.108 & (1.433,5.534) \\ $\alpha$ & 0.526 & (0.422,0.691) \\ $\gamma$ & 0.876 & (0.605,1.172) \\ $S_N(0)$ & 0.545 & (0.265,0.754) \\ $I_N(0)$ & 0.088 & (0.008,0.193) \end{tabular} \caption{Posterior mean estimates and 95\% credible intervals for estimated SEIR model parameters.} \label{table::Covid Param Ests} \end{table} \begin{figure}[H] \centering \includegraphics{Covid_Data_Fit.pdf} \caption{Plot of Princess Diamond Cruise COVID-19 proportions of infected. Sample proportions estimated from Table \ref{table::Covid Data} are plotted in black. The deterministic curve for $P(t)$ fitted from the posterior mean estimate of $\boldsymbol{\theta}$ is shown in blue, with 95\% credible intervals in red.} \label{figure::Covid_Data_Fit} \end{figure} \section{Discussion} \label{section::Discussion} In this work we proposed the JGDLA as a method for approximate inference on Markov population models. We showed that the JGDLA produces a joint Gaussian distribution that relies solely on the solution to a system of ODEs. We showed that, unlike the Euler-Maruyama scheme, the JGDLA does not require stochastic infill to perform inference or predict at unobserved times. We also illustrated the connection between SDE and ODE modeling by demonstrating how to perform inference on Markov population models directly from a deterministic system in our simulation study and data analysis. There are other frameworks for approximating the joint likelihood of the data, such as particle filtering \citep{doucet2009tutorial} and iterated filtering \citep{ionides2015inference}. These methods are commonly used when the Markov population process is assumed to be unobserved. Filtering methods rely on sequentially drawing samples from the filtering and predictive distributions of the latent states. This task requires recursively defining conditional densities from a Gaussian distribution. We fit a hidden Markov model in the COVID-19 data analysis of Section \ref{section::Covid Data Example} in which the population process was unobserved. The JGDLA does not require filtering methods to approximate the likelihood. We instead performed a Monte Carlo approximation of the likelihood using samples from the JGLDA's full joint distribution for the latent states. Inference for JGDLA models is not restricted to Bayesian approaches. In Section \ref{section::Simulation Study}, we considered a directly observed population process. This allowed for maximum likelihood estimates to be obtained by optimizing the JGDLA joint Gaussian likelihood. In Section \ref{section::Covid Data Example}, the JGDLA produces a joint distribution for the latent states at the time points at which seropositive data counts were observed. Maximum likelihood estimates could have been obtained by optimization, however we elected to use MCMC and found the results to be robust to initial conditions. In summary, we have constructed the JGDLA as a new method for performing approximate inference on Markov population models. We showed that likelihood evaluations of the JGDLA depend solely on the solution of a system of ODEs. In turn, the JGDLA does not require stochastic infill to predict or perform inference. We saw the JGDLA approximation is built directly from a system of ODEs, connecting ODE and SDE modeling. We also observed that the JGDLA outperformed the Euler-Maruyama approximation in the SIR simulation study considered in Section \ref{section::Simulation Study}. In conclusion, we suggest the use of the JGDLA as a new framework for performing inference on Markov models. \bibliographystyle{Chicago}
{'timestamp': '2021-01-05T02:19:05', 'yymm': '2101', 'arxiv_id': '2101.00491', 'language': 'en', 'url': 'https://arxiv.org/abs/2101.00491'}
arxiv
\section{Introduction} Emotions provide motivation for many aspects of human behavior. To be able to understand and predict human actions, artificial agents must be able to identify, comprehend, and reason about human emotions. Different formal models of human emotions have been studied in AI literature. Doyle, Shoham, and Wellman propose a logic of relative desire~\cite{dsw91ismis}. Lang, Van Der Torre, and Weydert introduce utilitarian desires~\cite{lvw02aamas}. Meyer states logical principles aiming at capturing anger and fear~\cite{m04ecai}. Steunebrink, Dastani, and Meyer expand this work to hope~\cite{sdm07aaai}. Adam, Herzig, and Longin propose formal definitions of hope, fear, relief, disappointment, resentment, gloating, pride, shame, admiration, reproach, gratification, remorse, gratitude, and anger~\cite{ahl09synthese}. Lorini and Schwarzentruber define regret and elation~\cite{ls11ai}. The focus of this article is on happiness and sadness. These notions have long been studied in literature on philosophy~\cite{s11ijw,f19ijw,b10yup,a10dup}, psychology~\cite{a13routledge,sed05pid}, and economics~\cite{f10mit,bp05oup}. Note that happiness/sadness are vague terms that have multiple meanings that overlap with several other terms such as joy/distress and elation/disappointment\footnote{For example, Merriam-Webster dictionary lists joy as synonym for happiness and happiness as synonym for joy. At the same time, thesaurus.com lists elation as synonym for joy and joy as synonym for elation.}. Two approaches to capturing happiness and sadness in formal logical systems have been proposed. The first approach is based on Ortony, Clore, and Collins' definitions of joy and distress (the capitalization is original): \begin{quote} \dots we shall often use the terms ``joy'' and ``distress'' as convenient shorthands for the reactions of being PLEASED ABOUT A DESIRABLE EVENT and DISPLEASED ABOUT AN UNDESIRABLE EVENT, respectively.~\cite[p.88]{occ88cup} \end{quote} Adam, Herzig, and Longin formalized these definitions. An agent feels joy about $\phi$ if she believes that $\phi$ is true and she desires $\phi$. An agent feels distress about $\phi$ if she believes $\phi$ is true, but she desires $\phi$ to be false~\cite{ahl09synthese}. Similarly, Lorini and Schwarzentruber define that an agent is elated/disappointed about $\phi$ if $\phi$ is desirable/undesirable to the agent, agent knows that $\phi$ is true, and she also knows that the others could have prevented $\phi$ from being true~\cite{ls11ai}. Although Adam, Herzig, and Longin use beliefs while Lorini and Schwarzentruber use knowledge and the latter authors also add ``could have prevented'' part, both definitions could be viewed as a variation of Ortony, Clore, and Collins' definitions of joy/distress. Meyer suggested a very different approach to defining these notions. He writes ``an agent that is happy observes that its subgoals (towards certain goals) are being achieved, and is `happy' with it''. He acknowledges, however, that this definition might be capturing only one of the forms of what people mean by happiness~\cite{m04ecai}. Note, for example, that if Pavel, the second author of this article, receives an unexpected gift from Sanaz, the first author, then he will experience ``joy'' as defined by Ortony, Clore, and Collins. However, he will not be ``happy'' as defined by Meyer because receiving such a gift has never been among Pavel's goals\footnote{Ortony, Clore, and Collins give a similar example with an unexpected inheritance from an unknown relative.}. In this article we adopt Ortony, Clore, and Collins' definitions, but we use terms happiness/sadness instead of joy/distress. While the cited above works suggest formal semantics and list formal properties of happiness and sadness, none of them gives an axiomatization of these properties. In this article we propose such an axiomatization and prove its completeness. We also show that notions of happiness and sadness in our formal system are, in some sense, dual but are not definable through each other. The rest of the article is structured as follows. First, we formally define epistemic models with preferences that serve as the foundation of our semantics of happiness and sadness. Then, we define formal syntax and semantics of our system and illustrate them with several examples. In Section~\ref{Undefinability of Sadness through Happiness section}, we show that sadness cannot be defined through happiness. In spite of this, as we show in Section~\ref{Duality of Happiness and Sadness} there is a certain duality between the properties of the happiness and sadness. We use this duality to observe that sadness can not be defined through happiness either. In Section~\ref{Axioms of Emotions}, we list the axioms of our logical system. In the section that follows, we prove its soundness. In Section~\ref{Utilitarian Emotions} and Section~\ref{Goodness-Based Emotions}, we show how utilitarian and goodness-based approaches to desires, already existing in the literature, could be adopted to happiness and sadness. In the rest of the article we prove the completeness of our logical section. The last section concludes. \section{Epistemic Models with Preferences} Throughout the article we assume a fixed countable set of agents $\mathcal{A}$ and a countable set of propositional variables. The semantics of our logical system is defined in terms of epistemic models with preferences. These models extend standard Kripke models for epistemic logic with a preference relation for each agent in set $\mathcal{A}$. \begin{definition}\label{epistemic model with preferences} A tuple $(W,\{\sim_a\}_{a\in\mathcal{A}},\{\prec_a\}_{a\in\mathcal{A}},\pi)$ is called an epistemic model with preferences if \begin{enumerate} \item $W$ is a set of epistemic worlds, \item $\sim_a$ is an ``indistinguishability'' equivalence relation on set $W$ for each agent $a\in\mathcal{A}$, \item $\prec_a$ is a strict partial order preference relation on set $W$ for each agent $a\in\mathcal{A}$, \item $\pi(p)$ is a subset of $W$ for each propositional variable $p$. \end{enumerate} \end{definition} For any two sets of epistemic worlds $U,V\subseteq W$, we write $U\prec_a V$ if $u\prec_a v$ for each world $u\in U$ and each world $v\in V$. \begin{figure}[ht] \begin{center} \scalebox{0.45}{\includegraphics{Images/example-gift.pdf}} \caption{Gift Scenario.}\label{example gift figure} \end{center} \end{figure} An example of an epistemic model with preferences is depicted in Figure~\ref{example gift figure}. It captures mentioned in the introduction scenario in which the first author of this article, Sanaz, is sending a gift to the second author, Pavel. If Pavel receives the gift, he will acknowledge it by sending back a thank you note. We assume that either the gift or the note can be lost in the mail and that there is no additional communication between the authors. This epistemic model with preferences in Figure~\ref{example gift figure} has four worlds corresponding to four different scenarios. In world $t$ Sanaz did not send the gift. In world $v$, she sent the gift, but it was lost in the mail. In world $u$, Pavel received the gift, but his note is lost in the mail. Finally, in world $w$ Pavel received the gift and Sanaz received his note. Sanaz cannot distinguish the world $v$, in which the gift is lost, from world $u$, in which the note is lost. Pavel cannot distinguish the world $t$, in which gift is not sent, from world $v$, in which the gift is lost. He also cannot distinguish the world $u$, in which the note is lost, from world $w$, in which the note is received. In the diagram, the indistinguishability relations of Sanaz and Pavel are denoted by dashed lines labeled by $s$ and $p$ respectively. Although in general, according to Definition~\ref{epistemic model with preferences}, different agents might have different preference relations between world, in this scenario we assume that Sanaz and Pavel have the same preferences. These preferences are shown in the diagram using directed edges. For example, the directed edge from world $v$ to world $t$ labeled with $s,p$ means that they both would prefer if Sanaz does not send the gift at all to the scenario when the gift is lost in the mail. \section{Syntax and Semantics} In this section we introduce the formal syntax and semantics of our logical system. Throughout the article we assume a fixed countable set of agents $\mathcal{A}$ and a fixed nonempty countable set of propositional variables. The language $\Phi$ of our logical system is defined by grammar: $$ \phi:=p\;|\;\neg\phi\;|\;\phi\to\phi\;|\;{\sf N}\phi\;|\;{\sf K}_a\phi\;|\;\H_a\phi\;|\;\S_a\phi, $$ where $p$ is a propositional variable and $a\in\mathcal{A}$ is an agent. We read formula ${\sf N}\phi$ as ``statement $\phi$ is true in each world'', formula ${\sf K}_a\phi$ as ``agent $a$ knows $\phi$'', formula $\H_a\phi$ as ``agent $a$ is happy about $\phi$'', and formula $\S_a\phi$ as ``agent $a$ is sad about $\phi$''. We assume that Boolean connectives conjunction $\wedge$, disjunction $\vee$, and biconditional $\leftrightarrow$ are defined through negation $\neg$ and implication $\to$ in the standard way. By ${\sf \overline{N}}\phi$ we denote formula $\neg{\sf N}\neg\phi$. We read ${\sf \overline{N}}\phi$ as ``statement $\phi$ is true in at least one of the worlds''. \begin{definition}\label{sat} For any world $w\in W$ of an epistemic model with preferences $(W,\{\sim_a\}_{a\in\mathcal{A}},\{\prec_a\}_{a\in\mathcal{A}},\pi)$ and any formula $\phi\in\Phi$, satisfaction relation $w\Vdash\phi$ is defined as follows: \begin{enumerate} \item $w\Vdash p$, if $w\in \pi(p)$, \item $w\Vdash\neg\phi$, if $w\nVdash\phi$, \item $w\Vdash\phi\to\psi$, if $w\nVdash\phi$ or $w\Vdash\psi$, \item $w\Vdash{\sf N}\phi$, if $u\Vdash \phi$ for each world $u\in W$, \item\label{item K} $w\Vdash{\sf K}_a\phi$, if $u\Vdash \phi$ for each world $u\in W$ such that $w\sim_a u$, \item\label{item H} $w\Vdash \H_a\phi$, if the following three conditions are satisfied: \begin{enumerate} \item $u\Vdash \phi$ for each world $u\in W$ such that $w\sim_a u$, \item for any two worlds $u,u'\in W$, if $u\nVdash\phi$ and $u'\Vdash\phi$, then $u\prec_a u'$, \item there is a world $u\in W$ such that $u\nVdash\phi$, \end{enumerate} \item $w\Vdash \S_a\phi$, if the following three conditions are satisfied: \begin{enumerate} \item $u\Vdash \phi$ for each world $u\in W$ such that $w\sim_a u$, \item for any two worlds $u,u'\in W$, if $u\Vdash\phi$ and $u'\nVdash\phi$, then $u\prec_a u'$, \item there is a world $u\in W$ such that $u\nVdash\phi$. \end{enumerate} \end{enumerate} \end{definition} Items 6 and 7 of Definition~\ref{sat} capture the notions of happiness and sadness studied in this article. Item 6 states that to be happy about a condition $\phi$, the agent must know that $\phi$ is true, the agent must prefer the worlds in which condition $\phi$ is true to those where it is false, and the condition $\phi$ must not be trivial. These three parts are captured by items 6(a), 6(b), and 6(c) of the above definition. Note that we require condition $\phi$ to be non-trivial to exclude an agent being happy about conditions that always hold in the model. Thus, for example, we believe that an agent cannot be happy that $2+2=4$. Similarly, item 7 states that an agent is sad about condition $\phi$ if she knows that $\phi$ is true, she prefers worlds in which condition $\phi$ is false to those in which condition $\phi$ is true, and condition $\phi$ is not trivial. Note that being sad is different from not being happy. In fact, later in this article we show that neither of modalities $\H$ and $\S$ is expressible through the other. We conclude this section with a technical observation that follows from Definition~\ref{sat}. \begin{lemma}\label{semantic substitution lemma} For any epistemic model with preferences $(W,\{\sim_a\}_{a\in\mathcal{A}},\{\prec_a\}_{a\in\mathcal{A}},\pi)$, any agent $a\in\mathcal{A}$, and any formulae $\phi,\psi\in\Phi$, if $w\Vdash\phi$ iff $w\Vdash\psi$ for each world $w\in W$, then \begin{enumerate} \item $w\Vdash\H_a\phi$ iff $w\Vdash\H_a \psi$ for each world $w\in W$, \item $w\Vdash\S_a\phi$ iff $w\Vdash\S_a \psi$ for each world $w\in W$. \qed \end{enumerate} \end{lemma} \section{Gift Scenario}\label{gift scenario section} In this section we illustrate Definition~\ref{sat} using the gift scenario depicted in the diagram in Figure~\ref{example gift figure}. For the benefit of the reader, we reproduce this diagram in Figure~\ref{example gift figure repeated}. \begin{figure}[ht] \begin{center} \scalebox{0.45}{\includegraphics{Images/example-gift.pdf}} \caption{Gift Scenario (repeated from Figure~\ref{example gift figure}).}\label{example gift figure repeated} \end{center} \end{figure} \begin{proposition}\label{Hp proposition} $z\Vdash \H_p(\mbox{``Pavel received a gift from Sanaz''})$ iff $z\in\{w,u\}$. \end{proposition} \begin{proof} $(\Rightarrow):$ Suppose $z\notin \{w,u\}$. Thus, $z\in \{t,v\}$. Hence, see Figure~\ref{example gift figure repeated}, $$z\nVdash \mbox{``Pavel received a gift from Sanaz''}.$$ Therefore, $z\nVdash \H_p(\mbox{``Pavel received a gift from Sanaz''})$ by item 6(a) of Definition~\ref{sat} because $z\sim_p z$. \vspace{1mm} \noindent $(\Leftarrow):$ Suppose $z\in \{w,u\}$. To show $z\Vdash \H_p(\mbox{``Pavel received a gift from Sanaz''})$, we will verify conditions (a), (b) and (c) of item~\ref{item H} of Definition~\ref{sat} separately: \vspace{1mm} \noindent{\em Condition a:} Consider any world $z'$ such that $z\sim_p z'$. To verify the condition, it suffices to show that $z'\Vdash \mbox{``Pavel received a gift from Sanaz''}$. Indeed, assumptions $z\in \{w,u\}$ and $z\sim_p z'$ imply that $z'\in \{w,u\}$, see Figure~\ref{example gift figure repeated}. Therefore, $z'\Vdash \mbox{``Pavel received a gift from Sanaz''}$, again see Figure~\ref{example gift figure repeated}. \vspace{1mm} \noindent{\em Condition b:} Consider any two epistemic worlds $x,y$ such that \begin{eqnarray} &&x\nVdash \mbox{``Pavel received a gift from Sanaz''},\label{sept12-1}\\ &&y\Vdash \mbox{``Pavel received a gift from Sanaz''}.\label{sept12-2} \end{eqnarray} To verify the condition, it suffices to show that $x\prec_p y$. Indeed, assumptions~(\ref{sept12-1}) and (\ref{sept12-2}) implies that $x\in \{t,v\}$ and $y\in \{w,u\}$, see Figure~\ref{example gift figure repeated}. Note that $\{t,v\}\prec_p \{w,u\}$, see Figure~\ref{example gift figure repeated}. Therefore, $x\prec_p y$. \vspace{1mm} \noindent{\em Condition c:} $t\nVdash \mbox{``Pavel received a gift from Sanaz''}$. \end{proof} \begin{proposition}\label{Hs proposition} $z\Vdash \H_s(\mbox{``Pavel received a gift from Sanaz''})$ iff $z\in\{w\}$. \end{proposition} \begin{proof} $(\Rightarrow):$ Suppose that $z\notin \{w\}$. Thus, either $z\in \{t\}$ or $z\in \{u,v\}$. We consider these two cases separately. \vspace{1mm} \noindent{\em Case I}: $z\in \{t\}$. Then, $z\nVdash \mbox{``Pavel received a gift from Sanaz''}$, see Figure~\ref{example gift figure repeated}. Therefore, $z\Vdash \H_s(\mbox{``Pavel received a gift from Sanaz''})$ by item 6(a) of Definition~\ref{sat} and because $z\sim_s z$. \vspace{1mm} \noindent{\em Case II}: $z\in \{u,v\}$. Then, $z\sim_s v$, see Figure~\ref{example gift figure repeated}. Note that, see again Figure~\ref{example gift figure repeated}, $v\nVdash \mbox{``Pavel received a gift from Sanaz''}$. Therefore, by item 6(a) of Definition~\ref{sat}, $z\nVdash \H_s(\mbox{``Pavel received a gift from Sanaz''})$. \vspace{1mm} \noindent$(\Leftarrow):$ To show that $w\Vdash \H_s(\mbox{``Pavel received a gift from Sanaz''})$, we verify conditions (a), (b), and (c) of item~\ref{item H} of Definition~\ref{sat}: \vspace{1mm} \noindent{\em Condition a:} Consider any world $z$ such that $w\sim_s z$. It suffices to show that $z\Vdash \mbox{``Pavel received a gift from Sanaz''}$. Indeed, assumption $w\sim_s z$ implies that $z=w$, see Figure~\ref{example gift figure repeated}. Note that $w\Vdash \mbox{``Pavel received a gift from Sanaz''}$, see again Figure~\ref{example gift figure repeated}. \vspace{1mm} \noindent{\em Condition b:} The proof is similar to the proof of {\em Condition b} in Proposition~\ref{Hp proposition}. \vspace{1mm} \noindent{\em Condition c:} $t\nVdash \mbox{``Pavel received a gift from Sanaz''}$. \end{proof} The next proposition shows that Sanaz is happy that Pavel is happy only if she gets the thank you card and, thus, she knows that he received the the gift. \begin{proposition}\label{HsHp proposition} $z\Vdash \H_s\H_p(\mbox{``Pavel received a gift from Sanaz''})$ iff $z\in\{w\}$. \end{proposition} \begin{proof} Note that $x\Vdash \mbox{``Pavel received a gift from Sanaz''}$ iff $x\in \{w,u\}$, see Figure~\ref{example gift figure repeated}. Thus, by Proposition~\ref{Hp proposition}, for any world $x\in W$, \begin{eqnarray*} &&x\Vdash \mbox{``Pavel received a gift from Sanaz''}\\ &&\hspace{5mm}\mbox{ iff } x\Vdash \H_p(\mbox{``Pavel received a gift from Sanaz''}). \end{eqnarray*} Hence, by Lemma~\ref{semantic substitution lemma}, for any world $x\in W$, \begin{eqnarray*} &&x\Vdash \H_s(\mbox{``Pavel received a gift from Sanaz''})\\ &&\hspace{5mm}\mbox{ iff } x\Vdash \H_s\H_p(\mbox{``Pavel received a gift from Sanaz''}). \end{eqnarray*} Therefore, $z\Vdash \H_s\H_p(\mbox{``Pavel received a gift from Sanaz''})$ iff $z\in\{w\}$ and Proposition~\ref{Hs proposition}. \end{proof} Note that because Sanaz never acknowledges the thank you card, Pavel does not know that Sanaz is happy. Hence, he cannot be happy that she is happy. This is captured in the next proposition. \begin{proposition}\label{HpHs proposition} $z\nVdash \H_p\H_s(\mbox{``Pavel received a gift from Sanaz''})$ for each world $z\in \{w,u,v,t\}$. \end{proposition} \begin{proof} We consider the following two cases separately: \vspace{1mm} \noindent{\em Case I}: $z\in \{w,u\}$. Then, $z\sim_p u$, see Figure~\ref{example gift figure repeated}. Note that by Proposition~\ref{Hs proposition}, $$u\nVdash \H_s(\mbox{``Pavel received a gift from Sanaz''}).$$ Therefore, $z\nVdash \H_p\H_s(\mbox{``Pavel received a gift from Sanaz''})$ by item 6(a) of Definition~\ref{sat} and the statement $z\sim_p u$. \vspace{1mm} \noindent{\em Case II}: $z\in \{v,t\}$. Then, $z\nVdash \H_s(\mbox{``Pavel received a gift from Sanaz''})$ by Proposition~\ref{Hs proposition}. Therefore, $z\nVdash \H_p\H_s(\mbox{``Pavel received a gift from Sanaz''})$ by item 6(a) of Definition~\ref{sat}. \end{proof} The proof of the next statement is similar to the proof of Proposition~\ref{HpHs proposition} except that it refers to Proposition~\ref{HsHp proposition} instead of Proposition~\ref{Hs proposition}. \begin{proposition} $z\nVdash \H_p\H_s\H_p(\mbox{``Pavel received a gift from Sanaz''})$ for each world $z\in \{w,u,v,t\}$. \qed \end{proposition} The next proposition states that Sanaz is sad about Pavel not receiving the gift only if she does not send it. Informally, this proposition is true because Sanaz cannot distinguish world $v$ in which the gift is lost from world $u$ in which the card is lost. \begin{proposition}\label{Ss proposition} $z\Vdash \S_s\neg(\mbox{``Pavel received a gift from Sanaz''})$ iff $z\in \{t\}$. \end{proposition} \begin{proof} $(\Rightarrow):$ Suppose that $z\notin \{t\}$. Thus, either $z\in \{w\}$ or $z\in\{u,v\}$. We consider the these two cases separately: \vspace{1mm} \noindent{\em Case I}: $z\in \{w\}$. Then, $z\Vdash \mbox{``Pavel received a gift from Sanaz''}$, see Figure~\ref{example gift figure repeated}. Thus, $z\nVdash \neg(\mbox{``Pavel received a gift from Sanaz''})$ by item 2 of Definition~\ref{sat}. Therefore, $z\nVdash \S_s\neg(\mbox{``Pavel received a gift from Sanaz''})$ by item 7(a) of Definition~\ref{sat}. \vspace{1mm} \noindent{\em Case II}: $z\in\{u,v\}$. Then, $z\sim_s u$, see Figure~\ref{example gift figure repeated}. Note that $$u\Vdash \mbox{``Pavel received a gift from Sanaz''},$$ see Figure~\ref{example gift figure repeated}. Thus, $u\nVdash \neg(\mbox{``Pavel received a gift from Sanaz''})$ by item 2 of Definition~\ref{sat}. Therefore, $z\nVdash \S_s\neg(\mbox{``Pavel received a gift from Sanaz''})$ by item 7(a) of Definition~\ref{sat} and the statement $z\sim_s u$. \vspace{1mm} \noindent$(\Leftarrow):$ To prove that $t\Vdash \S_s\neg(\mbox{``Pavel received a gift from Sanaz''})$, we verify conditions (a), (b), and (c) of item 7 in Definition~\ref{sat} separately: \vspace{1mm} \noindent{\em Condition a:} Consider any world $z'$ such that $t\sim_s z'$. It suffices to show that $z'\Vdash \neg(\mbox{``Pavel received a gift from Sanaz''})$. Indeed, note that $$t\nVdash (\mbox{``Pavel received a gift from Sanaz''}),$$ see Figure~\ref{example gift figure repeated}. Then, $t\Vdash \neg(\mbox{``Pavel received a gift from Sanaz''})$ by item 2 of Definition~\ref{sat}. Also note that the assumption $t\sim_s z'$ implies that $t=z'$, see Figure~\ref{example gift figure repeated}. Therefore, $z'\Vdash \neg(\mbox{``Pavel received a gift from Sanaz''})$. \vspace{1mm} \noindent{\em Condition b:} Consider any two epistemic worlds $x,y$ such that \begin{eqnarray*} &&x\Vdash \neg(\mbox{``Pavel received a gift from Sanaz''}),\\ &&y\nVdash \neg(\mbox{``Pavel received a gift from Sanaz''}). \end{eqnarray*} To verify the condition, it suffices to show that $x\prec_s y$. Indeed, by item 2 of Definition~\ref{sat}, \begin{eqnarray*} &&x\nVdash \mbox{``Pavel received a gift from Sanaz''},\\ &&y\Vdash \mbox{``Pavel received a gift from Sanaz''}. \end{eqnarray*} Thus, $x\in \{t,v\}$ and $y\in \{w,u\}$, see Figure~\ref{example gift figure repeated}. Note that $\{t,v\}\prec_s \{w,u\}$, see also Figure~\ref{example gift figure repeated}. Therefore, $x\prec_s y$. \vspace{1mm} \noindent{\em Condition c:} Note that $w\Vdash \mbox{``Pavel received a gift from Sanaz''}$. Therefore, $w\nVdash \neg(\mbox{``Pavel received a gift from Sanaz''})$ by item 2 of Definition~\ref{sat}. \end{proof} By Proposition~\ref{Ss proposition}, Sanaz is sad about Pavel not receiving the gift only if she does not send it. Since Pavel cannot distinguish world $t$ in which the gift is sent from world $v$ in which it is lost, Pavel cannot know that Sanaz is sad. This is formally captured in the next proposition. \begin{proposition} $z\nVdash {\sf K}_p\S_s\neg(\mbox{``Pavel received a gift from Sanaz''})$ for each world $z\in \{w,u,t,v\}$. \end{proposition} \begin{proof} We consider the following two cases separately: \vspace{1mm} \noindent{\em Case I:} $z\in\{w,u\}$. Then, $z\nVdash \S_s\neg(\mbox{``Pavel received a gift from Sanaz''})$ by Proposition~\ref{Ss proposition}. Therefore, $z\nVdash {\sf K}_p\S_s\neg(\mbox{``Pavel received a gift from Sanaz''})$ by item 5 of Definition~\ref{sat}. \vspace{1mm} \noindent{\em Case II:} $z\in\{t,v\}$. Then, $z\sim_p v$, see Figure~\ref{example gift figure repeated}. Note that $$v\nVdash \S_s\neg(\mbox{``Pavel received a gift from Sanaz''})$$ by Proposition~\ref{Ss proposition}. Therefore, $z\nVdash {\sf K}_p\S_s\neg(\mbox{``Pavel received a gift from Sanaz''})$ by item 5 of Definition~\ref{sat} and the statement $z\sim_p v$. \end{proof} \begin{proposition}\label{Sp proposition} $z\Vdash \S_p\neg(\mbox{``Pavel received a gift from Sanaz''})$ iff $z\in \{v,t\}$. \end{proposition} \begin{proof} $(\Rightarrow):$ Suppose that $z\notin \{v,t\}$. Thus, $z\in\{w,u\}$. Hence, see Figure~\ref{example gift figure repeated}, $z\Vdash \mbox{``Pavel received a gift from Sanaz''}$. Then, by item 2 of Definition~\ref{sat}, $$z\nVdash \neg(\mbox{``Pavel received a gift from Sanaz''}).$$ Therefore, $z\nVdash \S_p\neg(\mbox{``Pavel received a gift from Sanaz''})$ by item 7(a) of Definition~\ref{sat}. \vspace{1mm} \noindent$(\Leftarrow):$ Suppose that $z\in \{v,t\}$. We verify conditions (a), (b), and (c) from item 7 of Definition~\ref{sat} to prove that $z\Vdash \S_p\neg(\mbox{``Pavel received a gift from Sanaz''})$: \vspace{1mm} \noindent{\em Condition a:} Consider any world $z'$ such that $z\sim_p z'$. It suffices to show that $z'\Vdash \neg(\mbox{``Pavel received a gift from Sanaz''})$. Indeed, the assumptions $z\in \{v,t\}$ and $z\sim_p z'$ imply that $z'\in \{v,t\}$, see Figure~\ref{example gift figure repeated}. Thus, see again Figure~\ref{example gift figure repeated}, $z'\nVdash \mbox{``Pavel received a gift from Sanaz''}$. Therefore, by item 2 of Definition~\ref{sat}, $z'\Vdash \neg(\mbox{``Pavel received a gift from Sanaz''})$. \vspace{1mm} \noindent{\em Condition b:} The proof is similar to the proof of {\em Condition b} in Proposition~\ref{Ss proposition}. \vspace{1mm} \noindent{\em Condition c:} Note that $w\Vdash \mbox{``Pavel received a gift from Sanaz''}$. Therefore, $w\nVdash \neg(\mbox{``Pavel received a gift from Sanaz''})$ by item 2 of Definition~\ref{sat}. \end{proof} \begin{proposition}\label{SsSp proposition} $z\Vdash \S_s\S_p\neg(\mbox{``Pavel received a gift from Sanaz''})$ iff $z\in \{t\}$. \end{proposition} \begin{proof} Note that $x\nVdash \mbox{``Pavel received a gift from Sanaz''}$ iff $x\in \{t,v\}$, see Figure~\ref{example gift figure repeated}. Thus, $x\Vdash\neg( \mbox{``Pavel received a gift from Sanaz''})$ iff $x\in \{t,v\}$ by item 2 of Definition~\ref{sat}. Thus, by Proposition~\ref{Sp proposition}, for any world $x\in W$, \begin{eqnarray*} &&x\Vdash \neg(\mbox{``Pavel received a gift from Sanaz''})\\ &&\hspace{5mm}\mbox{ iff } x\Vdash \S_p\neg(\mbox{``Pavel received a gift from Sanaz''}). \end{eqnarray*} Hence, by Lemma~\ref{semantic substitution lemma}, for any world $z\in W$, \begin{eqnarray*} &&z\Vdash \S_s\neg(\mbox{``Pavel received a gift from Sanaz''})\\ &&\hspace{5mm}\mbox{ iff } z\Vdash \S_s\S_p\neg(\mbox{``Pavel received a gift from Sanaz''}). \end{eqnarray*} Therefore, $z\Vdash \S_s\S_p\neg(\mbox{``Pavel received a gift from Sanaz''})$ iff $z\in\{t\}$ by Proposition~\ref{Ss proposition}. \end{proof} \begin{proposition} $z\nVdash {\sf K}_p\S_s\S_p\neg(\mbox{``Pavel received a gift from Sanaz''})$ for each world $z\in \{w,u,v,t\}$. \end{proposition} \begin{proof} We consider the following two cases separately: \vspace{1mm} \noindent{\em Case I}: $z\in \{w,u\}$. Then, $z\nVdash \S_s\S_p\neg(\mbox{``Pavel received a gift from Sanaz''})$ by Proposition~\ref{SsSp proposition}. Therefore, $z\nVdash {\sf K}_p\S_s\S_p\neg(\mbox{``Pavel received a gift from Sanaz''})$ by item 5 of Definition~\ref{sat}. \noindent{\em Case II}: $z\in \{t,v\}$. Then, $z\sim_p v$, see Figure~\ref{example gift figure repeated}. Note that, by Proposition~\ref{SsSp proposition}, $v\nVdash \S_s\S_p\neg(\mbox{``Pavel received a gift from Sanaz''})$. Therefore, by item 5 of Definition~\ref{sat}, $z\nVdash {\sf K}_p\S_s\S_p\neg(\mbox{``Pavel received a gift from Sanaz''})$. \end{proof} \section{The Battle of Cuisines Scenario}\label{The Battle of Cuisines Scenario section} In this section we illustrate Definition~\ref{sat} using a scenario based on a classical strategic game. \begin{table}[ht] \begin{center} \begin{tabular}{ ccc } \toprule & Iranian & Russian\\ \midrule Iranian & 1,3 & 0,0 \\ Russian & 0,0 & 3,1 \\ \bottomrule \end{tabular} \caption{The Battle of Cuisines. Sanaz is the first player, Pavel is the second.}\label{example table figure} \end{center} \end{table} Suppose that the two co-authors finally met and are deciding on a restaurant to have dinner. Sanaz, being Iranian, wants to explore Russian cuisine, while Pavel would prefer to have dinner in an Iranian restaurant. The epistemic worlds in this model are pairs $(r_s,r_p)$ of restaurants choices made by Sanaz and Pavel respectively, where $r_s,r_p\in\{\mbox{Iranian},\mbox{Russian}\}$. We will consider the situation after they both arrived to a restaurant and thus each of them already knows the choice made by the other. Hence, both of them can distinguish all epistemic worlds. In other words, this is a {\em perfect information} scenario. We specify the preference relations of Sanaz and Pavel through their respective utility functions $u_s$ and $u_p$ captured in Table~\ref{example table figure}. For example, $(\mbox{Russian},\mbox{Iranian})\prec_s(\mbox{Iranian},\mbox{Iranian})$ because the value of Sanaz's utility function in world $(\mbox{Iranian},\mbox{Iranian})$ is larger than in world $(\mbox{Russian},\mbox{Iranian})$: \begin{eqnarray*} &&u_s(\mbox{Iranian},\mbox{Iranian})=1,\\ &&u_s(\mbox{Russian},\mbox{Iranian})=0. \end{eqnarray*} \begin{proposition} $$(\mathrm{Russian},\mathrm{Russian})\nVdash \H_p(\mbox{``Pavel is in the Russian restaurant''}).$$ \end{proposition} \begin{proof} Note that \begin{eqnarray*} && (\mathrm{Iranian},\mathrm{Iranian})\nVdash \mbox{``Pavel is in the Russian restaurant''},\\ && (\mathrm{Russian},\mathrm{Russian})\Vdash \mbox{``Pavel is in the Russian restaurant''}. \end{eqnarray*} At the same time, see Table~\ref{example table figure}, $$ u_p(\mathrm{Russian},\mathrm{Russian})=1<3=u_p(\mathrm{Iranian},\mathrm{Iranian}). $$ Hence, $(\mathrm{Iranian},\mathrm{Iranian})\nprec_p(\mathrm{Russian},\mathrm{Russian})$. Therefore, by item 6(b) of Definition~\ref{sat}, $(\mathrm{Russian},\mathrm{Russian})\nVdash \H_p(\mbox{``Pavel is in the Russian restaurant''})$. \end{proof} Note that Sanaz prefers world $(\mathrm{Russian},\mathrm{Russian})$ to any other world. This, however, does not mean that she is happy about everything in this world. The next two propositions illustrate this. \begin{proposition}\label{oct19-rr} $$(\mathrm{Russian},\mathrm{Russian})\nVdash \H_s(\mbox{``Sanaz is in the Russian restaurant''}).$$ \end{proposition} \begin{proof} Note that \begin{eqnarray*} && (\mathrm{Iranian},\mathrm{Iranian})\nVdash \mbox{``Sanaz is in the Russian restaurant''},\\ && (\mathrm{Russian},\mathrm{Iranian})\Vdash \mbox{``Sanaz is in the Russian restaurant''}. \end{eqnarray*} At the same time, see Table~\ref{example table figure}, $$ u_s(\mathrm{Russian},\mathrm{Iranian})=0<1=u_s(\mathrm{Iranian},\mathrm{Iranian}). $$ Hence, $(\mathrm{Iranian},\mathrm{Iranian})\nprec_s(\mathrm{Russian},\mathrm{Iranian})$. Therefore, by item 6(b) of Definition~\ref{sat}, $(\mathrm{Russian},\mathrm{Russian})\nVdash \H_s(\mbox{``Sanaz is in the Russian restaurant''})$. \end{proof} \begin{proposition}\label{sept25 Hs} $$(x,y)\Vdash \H_s(\mbox{``Sanaz and Pavel are in the same restaurant''})$$ iff $x=y$. \end{proposition} \begin{proof} $(\Rightarrow):$ Suppose that $x\neq y$. Then, \begin{eqnarray*} && (x,y)\nVdash \mbox{``Sanaz and Pavel are in the same restaurant''},\\ && (x,x)\Vdash \mbox{``Sanaz and Pavel are in the same restaurant''}. \end{eqnarray*} Note also that $ u_s(x,y)=0<1\le u_s(x,x) $ because $x\neq y$, see Table~\ref{example table figure}. Hence $(x,x)\nprec_s(x,y)$. Therefore, $$(x,y)\nVdash \H_s(\mbox{``Sanaz and Pavel are in the same restaurant''})$$ by item 6(b) of Definition~\ref{sat}. \vspace{1mm} \noindent$(\Leftarrow):$ Suppose $x=y$. We verify conditions (a), (b), and (c) from item 6 of Definition~\ref{sat} to prove that $(x,y)\Vdash \H_s(\mbox{``Sanaz and Pavel are in the same restaurant''})$: \vspace{1mm} \noindent{\em Condition a:} Since this is a model with perfect information, it suffices to show that $(x,y)\Vdash \mbox{``Sanaz and Pavel are in the same restaurant''}$, which is true due to the assumption $x=y$. \vspace{1mm} \noindent{\em Condition b:} Consider any two worlds $(x_1,y_1), (x_2,y_2)\in W$ such that \begin{eqnarray} && (x_1,y_1)\nVdash \mbox{``Sanaz and Pavel are in the same restaurant''},\label{sept25-a}\\ && (x_2,y_2)\Vdash \mbox{``Sanaz and Pavel are in the same restaurant''}.\label{sept25-b} \end{eqnarray} It suffices to show that $(x_1,y_1)\prec_s(x_2,y_2)$. Indeed, statements~(\ref{sept25-a}) and (\ref{sept25-b}) imply that $x_1\neq y_1$ and $x_2=y_2$, respectively. Thus, $u_s(x_1,y_1)=0<1\le u_s(x_2,y_2)$, see Table~\ref{example table figure}. Therefore, $(x_1,y_1)\prec_s(x_2,y_2)$. \vspace{1mm} \noindent{\em Condition c:} Note that $$(\mathrm{Russian},\mathrm{Iranian})\nVdash \mbox{``Sanaz and Pavel are in the same restaurant''}.$$ \end{proof} The proof of the next proposition is similar to the proof of the one above. \begin{proposition}\label{sept25 Hp} $$(x,y)\Vdash \H_p(\mbox{``Sanaz and Pavel are in the same restaurant''})$$ iff $x=y$. \qed \end{proposition} \begin{proposition}\label{sept25 HpHs} $$(x,y)\Vdash \H_p\H_s(\mbox{``Sanaz and Pavel are in the same restaurant''})$$ iff $x=y$. \end{proposition} \begin{proof} Note that $(x,y)\Vdash \mbox{``Sanaz and Pavel are in the same restaurant''}$ iff $x=y$. Thus, by Proposition~\ref{sept25 Hs}, for any world $(x,y)\in W$, \begin{eqnarray*} &&(x,y)\Vdash \mbox{``Sanaz and Pavel are in the same restaurant''}\\ &&\hspace{5mm}\mbox{ iff } (x,y)\Vdash \H_s(\mbox{``Sanaz and Pavel are in the same restaurant''}). \end{eqnarray*} Hence, by Lemma~\ref{semantic substitution lemma}, for any world $(x,y)\in W$, \begin{eqnarray*} &&(x,y)\Vdash \H_p(\mbox{``Sanaz and Pavel are in the same restaurant''})\\ &&\hspace{5mm}\mbox{ iff } (x,y)\Vdash \H_p\H_s(\mbox{``Sanaz and Pavel are in the same restaurant''}). \end{eqnarray*} Therefore, $(x,y)\Vdash \H_p\H_s(\mbox{``Sanaz and Pavel are in the same restaurant''})$ iff $x=y$ by Proposition~\ref{sept25 Hp}. \end{proof} \begin{proposition} $$(x,y)\Vdash \H_s\H_p\H_s(\mbox{``Sanaz and Pavel are in the same restaurant''})$$ iff $x=y$. \end{proposition} \begin{proof} Note that $(x,y)\Vdash \mbox{``Sanaz and Pavel are in the same restaurant''}$ iff $x=y$. Thus, by Proposition~\ref{sept25 HpHs}, for any world $(x,y)\in W$, \begin{eqnarray*} &&(x,y)\Vdash \mbox{``Sanaz and Pavel are in the same restaurant''}\\ &&\hspace{5mm}\mbox{ iff } (x,y)\Vdash \H_p\H_s(\mbox{``Sanaz and Pavel are in the same restaurant''}). \end{eqnarray*} Hence, by Lemma~\ref{semantic substitution lemma}, for any world $(x,y)\in W$, \begin{eqnarray*} &&(x,y)\Vdash \H_s(\mbox{``Sanaz and Pavel are in the same restaurant''})\\ &&\hspace{5mm}\mbox{ iff } (x,y)\Vdash \H_s\H_p\H_s(\mbox{``Sanaz and Pavel are in the same restaurant''}). \end{eqnarray*} Therefore, $(x,y)\Vdash \H_s\H_p\H_s(\mbox{``Sanaz and Pavel are in the same restaurant''})$ iff $x=y$ by Proposition~\ref{sept25 Hs}. \end{proof} \begin{proposition}\label{sept26 Hs proposition} $$(x,y)\Vdash \H_s(\mbox{``Sanaz and Pavel are in the Russian restaurant''})$$ iff $x=y=\mathrm{Russian}$. \end{proposition} \begin{proof} $(\Rightarrow):$ By item 6(a) of Definition~\ref{sat}, the assumption of the proposition $(x,y)\Vdash \H_s(\mbox{``Sanaz and Pavel are in the Russian restaurant''})$ implies that $(x,y)\Vdash \mbox{``Sanaz and Pavel are in the Russian restaurant''}$. Therefore, $x=y=\mathrm{Russian}$. \vspace{1mm} \noindent $(\Leftarrow):$ Suppose $x=y=\mathrm{Russian}$. To prove that $$(x,y)\Vdash \H_s(\mbox{``Sanaz and Pavel are in the Russian restaurant''}),$$ we verify conditions (a), (b), and (c) from item 6 of Definition~\ref{sat}: \vspace{1mm} \noindent{\em Condition a:} Since this is a model with perfect information, it suffices to show that $(x,y)\Vdash \mbox{``Sanaz and Pavel are in the Russian restaurant''}$, which is true due to the assumption $x=y=\mathrm{Russian}$. \vspace{1mm} \noindent{\em Condition b:} Consider any two worlds $(x_1,y_1), (x_2,y_2)\in W$ such that \begin{eqnarray} && (x_1,y_1)\nVdash \mbox{``Sanaz and Pavel are in the Russian restaurant''},\label{sept25-c}\\ && (x_2,y_2)\Vdash \mbox{``Sanaz and Pavel are in the Russian restaurant''}.\label{sept25-d} \end{eqnarray} It suffices to show that $(x_1,y_1)\prec_s(x_2,y_2)$. Indeed, statement~(\ref{sept25-c}) implies that $u_s(x_1,y_1)\le 1$, see Table~\ref{example table figure}. Similarly, statement~(\ref{sept25-d}) implies that $u_s(x_2,y_2)=3$. Thus, $u_s(x_1,y_1)\le 1<3=u_s(x_2,y_2)$. Therefore, $(x_1,y_1)\prec_s(x_2,y_2)$. \vspace{1mm} \noindent{\em Condition c:} $(\mathrm{Russian},\mathrm{Iranian})\nVdash \mbox{``Sanaz and Pavel are in the Russian restaurant''}$. \end{proof} \begin{proposition} $$(\mathrm{Russian},\mathrm{Russian})\nVdash \H_p(\mbox{``Sanaz and Pavel are in the Russian restaurant''}).$$ \end{proposition} \begin{proof} Note that $u_p(\mathrm{Iranian},\mathrm{Iranian})=3>1=u_p(\mathrm{Russian},\mathrm{Russian})$. Thus, $(\mathrm{Iranian},\mathrm{Iranian})\nprec_p(\mathrm{Russian},\mathrm{Russian})$. Therefore, the proposition is true by item 6(b) of Definition~\ref{sat}. \end{proof} \begin{proposition} $$(\mathrm{Russian},\mathrm{Russian})\nVdash \H_p\H_s(\mbox{``Sanaz and Pavel are in the Russian restaurant''}).$$ \end{proposition} \begin{proof} Note that \begin{eqnarray*} && (\mathrm{Iranian},\mathrm{Iranian})\nVdash \H_s(\mbox{``Sanaz and Pavel are in the Russian restaurant''}),\label{sept26-c}\\ &&(\mathrm{Russian},\mathrm{Russian})\Vdash \H_s(\mbox{``Sanaz and Pavel are in the Russian restaurant''}).\label{sept26-d} \end{eqnarray*} by Proposition~\ref{sept26 Hs proposition}. At the same time, $$u_p(\mathrm{Iranian},\mathrm{Iranian})=3>1=u_p(\mathrm{Russian},\mathrm{Russian}).$$ Thus, $(\mathrm{Iranian},\mathrm{Iranian})\nprec_p(\mathrm{Russian},\mathrm{Russian})$. Therefore, the proposition is true by item 6(b) of Definition~\ref{sat}. \end{proof} \begin{proposition}\label{sept26-Ss} $$(x,y)\Vdash \S_s(\mbox{``Sanaz and Pavel are in different restaurants''})\;\;\mbox{ iff }\;\; x\neq y.$$ \end{proposition} \begin{proof} $(\Rightarrow):$ Suppose that $x=y$. Thus, $$(x,y)\nVdash \mbox{``Sanaz and Pavel are in different restaurants''}.$$ Thus, by item 7(a) of Definition~\ref{sat}, $$(x,y)\nVdash \S_s(\mbox{``Sanaz and Pavel are in different restaurants''}).$$ \vspace{1mm} \noindent$(\Leftarrow):$ Suppose that $x\neq y$. To prove that $$(x,y)\Vdash \S_s(\mbox{``Sanaz and Pavel are in different restaurants''}),$$ we verify conditions (a), (b), and (c) from item 7 of Definition~\ref{sat}: \vspace{1mm} \noindent{\em Condition a:} Since this is a model with perfect information, it suffices to show that $(x,y)\Vdash \mbox{``Sanaz and Pavel are in different restaurants''}$, which is true due to the assumption $x\neq y$. \vspace{1mm} \noindent{\em Condition b:} The proof of this condition is similar to the proof of {\em Condition b} in the proof of Proposition~\ref{sept25 Hs}. \vspace{1mm} \noindent{\em Condition c:} $(\mathrm{Iranian},\mathrm{Iranian})\nVdash \mbox{``Sanaz and Pavel are in different restaurants''}$. \end{proof} The proof of the following statement is similar to the proof of the one above. \begin{proposition}\label{sept26-Sp} $$(x,y)\Vdash \S_p(\mbox{``Sanaz and Pavel are in different restaurants''}) \;\;\mbox{ iff }\;\;x\neq y.$$ \qed \end{proposition} \begin{proposition} $$(x,y)\Vdash \S_p\S_s(\mbox{``Sanaz and Pavel are in different restaurants''})\;\;\mbox{ iff }\;\; x\neq y.$$ \end{proposition} \begin{proof} Note that $(x,y)\Vdash \mbox{``Sanaz and Pavel are in different restaurants''}$ iff $x\neq y$. Thus, by Proposition~\ref{sept26-Ss}, for any world $(x,y)\in W$, \begin{eqnarray*} &&(x,y)\Vdash \mbox{``Sanaz and Pavel are in different restaurants''}\\ &&\hspace{5mm}\mbox{ iff } (x,y)\Vdash \S_s(\mbox{``Sanaz and Pavel are in different restaurants''}). \end{eqnarray*} Hence, by Lemma~\ref{semantic substitution lemma}, for any world $(x,y)\in W$, \begin{eqnarray*} &&(x,y)\Vdash \S_p(\mbox{``Sanaz and Pavel are in different restaurants''})\\ &&\hspace{5mm}\mbox{ iff } (x,y)\Vdash \S_p\S_s(\mbox{``Sanaz and Pavel are in different restaurants''}). \end{eqnarray*} Therefore, $(x,y)\Vdash \S_p\S_s(\mbox{``Sanaz and Pavel are in different restaurants''})$ iff $x=y$ by Proposition~\ref{sept26-Sp}. \end{proof} \section{Lottery Example} \epigraph{Be happy for this moment. This moment is your life.}% {The Rub\'{a}iy\'{a}t of Omar Khayy\'{a}m} As our next example, consider a hypothetical situation when Sanaz and Pavel play lottery with Omar Khayy\'{a}m, an Iranian mathematician, astronomer, philosopher, and poet. Each of them gets a lottery ticket and it is known that exactly one out of three tickets is winning. We consider the moment when each of the players has already seen her or his own ticket, but does not know yet what are the tickets of the other players. We assume that each of the three players prefers the outcome when she or he wins the lottery. \begin{figure}[ht] \begin{center} \scalebox{0.45}{\includegraphics{Images/example-lottery.pdf}} \caption{Lottery Epistemic Model with Preferences.}\label{example lottery figure} \end{center} \end{figure} Figure~\ref{example lottery figure} depicts the epistemic model with preferences capturing the above scenario. It has three epistemic worlds, $u$, $v$, and $w$ in which the winner is Sanaz, Omar, and Pavel respectively. Dashed lines represent indistinguishability relations. For example, the dashed line between worlds $w$ and $v$ labeled with $s$ shows that Sanaz cannot distinguish the world in which Pavel wins from the one in which Omar wins. This is true because we consider the knowledge at the moment when neither of the players knows yet what are the tickets of the other players. The directed edges between worlds represent preference relations. For example, the directed edge from world $w$ to world $v$ labeled with $o$ captures the fact that Omar would prefer to win the lottery rather than to lose it. \begin{proposition}\label{oct3-Hs} $x\Vdash \H_s(\mbox{``Sanaz won the lottery''})$ iff $x=u$. \end{proposition} \begin{proof} $(\Rightarrow):$ Suppose that $x\neq u$. Thus, $x\nVdash \mbox{``Sanaz won the lottery''}$, see Figure~\ref{example lottery figure}. Therefore, $x\nVdash \H_s(\mbox{``Sanaz won the lottery''})$ by item 6(a) of Definition~\ref{sat}. \vspace{1mm} \noindent$(\Leftarrow):$ Suppose that $x=u$. To prove the required, it suffices to verify conditions (a), (b), and (c) from item 6 of Definition~\ref{sat}: \vspace{1mm} \noindent{\em Condition a:} Consider any world $y$ such that $u\sim_s y$. We will show that $y\Vdash \mbox{``Sanaz won the lottery''}$. Indeed, assumption $u\sim_s y$ implies that $u=y$, see Figure~\ref{example lottery figure}. Therefore, $y\Vdash \mbox{``Sanaz won the lottery''}$, see again Figure~\ref{example lottery figure}. \vspace{1mm} \noindent{\em Condition b:} Consider any worlds $y,z$ such that $y\nVdash \mbox{``Sanaz won the lottery''}$ and $z\Vdash \mbox{``Sanaz won the lottery''}$. We will show that $y\prec_s z$. Indeed, assumption $y\nVdash \mbox{``Sanaz won the lottery''}$ implies that $y\in \{w,v\}$, see Figure~\ref{example lottery figure}. Similarly, assumption $z\Vdash \mbox{``Sanaz won the lottery''}$ implies that $z=u$. Statements $y\in \{w,v\}$ and $z=u$ imply that $y\prec_s z$, see again Figure~\ref{example lottery figure}. \vspace{1mm} \noindent{\em Condition c:} $w\nVdash \mbox{``Sanaz won the lottery''}$. \end{proof} \begin{proposition} $u\nVdash \H_s(\mbox{``Pavel lost the lottery''})$. \end{proposition} \begin{proof} Note that $w\nVdash \mbox{``Pavel lost the lottery''}$, $v\Vdash \mbox{``Pavel lost the lottery''}$, and $w\nprec_s v$, see Figure~\ref{example lottery figure}. Therefore, $u\nVdash \H_s(\mbox{``Pavel lost the lottery''})$ by item 6(b) of Definition~\ref{sat}. \end{proof} \begin{proposition} $u\nVdash {\sf K}_p\H_s(\mbox{``Sanaz won the lottery''})$. \end{proposition} \begin{proof} Note that $u\sim_p v$, see Figure~\ref{example lottery figure}. Also, $v\nVdash \H_s(\mbox{``Sanaz won the lottery''})$ by Proposition~\ref{oct3-Hs}. Therefore, $u\nVdash {\sf K}_p\H_s(\mbox{``Sanaz won the lottery''})$ by item 5 of Definition~\ref{sat}. \end{proof} \begin{proposition}\label{oct3-Sp} $u\Vdash \S_p(\mbox{``Pavel lost the lottery''})$. \end{proposition} \begin{proof} It suffices to verify conditions (a), (b), and (c) from item 7 of Definition~\ref{sat}: \vspace{1mm} \noindent{\em Condition a:} Consider any world $y$ such that $u\sim_p y$. We will show that $y\Vdash \mbox{``Pavel lost the lottery''}$. Indeed, assumption $u\sim_p y$ implies that $y\in\{u,v\}$, see Figure~\ref{example lottery figure}. Therefore, $y\Vdash \mbox{``Pavel lost the lottery''}$, see again Figure~\ref{example lottery figure}. \vspace{1mm} \noindent{\em Condition b:} Consider any worlds $y,z$ such that $y\Vdash \mbox{``Pavel lost the lottery''}$ and $z\nVdash \mbox{``Pavel lost the lottery''}$. We will show that $y\prec_p z$. Indeed, assumption $y\Vdash \mbox{``Pavel lost the lottery''}$ implies that $y\in \{u,v\}$, see Figure~\ref{example lottery figure}. Similarly, assumption $z\nVdash \mbox{``Pavel lost the lottery''}$ implies that $z=w$. Statements $y\in \{u,v\}$ and $z=w$ imply that $y\prec_s z$, see again Figure~\ref{example lottery figure}. \vspace{1mm} \noindent{\em Condition c:} $w\nVdash \mbox{``Pavel lost the lottery''}$. \end{proof} \begin{proposition} $u\Vdash {\sf K}_s\S_p(\mbox{``Pavel lost the lottery''})$. \end{proposition} \begin{proof} Consider any world $y$ such that $u\sim_s y$. By item 5 of Definition~\ref{sat}, it suffices to show that $y\Vdash \S_p(\mbox{``Pavel lost the lottery''})$. Indeed, assumption $u\sim_s y$ implies that $u=y$, see Figure~\ref{example lottery figure}. Therefore, $y\Vdash \S_p(\mbox{``Pavel lost the lottery''})$ by Proposition~\ref{oct3-Sp}. \end{proof} \section{Undefinability of Sadness through Happiness}\label{Undefinability of Sadness through Happiness section} In this section we prove that sadness is not definable through happiness. More formally, we show that formula $\S_a p$ is not equivalent to any formula in the language $\Phi^{-\S}$: $$ \phi:=p\;|\;\neg\phi\;|\;\phi\to\phi\;|\;{\sf N}\phi\;|\;{\sf K}_a\phi\;|\;\H_a\phi, $$ which is obtained by removing modality $\S$ from the full language $\Phi$ of our logical system. In the next section we will use a duality principle to claim that happiness is not definable through sadness either. Without loss of generality, in this section we assume that the set of agents $\mathcal{A}$ contains a single agent $a$ and the set of propositional variables contains a single variable $p$. To prove undefinability of sadness through happiness we consider two epistemic models with preferences depicted in Figure~\ref{two models figure}. By $\Vdash_l$ and $\Vdash_r$ we mean the satisfaction relations for the left and and the right model respectively. In Lemma~\ref{nov30-a}, we show that these two models are indistinguishable in language the $\Phi^{-\S}$. In Lemma~\ref{nov30-b} and Lemma~\ref{nov30-c}, we prove that $w_1\Vdash_l \S_a p$ and $w_1\nVdash_r \S_a p$ respectively. Together, these three statements imply undefinability of modality $\S$ in the language $\Phi^{-\S}$, which is stated in the end of this section as Theorem~\ref{dec1-S-is-not-definable}. We start with two auxiliary lemmas used in the proof of Lemma~\ref{nov30-a}. \begin{figure}[ht] \begin{center} \scalebox{0.45}{\includegraphics{Images/two-models.pdf}} \caption{Two Models.}\label{two models figure} \end{center} \end{figure} \begin{lemma}\label{H l lemma} $w\nVdash_l \H_a \phi$ for each world $w\in\{w_1,w_2,w_3\}$ and each formula $\phi\in \Phi$. \end{lemma} \begin{proof} Suppose that $w\Vdash_l \H_a \phi$. Thus, by item 6 of Definition~\ref{sat}, \begin{eqnarray} &&u\Vdash_l\phi \mbox{ for each world $u\in W$ such that } w\sim_a u,\label{item a}\\ &&u\prec_a u' \mbox{ for all worlds $u,u'\in W$ such that } u\nVdash\phi \mbox{ and } u'\Vdash \phi,\label{item b} \end{eqnarray} and there is a world $\widehat{w}\in\{w_1,w_2,w_3\}$ such that \begin{equation}\label{item c} \widehat{w}\nVdash\phi. \end{equation} Since relation $\sim_a$ is reflexive, statement~(\ref{item a}) implies that \begin{equation}\label{item 1} w\Vdash\phi. \end{equation} Thus, using statements~(\ref{item b}) and (\ref{item c}), \begin{equation}\label{item 2} \widehat{w}\prec_a w. \end{equation} Hence, see Figure~\ref{two models figure} (left), \begin{eqnarray} &&\widehat{w}\in\{w_1,w_3\},\label{item 3a}\\ &&w=w_2. \label{item 3b} \end{eqnarray} Note that $w_2\sim_a w_3$, see Figure~\ref{two models figure} (left). Thus, $w\sim_a w_3$ by statement~(\ref{item 3b}). Then, by statement~(\ref{item a}), \begin{equation}\label{item 4} w_3\Vdash\phi. \end{equation} Hence, $\widehat{w}\neq w_3$ because of statement~(\ref{item c}). Thus, $\widehat{w}=w_1$ due to statement~(\ref{item 3a}). Then, $w_1\nVdash\phi$ because of statement~(\ref{item c}). Therefore, $w_1\prec_a w_3$ by statements~(\ref{item b}) and (\ref{item 4}), which is a contradiction, see Figure~\ref{two models figure} (left). \end{proof} \begin{lemma}\label{H r lemma} $w\nVdash_r \H_a \phi$ for each world $w\in\{w_1,w_2,w_3\}$ and each formula $\phi\in \Phi$. \end{lemma} \begin{proof} Suppose $w\Vdash_r \H_a \phi$. Thus, $w\Vdash_r \phi$ by item 6(a) of Definition~\ref{sat} and the reflexivity of relation $\sim_a$. At the same time, by item 6(c) of Definition~\ref{sat}, there must exist a world $u\in W$ such that $u\nVdash_r\phi$. By item 6(b) of the same Definition~\ref{sat}, the assumption $w\Vdash_r \H_a \phi$ and the statements $u\nVdash_r\phi$ and $w\Vdash_r \phi$ imply that $u\prec_a w$, which is a contradiction because relation $\prec_a$ in the right model is empty, see Figure~\ref{two models figure}. \end{proof} \begin{lemma}\label{nov30-a} $w\Vdash_l \phi$ iff $w\Vdash_r \phi$ for each world $w$ and each formula $\phi\in \Phi^{-\S}$. \end{lemma} \begin{proof} We prove the statement by structural induction on formula $\phi$. For the case when formula $\phi$ is propositional variable $p$, observe that $\pi_l(p)=\{w_1,w_3\}=\pi_r(p)$ by the choice of the models, see Figure~\ref{two models figure}. Thus, $w\Vdash_l p$ iff $w\Vdash_r p$ for any world $w$ by item 1 of Definition~\ref{sat}. The case when formula $\phi$ is a negation or an implication follows from the induction hypothesis and items 2 and 3 of Definition~\ref{sat} in the straightforward way. Suppose formula $\phi$ has the form ${\sf N}\psi$. If $w\nVdash_l{\sf N}\psi$, then by item 4 of Definition~\ref{sat}, there must exists a world $u\in \{w_1,w_2,w_3\}$ such that $u\nVdash_l\psi$. Hence, by the induction hypothesis, $u\nVdash_r\psi$. Therefore, $w\nVdash_r{\sf N}\psi$, by item 4 of Definition~\ref{sat}. The proof in the other direction is similar. Assume that formula $\phi$ has the form ${\sf K}_a\psi$. If $w\nVdash_l{\sf K}_a\psi$, then, by item 5 of Definition~\ref{sat}, there is a world $u\in \{w_1,w_2,w_3\}$ such that $w\sim^l_a u$ and $u\nVdash_l \psi$. Then, $w\sim^r_a u$ because relations $\sim^l$ and $\sim^r$ are equal, see Figure~\ref{two models figure} and, by the induction hypothesis, $u\nVdash_r \psi$. Therefore, $w\nVdash_r{\sf K}_a\psi$ by item 5 of Definition~\ref{sat}. The proof in the other direction is similar. Finally, suppose formula $\phi$ has the form $\H_a\psi$. Therefore, $w\nVdash_l\phi$ and $w\nVdash_r\phi$ by Lemma~\ref{H l lemma} and Lemma~\ref{H r lemma} respectively. \end{proof} \begin{lemma}\label{nov30-b} $w_1\Vdash_l \S_a p$. \end{lemma} \begin{proof} We verify the three conditions from item 7 of Definition~\ref{sat} separately: \vspace{1mm} \noindent{\em Condition a:} Observe that $w_1\in \{w_1,w_3\}=\pi_l(p)$, see Figure~\ref{two models figure} (left). Then, $w_1\Vdash_l p$ by item 1 of Definition~\ref{sat}. Note also that there is only one world $u\in\{w_1,w_2,w_3\}$ such that $w_1\sim^l_a u$ (namely, the world $w_1$ itself), see Figure~\ref{two models figure} (left). Therefore, $u\Vdash p$ for each world $u\in \{w_1,w_2,w_3\}$ such that $w_1\sim_a u$. \vspace{1mm} \noindent{\em Condition b:} Note that $\pi_l(p)=\{w_1,w_3\}$, see Figure~\ref{two models figure} (left). Then, $w_1\Vdash_l p$, $w_3\Vdash_l p$, and $w_2\nVdash_l p$ by item 1 of Definition~\ref{sat}. Also, observe that $w_1\prec^l_a w_2$ and $w_3\prec^l_a w_2$, see Figure~\ref{two models figure} (left). Thus, for any world $u,u'\in \{w_1,w_2,w_3\}$, if $u\Vdash p$ and $u'\nVdash p$, then $u\prec_a u'$. \vspace{1mm} \noindent{\em Condition c:} $w_2\nVdash_l p$ by item 1 of Definition~\ref{sat} and because $w_2\notin \{w_1,w_3\}=\pi_l(p)$, see Figure~\ref{two models figure} (left). \vspace{1mm} This concludes the proof of the lemma. \end{proof} \begin{lemma}\label{nov30-c} $w_1\nVdash_r \S_a p$. \end{lemma} \begin{proof} Note that $\pi_r(p)=\{w_1,w_3\}$, see Figure~\ref{two models figure} (right). Thus, $w_1\Vdash_r p$ and $w_2\nVdash_r p$ by item 1 of Definition~\ref{sat}. Observe also, that $w_1\nprec_a w_2$, Figure~\ref{two models figure} (right). Therefore, $w_1\nVdash_r \S_a p$ by item 7(b) of Definition~\ref{sat}. \end{proof} The next theorem follows from the three lemmas above. \begin{theorem}\label{dec1-S-is-not-definable} Modality $\S$ is not definable in language $\Phi^{-\S}$. \qed \end{theorem} \section{Duality of Happiness and Sadness}\label{Duality of Happiness and Sadness} As we have shown in the previous section, sadness modality is not definable through happiness modality. In spite of this, there still is a connection between these two modalities captured below in Theorem~\ref{duality theorem}. To understand this connection, we need to introduce the notion of a converse model and the notion of $\tau$-translation. As usual, for any binary relation $R\subseteq X\times Y$, by converse relation $R^{\c}$ we mean the set of pairs $\{(y,x)\in Y\times X\;|\; (x,y)\in R\}$. \begin{definition}\label{converse model} By the converse model $M^{\c}$ of an epistemic model with preference $M=(W,\{\sim_a\}_{a\in\mathcal{A}},\{\prec_a\}_{a\in\mathcal{A}},\pi)$, we mean model $(W,\{\sim_a\}_{a\in\mathcal{A}},\{\prec^{\c}_a\}_{a\in\mathcal{A}},\pi)$. \end{definition} For any epistemic model with preference, by $\Vdash$ we denote the satisfaction relation for this model and by $\Vdash^\c$ the satisfaction relation for the converse model. \begin{definition}\label{tau translation} For any formula $\phi\in\Phi$, formula $\tau(\phi)\in \Phi$ is defined recursively as follows: \begin{enumerate} \item $\tau(p) \equiv p$, where $p$ is a propositional variable, \item $\tau(\neg\phi) \equiv \neg\tau(\phi)$, \item $\tau(\phi\to\psi) \equiv \tau(\phi)\to\tau(\psi)$, \item $\tau({\sf N}\phi) \equiv {\sf N}\tau(\phi)$, \item $\tau({\sf K}_a\phi) \equiv {\sf K}_a\tau(\phi)$, \item $\tau(\H_a\phi) \equiv \S_a\tau(\phi)$, \item $\tau(\S_a\phi) \equiv \H_a\tau(\phi)$. \end{enumerate} \end{definition} We are now ready to state and prove the ``duality principle'' that connects modalities $\H$ and $\S$. \begin{theorem}\label{duality theorem} $w\Vdash \phi$ iff $w\Vdash^\c \tau(\phi)$, for each world $w$ of an epistemic model with preferences. \end{theorem} \begin{proof} We prove the theorem by induction on structural complexity of formula $\phi$. If $\phi$ is a propositional variable, then the statement of the theorem holds because the model and the converse model have the same valuation function $\pi$. If $\phi$ is a negation, an implication, an ${\sf N}$-formula, or an ${\sf K}$-formula, then the statement of the theorem follows from the induction hypothesis and items 2, 3, 4, and 5 of Definition~\ref{sat} respectively. Suppose that formula $\phi$ has the form $\H_a\psi$. First, assume that $w\Vdash\H_a\psi$. Thus, by item 6 of Definition~\ref{sat}, the following three conditions are satisfied: \begin{enumerate} \item[(a)] $u\Vdash \psi$ for each world $u\in W$ such that $w\sim_a u$, \item[(b)] for any two worlds $u,u'\in W$, if $u\nVdash\psi$ and $u'\Vdash\psi$, then $u\prec_a u'$, \item[(c)] there is a world $u\in W$ such that $u\nVdash\psi$. \end{enumerate} Hence, by the induction hypothesis, \begin{enumerate} \item[(d)] $u\Vdash^\c \tau(\psi)$ for each world $u\in W$ such that $w\sim_a u$, \item[(e)] for any two worlds $u,u'\in W$, if $u\nVdash^\c\tau(\psi)$ and $u'\Vdash^\c\tau(\psi)$, then $u\prec_a u'$, \item[(f)] there is a world $u\in W$ such that $u\nVdash^\c\tau(\psi)$. \end{enumerate} Note that statement (e) is logically equivalent to \begin{enumerate} \item[(g)] for any two worlds $u,u'\in W$, if $u\Vdash^\c\tau(\psi)$ and $u'\nVdash^\c\tau(\psi)$, then $u'\prec_a u$. \end{enumerate} By the definition of converse partial order, statement (g) is equivalent to \begin{enumerate} \item[(h)] for any two worlds $u,u'\in W$, if $u\Vdash^\c\tau(\psi)$ and $u'\nVdash^\c\tau(\psi)$, then $u\prec^\c_a u'$. \end{enumerate} Thus, $w\Vdash^\c\S_a\tau(\psi)$ by item 7 of Definition~\ref{sat} using statements (d), (h), and (f). Therefore, $w\Vdash^\c\tau(\H_a\psi)$. The proof in the other direction and the proof for the case when formula $\phi$ has the form $\S_a\psi$ are similar. \end{proof} The next theorem follows from Theorem~\ref{dec1-S-is-not-definable} and Theorem~\ref{duality theorem}. \begin{theorem} Modality $\H$ is not definable in language $\Phi^{-\H}$. \qed \end{theorem} \section{Axioms of Emotions}\label{Axioms of Emotions} In addition to propositional tautologies in language $\Phi$, our logical system contains the following axioms, where ${\sf E}\in\{\H,\S\}$. \begin{enumerate} \item Truth: ${\sf N}\phi\to\phi$, ${\sf K}_a\phi\to\phi$, and ${\sf E}_a\phi\to\phi$, \item Distributivity:\\ ${\sf N}(\phi\to\psi)\to({\sf N}\phi\to{\sf N}\psi)$,\\ ${\sf K}_a(\phi\to\psi)\to({\sf K}_a\phi\to{\sf K}_a\psi)$, \item Negative Introspection: $\neg{\sf N}\phi\to{\sf N}\neg{\sf N}\phi$, and $\neg{\sf K}_a\phi\to{\sf K}_a\neg{\sf K}_a\phi$, \item Knowledge of Necessity: ${\sf N}\phi\to{\sf K}_a\phi$, \item Emotional Introspection: ${\sf E}_a\phi\to{\sf K}_a{\sf E}_a\phi$, \item Emotional Consistency: $\H_a\phi\to\neg\S_a\phi$, \item Coherence of Potential Emotions:\\ ${\sf \overline{N}}{\sf E}_a\phi\wedge{\sf \overline{N}}{\sf E}_a\psi\to {\sf N}(\phi\to\psi)\vee {\sf N}(\psi\to\phi)$,\\ ${\sf \overline{N}}\H_a\phi\wedge{\sf \overline{N}}\S_a\psi\to {\sf N}(\phi\to\neg\psi)\vee {\sf N}(\neg\psi\to\phi)$, \item Counterfactual: ${\sf E}_a\phi\to\neg{\sf N}\phi$, \item Emotional Predictability:\\ ${\sf \overline{N}}\H_a\phi\vee{\sf \overline{N}}\S_a\neg\phi\to({\sf K}_a\phi\to\H_a\phi)$,\\ ${\sf \overline{N}}\H_a\neg\phi\vee{\sf \overline{N}}\S_a\phi\to({\sf K}_a\phi\to\S_a\phi)$, \item Substitution: ${\sf N}(\phi\leftrightarrow\psi)\to ({\sf E}_a\phi\to{\sf E}_a\psi)$. \end{enumerate} The Truth, the Distributivity, and the Negative Introspection axioms for modalities ${\sf N}$ and ${\sf K}$ are well-known properties from modal logic S5. The Truth axiom for modality ${\sf E}$ states that if an agent is either happy or sad about $\phi$, then statement $\phi$ must be true. This axiom reflects the fact that our emotions are defined through agent's knowledge. We will mention belief-based emotions in the conclusion. The Knowledge of Necessity axioms states that each agent knows all statements that are true in all worlds of the model. The Emotional Introspection axiom captures one of the two possible interpretations of the title of this article: each agent knows her emotions. The other interpretation of the title is stated below as Lemma~\ref{E to K}. The Emotional Consistency axiom states that an agent cannot be simultaneously happy and sad about the same thing. Recall that ${\sf \overline{N}}\phi$ stands for formula $\neg{\sf N}\neg\phi$. Thus, formula ${\sf \overline{N}}{\sf E}_a\phi$ means that agent $a$ {\em might} have the emotion ${\sf E}$ about statement $\phi$. In other words, formula ${\sf \overline{N}}{\sf E}_a\phi$ states that agent $a$ has a {\em potential} emotion ${\sf E}$ about $\phi$. The Coherence of Potential Emotions axioms expresses the fact that potential emotions of any agent are not independent. The first of these axioms says that if an agent has {\em the same} potential emotions about statements $\phi$ and $\psi$, then one of these statements must imply the other in each world of our model. The second of these axioms says that if an agent has {\em opposite} potential emotions about statements $\phi$ and $\psi$, then these statements cannot be both true in any world of the model. We prove soundness of these axioms along with the soundness of the other axioms of our system in Section~\ref{Soundness section}. The Counterfactual axiom states that an agent cannot have an emotion about something which is universally true in the model. This axiom reflects items 6(c) and 7(c) of Definition~\ref{sat}. Because the assumptions of both Emotional Predictability axioms contain disjunctions, each of these axioms could be split into two statements. The first statement of the first Emotional Predictability axiom says that if an agent is potentially happy about $\phi$, then she must be happy about $\phi$ each time when she knows that $\phi$ is true. The second statement of the same axiom says that if an agent is potentially sad about $\neg\phi$, then she must be happy about $\phi$ each time when she knows that $\phi$ is true. The second Emotional Predictability axioms is the dual form of the first axiom. Finally, the Substitution axiom states that if two statements are equivalent in each world of the model and an agent has an emotion about one of them, then she must have the same emotion about the other statement. We write $\vdash\phi$ and say that statement $\phi$ is a {\em theorem} of our logical system if $\phi$ is derivable from the above axioms using the Modus Ponens and the Necessitation inference rules: $$ \dfrac{\phi, \phi\to\psi}{\psi}\hspace{20mm} \dfrac{\phi}{{\sf N}\phi}. $$ For any set of statements $X\subseteq\Phi$, we write $X\vdash\phi$ if formula $\phi$ is derivable from the theorems of our system and the set $X$ using only the Modus Ponens inference rule. We say that set $X$ is {\em inconsistent} if there is a formula $\phi\in\Phi$ such that $X\vdash\phi$ and $X\vdash\neg\phi$. \begin{lemma}\label{K Necessitation} Inference rule $\dfrac{\phi}{{\sf K}_a\phi}$ is derivable. \end{lemma} \begin{proof} This rule is a combination of the Necessitation inference rule, the Knowledge of Necessity axiom, and the Modus Ponens inference rule. \end{proof} \begin{lemma}\label{E to K} $\vdash {\sf E}_a\phi\to{\sf K}_a\phi$. \end{lemma} \begin{proof} Note that $\vdash {\sf E}_a\phi\to\phi$ by the Truth axiom. Thus, $\vdash {\sf K}_a({\sf E}_a\phi\to\phi)$ by Lemma~\ref{K Necessitation}. Hence, $\vdash {\sf K}_a{\sf E}_a\phi\to{\sf K}_a\phi$ by the Distributivity axiom and the Modus Ponens inference rule. Therefore, $\vdash {\sf E}_a\phi\to{\sf K}_a\phi$ by the Emotional Introspection axiom and propositional reasoning. \end{proof} The next three lemmas are well-known in model logic. We reproduce their proofs here to keep the article self-contained. \begin{lemma}[deduction]\label{deduction lemma} If $X,\phi\vdash\psi$, then $X\vdash\phi\to\psi$. \end{lemma} \begin{proof} Suppose that sequence $\psi_1,\dots,\psi_n$ is a proof from set $X\cup\{\phi\}$ and the theorems of our logical system that uses the Modus Ponens inference rule only. In other words, for each $k\le n$, either \begin{enumerate} \item $\vdash\psi_k$, or \item $\psi_k\in X$, or \item $\psi_k$ is equal to $\phi$, or \item there are $i,j<k$ such that formula $\psi_j$ is equal to $\psi_i\to\psi_k$. \end{enumerate} It suffices to show that $X\vdash\phi\to\psi_k$ for each $k\le n$. We prove this by induction on $k$ through considering the four cases above separately. \vspace{1mm} \noindent{\em Case I}: $\vdash\psi_k$. Note that $\psi_k\to(\phi\to\psi_k)$ is a propositional tautology, and thus, is an axiom of our logical system. Hence, $\vdash\phi\to\psi_k$ by the Modus Ponens inference rule. Therefore, $X\vdash\phi\to\psi_k$. \vspace{1mm} \noindent{\em Case II}: $\psi_k\in X$. Then, $X\vdash\psi_k$. \vspace{1mm} \noindent{\em Case III}: formula $\psi_k$ is equal to $\phi$. Thus, $\phi\to\psi_k$ is a propositional tautology. Therefore, $X\vdash\phi\to\psi_k$. \vspace{1mm} \noindent{\em Case IV}: formula $\psi_j$ is equal to $\psi_i\to\psi_k$ for some $i,j<k$. Thus, by the induction hypothesis, $X\vdash\phi\to\psi_i$ and $X\vdash\phi\to(\psi_i\to\psi_k)$. Note that formula $ (\phi\to\psi_i)\to((\phi\to(\psi_i\to\psi_k))\to(\phi\to\psi_k)) $ is a propositional tautology. Therefore, $X\vdash \phi\to\psi_k$ by applying the Modus Ponens inference rule twice. \end{proof} \begin{lemma}\label{superdistributivity lemma} If $\phi_1,\dots,\phi_n\vdash\psi$, then $\Box\phi_1,\dots,\Box\phi_n\vdash\Box\psi$, where $\Box$ is either modality ${\sf N}$ or modality ${\sf K}_a$. \end{lemma} \begin{proof} Lemma~\ref{deduction lemma} applied $n$ times to assumption $\phi_1,\dots,\phi_n\vdash\psi$ implies that $\vdash\phi_1\to(\dots\to(\phi_n\to\psi)\dots)$. Thus, $\vdash\Box(\phi_1\to(\dots\to(\phi_n\to\psi)\dots))$, by either the Necessitation inference rule (if $\Box$ is modality ${\sf N}$) or Lemma~\ref{K Necessitation} (if $\Box$ is modality ${\sf K}$). Hence, by the Distributivity axiom and the Modus Ponens inference rule, $$\vdash\Box\phi_1\to\Box(\phi_2\dots\to(\phi_n\to\psi)\dots).$$ Then, $\Box\phi_1\vdash\Box(\phi_2\dots\to(\phi_n\to\psi)\dots)$ by the Modus Ponens inference rule. Thus, again by the Distributivity axiom and the Modus Ponens inference rule, $\Box\phi_1\vdash\Box\phi_2\to \Box(\phi_3\dots\to(\phi_n\to\psi)\dots)$. Therefore, $\Box\phi_1,\dots,\Box\phi_n\vdash\Box\psi$, by repeating the last two steps $n-2$ times. \end{proof} \begin{lemma}[positive introspection]\label{positive introspection lemma} $\vdash \Box\phi\to\Box\Box\phi$, where $\Box$ is either modality ${\sf N}$ or modality ${\sf K}_a$. \end{lemma} \begin{proof} Formula $\Box\neg\Box\phi\to\neg\Box\phi$ is an instance of the Truth axiom. Thus, by contraposition, $\vdash \Box\phi\to\neg\Box\neg\Box\phi$. Hence, taking into account the following instance of the Negative Introspection axiom: $\neg\Box\neg\Box\phi\to\Box\neg\Box\neg\Box\phi$, we have \begin{equation}\label{pos intro eq 2} \vdash \Box\phi\to\Box\neg\Box\neg\Box\phi. \end{equation} At the same time, $\neg\Box\phi\to\Box\neg\Box\phi$ is an instance of the Negative Introspection axiom. Thus, $\vdash \neg\Box\neg\Box\phi\to \Box\phi$ by the law of contrapositive in the propositional logic. Hence, $\vdash \Box(\neg\Box\neg\Box\phi\to \Box\phi)$ by either the Necessitation inference rule (if $\Box$ is modality ${\sf N}$) or Lemma~\ref{K Necessitation} (if $\Box$ is modality ${\sf K}$). Thus, by the Distributivity axiom and the Modus Ponens inference rule, $ \vdash \Box\neg\Box\neg\Box\phi\to \Box\Box\phi. $ The latter, together with statement~(\ref{pos intro eq 2}), implies the statement of the lemma by propositional reasoning. \end{proof} \begin{lemma}\label{N biconditional lemma} ~ \begin{enumerate} \item ${\sf N}(\phi\to\psi),{\sf N}(\neg\phi\to\neg\psi)\vdash {\sf N}(\phi\leftrightarrow \psi)$, \item ${\sf N}(\phi\to\neg\psi),{\sf N}(\neg\phi\to\psi)\vdash {\sf N}(\phi\leftrightarrow \neg\psi)$. \end{enumerate} \end{lemma} \begin{proof} It is provable in the propositional logic that $\phi\to\psi,\neg\phi\to\neg\psi\vdash \phi\leftrightarrow \psi$. Thus, ${\sf N}(\phi\to\psi),{\sf N}(\neg\phi\to\neg\psi)\vdash {\sf N}(\phi\leftrightarrow \psi)$ by Lemma~\ref{superdistributivity lemma}. The proof of the second part of the lemma is similar. \end{proof} \begin{lemma}\label{substitution lemma} ~ \begin{enumerate} \item ${\sf N}(\phi\leftrightarrow\psi), {\sf \overline{N}}\H_a\phi \vdash {\sf \overline{N}}\H_a\psi$, \item ${\sf N}(\phi\leftrightarrow\psi), {\sf \overline{N}}\S_a\neg\phi\vdash {\sf \overline{N}}\S_a\neg\psi$, \item ${\sf N}(\phi\leftrightarrow\neg\psi), {\sf \overline{N}}\S_a\neg\phi\vdash {\sf \overline{N}}\S_a\psi$. \end{enumerate} \end{lemma} \begin{proof} Formula ${\sf N}(\phi\leftrightarrow\psi)\to(\H_a\phi\to\H_a\psi)$ is an instance of the Substitution axiom. Thus, $\vdash {\sf N}(\phi\leftrightarrow\psi)\to(\neg\H_a\psi\to\neg\H_a\phi)$ by the laws of propositional reasoning. Hence, ${\sf N}(\phi\leftrightarrow\psi),\neg\H_a\psi\vdash \neg\H_a\phi$ by the Modus Ponens rule applied twice. Then, ${\sf N}\N(\phi\leftrightarrow\psi),{\sf N}\neg\H_a\psi\vdash {\sf N}\neg\H_a\phi$ by Lemma~\ref{superdistributivity lemma}. Thus, by Lemma~\ref{positive introspection lemma} and the Modus Ponens inference rule, ${\sf N}(\phi\leftrightarrow\psi),{\sf N}\neg\H_a\psi\vdash {\sf N}\neg\H_a\phi$. Hence, ${\sf N}(\phi\leftrightarrow\psi)\vdash{\sf N}\neg\H_a\psi\to{\sf N}\neg\H_a\phi$ by Lemma~\ref{deduction lemma}. Then, by the laws of propositional reasoning, ${\sf N}(\phi\leftrightarrow\psi)\vdash\neg{\sf N}\neg\H_a\phi\to\neg{\sf N}\neg\H_a\psi$. Thus, by the definition of modality ${\sf \overline{N}}$, we have ${\sf N}(\phi\leftrightarrow\psi)\vdash{\sf \overline{N}}\H_a\phi\to{\sf \overline{N}}\H_a\psi$. Therefore, by the Modus Ponens inference rule, ${\sf N}(\phi\leftrightarrow\psi),{\sf \overline{N}}\H_a\phi\vdash{\sf \overline{N}}\H_a\psi$. To prove the second statement, observe that $(\phi\leftrightarrow\psi)\to(\neg\phi\leftrightarrow\neg\psi)$ is a propositional tautology. Thus, $\phi\leftrightarrow\psi\vdash \neg\phi\leftrightarrow\neg\psi$ by the Modus Ponens inference rule. Hence, ${\sf N}(\phi\leftrightarrow\psi)\vdash {\sf N}(\neg\phi\leftrightarrow\neg\psi)$ by Lemma~\ref{superdistributivity lemma}. Then, to prove of the second statement, it suffices to show that ${\sf N}(\neg\phi\leftrightarrow\neg\psi), {\sf \overline{N}}\S_a\neg\phi\vdash {\sf \overline{N}}\S_a\neg\psi$. The proof of this is the same as of the first statement. The proof of the third statement is similar to the proof of the second, but it starts with the tautology $(\phi\leftrightarrow\neg\psi)\to(\neg\phi\leftrightarrow\psi)$. \end{proof} \begin{lemma}[Lindenbaum]\label{Lindenbaum's lemma} Any consistent set of formulae can be extended to a maximal consistent set of formulae. \end{lemma} \begin{proof} The standard proof of Lindenbaum's lemma applies here~\cite[Proposition 2.14]{m09}. \end{proof} \section{Soundness}\label{Soundness section} The Truth, the Distributivity, and the Negative Introspection axioms for modalities ${\sf K}$ and ${\sf N}$ are well-known principles of S5 logic. The soundness of the Knowledge of Necessity axiom follows from Definition~\ref{sat}. Below we prove the soundness of each of the remaining axioms as a separate lemma. We state strong soundness as Theorem~\ref{soundness theorem} in the end of the section. In the lemmas below we assume that $w\in W$ is an arbitrary world of an epistemic model with preferences $M=(W,\{\sim_a\}_{a\in\mathcal{A}},\{\prec_a\}_{a\in\mathcal{A}},\pi)$. \begin{lemma} If $w\Vdash {\sf E}_a\phi$, then $w\Vdash \phi$. \end{lemma} \begin{proof} First, we consider the case ${\sf E}=\H$. Note that $w\sim_a w$ because $\sim_a$ is an equivalence relation. Thus, the assumption $w\Vdash \H_a\phi$ implies $w\Vdash \phi$ by item 6(a) of Definition~\ref{sat}. The proof for the case ${\sf E}=\S$ is similar, but it uses item 7(a) of Definition~\ref{sat} instead of item 6(a). \end{proof} \begin{lemma} If $w\Vdash {\sf E}_a\phi$, then $w\Vdash {\sf K}_a{\sf E}_a\phi$. \end{lemma} \begin{proof} First, we consider the case ${\sf E}=\H$. Consider any world $w'\in W$ such that $w\sim_a w'$. By item 5 of Definition~\ref{sat}, it suffices to show that $w'\Vdash \H_a\phi$. Indeed, by item 6 of Definition~\ref{sat}, the assumption $w\Vdash \H_a\phi$ of the lemma implies that \begin{enumerate} \item[(a)] $u\Vdash \phi$ for each world $u\in W$ such that $w\sim_a u$, \item[(b)] for any two worlds $u,u'\in W$, if $u\nVdash\phi$ and $u'\Vdash\phi$, then $u\prec_a u'$, \item[(c)] there is a world $u\in W$ such that $u\nVdash\phi$, \end{enumerate} By the assumption $w\sim_a w'$, statement (a) implies that \begin{enumerate} \item[(a')] $u\Vdash \phi$ for each world $u\in W$ such that $w'\sim_a u$. \end{enumerate} Finally, statements (a'), (b), and (c) imply that $w'\Vdash \H_a\phi$ by item 6 of Definition~\ref{sat}. The proof for the case ${\sf E}=\S$ is similar, but it uses item 7 of Definition~\ref{sat} instead of item 6. \end{proof} \begin{lemma} If $w\Vdash \H_a\phi$, then $w\nVdash \S_a\phi$. \end{lemma} \begin{proof} By item 6(a) of Definition~\ref{sat}, the assumption $w\Vdash \H_a\phi$ implies that $w\Vdash \phi$. By item 6(c) of Definition~\ref{sat}, the same assumption implies that there is a world $w'\in W$ such that $w'\nVdash\phi$. By item 6(b) of Definition~\ref{sat} the assumption $w\Vdash \H_a\phi$ and statements $w'\nVdash \phi$ and $w\Vdash\phi$ imply that $w'\prec_a w$. Thus, $w\nprec_a w'$ because relation $\prec_a$ is a strict partial order. Therefore, $w\nVdash \S_a\phi$ by item 7(b) of Definition~\ref{sat} and statements $w\Vdash \phi$ and $w'\nVdash \phi$. \end{proof} \begin{lemma} If $w\Vdash {\sf \overline{N}}{\sf E}_a\phi$ and $w\Vdash {\sf \overline{N}}{\sf E}_a\psi$, then either $w\Vdash {\sf N}(\phi\to\psi)$ or $w\Vdash {\sf N}(\psi\to\phi)$. \end{lemma} \begin{proof} First, we consider the case ${\sf E}=\H$. Suppose that $w\nVdash {\sf N}(\phi\to\psi)$ and $w\nVdash {\sf N}(\psi\to\phi)$. Thus, by item 4 of Definition~\ref{sat}, there are epistemic worlds $w_1,w_2\in W$, such that $w_1\nVdash \phi\to\psi$ and $w_2\nVdash \psi\to\phi$. Hence, by item 3 of Definition~\ref{sat}, \begin{equation}\label{nov16-big} w_1\Vdash \phi, \hspace{5mm} w_1\nVdash \psi, \hspace{5mm} w_2\Vdash \psi, \hspace{5mm} w_2\nVdash \phi. \end{equation} At the same time, by the definition of modality ${\sf \overline{N}}$ and items 2 and 4 of Definition~\ref{sat}, the assumption $w\Vdash {\sf \overline{N}}\H_a\phi$ of the lemma implies that there is a world $w'$ such that $w'\Vdash \H_a\phi$. Hence, $w_2\prec_a w_1$ by item 6(b) of Definition~\ref{sat} and parts $ w_2\nVdash \phi$ and $w_1\Vdash \phi$ of statement~(\ref{nov16-big}). Similarly, the assumption $w\Vdash {\sf \overline{N}}\H_a\psi$ of the lemma and parts $ w_1\nVdash \psi$ and $w_2\Vdash \psi$ of statement~(\ref{nov16-big}) imply that $w_1\prec_a w_2$. Note that statements $w_2\prec_a w_1$ and $w_1\prec_a w_2$ are inconsistent because relation $\prec_a$ is a strict partial order. The proof in the case ${\sf E}=\S$ is similar, but it uses item 7(b) of Definition~\ref{sat} instead of item 6(b). \end{proof} \begin{lemma} If $w\Vdash {\sf \overline{N}}\H_a\phi$ and $w\Vdash {\sf \overline{N}}\S_a\psi$, then either $w\Vdash {\sf N}(\phi\to\neg\psi)$ or $w\Vdash {\sf N}(\neg\psi\to\phi)$. \end{lemma} \begin{proof} Suppose that $w\nVdash {\sf N}(\phi\to\neg\psi)$ and $w\nVdash {\sf N}(\neg\psi\to\phi)$. Thus, by item 4 of Definition~\ref{sat}, there are epistemic worlds $w_1,w_2\in W$, such that $w_1\nVdash \phi\to\neg\psi$ and $w_2\nVdash \neg\psi\to\phi$. Hence, by item 3 and item 2 of Definition~\ref{sat}, \begin{equation}\label{nov17-big} w_1\Vdash \phi, \hspace{5mm} w_1\Vdash \psi, \hspace{5mm} w_2\nVdash \psi, \hspace{5mm} w_2\nVdash \phi. \end{equation} At the same time, by the definition of modality ${\sf \overline{N}}$ and items 2 and 4 of Definition~\ref{sat}, the assumption $w\Vdash {\sf \overline{N}}\H_a\phi$ of the lemma implies that there is a world $w'$ such that $w'\Vdash \H_a\phi$. Hence, $w_2\prec_a w_1$ by item 6(b) of Definition~\ref{sat} and parts $ w_2\nVdash \phi$ and $w_1\Vdash \phi$ of statement~(\ref{nov17-big}). Also, by item 7(b) of Definition~\ref{sat}, the assumption $w\Vdash {\sf \overline{N}}\S_a\psi$ of the lemma and parts $ w_1\Vdash \psi$ and $w_2\nVdash \psi$ of statement~(\ref{nov17-big}) imply that $w_1\prec_a w_2$. Note that statements $w_2\prec_a w_1$ and $w_1\prec_a w_2$ are inconsistent because relation $\prec_a$ is a strict partial order. \end{proof} \begin{lemma} If $w\Vdash {\sf E}_a\phi$, then $w\nVdash {\sf N}\phi$. \end{lemma} \begin{proof} First, suppose that ${\sf E}=\H$. Then, by item 6(c) of Definition~\ref{sat}, the assumption $w\Vdash {\sf E}_a\phi$ implies that there is an epistemic world $u\in W$ such that $u\nVdash\phi$. Therefore, $w\nVdash {\sf N}\phi$ by item 4 of Definition~\ref{sat}. The proof in the case ${\sf E}=\S$ is similar, but it uses item 7(c) of Definition~\ref{sat} instead of item 6(c). \end{proof} \begin{lemma}\label{first emotional predictability sound} If either $w\Vdash {\sf \overline{N}}\H_a\phi$ or $w\Vdash {\sf \overline{N}}\S_a\neg\phi$, then statement $w\Vdash {\sf K}_a\phi$ implies $w\Vdash \H_a\phi$. \end{lemma} \begin{proof} First, suppose that $w\Vdash {\sf \overline{N}}\H_a\phi$. Thus, by the definition of modality ${\sf \overline{N}}$ and items 2 and 4 of Definition~\ref{sat}, there is an epistemic world $w'\in W$ such that $w'\Vdash \H_a\phi$. Hence, by item 6 of Definition~\ref{sat}, \begin{enumerate} \item[(a)] $u\Vdash \phi$ for each world $u\in W$ such that $w'\sim_a u$, \item[(b)] for any two worlds $u,u'\in W$, if $u\nVdash\phi$ and $u'\Vdash\phi$, then $u\prec_a u'$, \item[(c)] there is a world $u\in W$ such that $u\nVdash\phi$. \end{enumerate} Also, by item 5 of Definition~\ref{sat}, the assumption $w\Vdash {\sf K}_a\phi$ implies that \begin{enumerate} \item[(a')] $u\Vdash \phi$ for each world $u\in W$ such that $w\sim_a u$. \end{enumerate} By item 6 of Definition~\ref{sat}, statements (a'), (b), and (c) imply $w\Vdash \H_a\phi$. \vspace{1mm} Next, suppose that $w\Vdash {\sf \overline{N}}\S_a\neg\phi$. Thus, by the definition of modality ${\sf \overline{N}}$ and items 2 and 4 of Definition~\ref{sat}, there is an epistemic world $w'\in W$ such that $w'\Vdash \S_a\neg\phi$. Hence, by item 7 of Definition~\ref{sat}, \begin{enumerate} \item[(a)] $u\Vdash \neg\phi$ for each world $u\in W$ such that $w'\sim_a u$, \item[(b)] for any two worlds $u,u'\in W$, if $u\Vdash\neg\phi$ and $u'\nVdash\neg\phi$, then $u\prec_a u'$, \item[(c)] there is a world $u\in W$ such that $u\nVdash\neg\phi$. \end{enumerate} Also, by item 5 of Definition~\ref{sat}, the assumption $w\Vdash {\sf K}_a\phi$ implies that \begin{enumerate} \item[(a')] $u\Vdash \phi$ for each world $u\in W$ such that $w\sim_a u$. \end{enumerate} Note that by item 2 of Definition~\ref{sat}, statement (b) implies that \begin{enumerate} \item[(b')] for any two worlds $u,u'\in W$, if $u\nVdash\phi$ and $u'\Vdash\phi$, then $u\prec_a u'$. \end{enumerate} And, by item 2 of Definition~\ref{sat}, statement (a) implies that \begin{enumerate} \item[(c')] $w'\nVdash \phi$ \end{enumerate} because relation $\sim_a$ is reflexive. Finally, note that by item 6 of Definition~\ref{sat}, statements (a'), (b'), and (c') imply $w\Vdash \H_a\phi$. \end{proof} The proof of the next lemma is using the converse models and translation $\tau$ that have been introduced in Definition~\ref{converse model} and Definition~\ref{tau translation} respectively. \begin{lemma} If either $w\Vdash {\sf \overline{N}}\H_a\neg\phi$ or $w\Vdash {\sf \overline{N}}\S_a\phi$, then statement $w\Vdash {\sf K}_a\phi$ implies $w\Vdash \S_a\phi$. \end{lemma} \begin{proof} Let $M^\c$ be the converse model of the epistemic model with preferences $M$ and $\Vdash^\c$ is the satisfaction relation for the model $M^\c$. By Lemma~\ref{first emotional predictability sound}, if either $w\Vdash^\c {\sf \overline{N}}\H_a\tau(\phi)$ or $w\Vdash^c {\sf \overline{N}}\S_a\neg\tau(\phi)$, then statement $w\Vdash^c {\sf K}_a\tau(\phi)$ implies $w\Vdash^\c \H_a\tau(\phi)$. Thus, by Definition~\ref{tau translation}, if either $w\Vdash^\c \tau({\sf \overline{N}}\S_a\phi)$ or $w\Vdash^c \tau({\sf \overline{N}}\H_a\neg\phi)$, then statement $w\Vdash^c \tau({\sf K}_a\phi)$ implies $w\Vdash^\c \tau(\S_a\phi)$. Therefore, by Theorem~\ref{duality theorem}, if either $w\Vdash {\sf \overline{N}}\S_a\phi$ or $w\Vdash {\sf \overline{N}}\H_a\neg\phi$, then statement $w\Vdash {\sf K}_a\phi$ implies $w\Vdash \S_a\phi$. \end{proof} \begin{lemma} If $w\Vdash {\sf N}(\phi\leftrightarrow\psi)$ and $w\Vdash {\sf E}_a\phi$, then $w\Vdash {\sf E}_a\psi$. \end{lemma} \begin{proof} First, we consider the case ${\sf E}=\H$. By item 6 of Definition~\ref{sat}, the assumption $w\Vdash \H_a\phi$ implies that \begin{enumerate} \item[(a)] $u\Vdash \phi$ for each world $u\in W$ such that $w\sim_a u$, \item[(b)] for any two worlds $u,u'\in W$, if $u\nVdash\phi$ and $u'\Vdash\phi$, then $u\prec_a u'$, \item[(c)] there is a world $u\in W$ such that $u\nVdash\phi$. \end{enumerate} Thus, by the assumption $w\Vdash {\sf N}(\phi\leftrightarrow\psi)$ and item 4 of Definition~\ref{sat}, \begin{enumerate} \item[(a')] $u\Vdash \psi$ for each world $u\in W$ such that $w\sim_a u$, \item[(b')] for any two worlds $u,u'\in W$, if $u\nVdash\psi$ and $u'\Vdash\psi$, then $u\prec_a u'$, \item[(c')] there is a world $u\in W$ such that $u\nVdash\psi$. \end{enumerate} By item 6 of Definition~\ref{sat}, statements (a'), (b'), and (c') imply $w\Vdash \H_a\psi$. The proof in the case ${\sf E}=\S$ is similar, but it uses item 7 of Definition~\ref{sat} instead of item 6. \end{proof} The strong soundness theorem below follows from the lemmas proven above. \begin{theorem}\label{soundness theorem} For any epistemic world $w$ of an epistemic model with preferences, any set of formulae $X\subseteq \Phi$, and any formula $\phi\in\Phi$, if $w\Vdash\chi$ for each formula $\chi\in X$ and $X\vdash\phi$, then $w\Vdash\phi$. \qed \end{theorem} \section{Utilitarian Emotions}\label{Utilitarian Emotions} Lang, van er Torre, and Weydert introduced a notion of utilitarian desire which is based on a utility function rather than a preference relation~\cite{lvw02aamas}. Although desire, as an emotion, is different from the happiness and sadness emotions that we study in this article, their approach could be adopted to happiness and sadness as well. To do this, one needs to modify Definition~\ref{epistemic model with preferences} to include agent-specific utility functions instead of agent-specific preference relations: \begin{definition}\label{epistemic model with utilities} A tuple $(W,\{\sim_a\}_{a\in\mathcal{A}},\{u_a\}_{a\in\mathcal{A}},\pi)$ is called an epistemic model with utilities if \begin{enumerate} \item $W$ is a set of epistemic worlds, \item $\sim_a$ is an ``indistinguishability'' equivalence relation on set $W$ for each agent $a\in\mathcal{A}$, \item $u_a$ is a ``utility'' function from set $W$ to real numbers for each agent $a\in\mathcal{A}$, \item $\pi(p)$ is a subset of $W$ for each propositional variable $p$. \end{enumerate} \end{definition} Below is the definition of the satisfaction relation for epistemic model with utilities. Its parts 6(b) and 7(b) are similar to Lang, van er Torre, and Weydert utilitarian desire definition in \cite{lvw02aamas}. Unlike the current article, \cite{lvw02aamas} does not prove any completeness results. In the definition below we assume that language $\Phi$ is modified to incorporate a no-negative real ``degree'' parameter into modalities $\H^d_a$ and $\S^d_a$. We read statement $\H^d_a\phi$ as ``agent $a$ is happy about $\phi$ with degree $d$''. Similarly, we read $\S^d_a\phi$ as ``agent $a$ is sad about $\phi$ with degree $d$''. \begin{definition}\label{sat-u} For any epistemic model with utilities $(W,\{\sim_a\}_{a\in\mathcal{A}},\{u_a\}_{a\in\mathcal{A}},\pi)$, any world $w\in W$, and any formula $\phi\in\Phi$, satisfaction relation $w\Vdash\phi$ is defined as follows: \begin{enumerate} \item $w\Vdash p$, if $w\in \pi(p)$, \item $w\Vdash\neg\phi$, if $w\nVdash\phi$, \item $w\Vdash\phi\to\psi$, if $w\nVdash\phi$ or $w\Vdash\psi$, \item $w\Vdash{\sf N}\phi$, if $v\Vdash \phi$ for each world $v\in W$, \item $w\Vdash{\sf K}_a\phi$, if $v\Vdash \phi$ for each world $v\in W$ such that $w\sim_a v$, \item $w\Vdash \H^d_a\phi$, if the following three conditions are satisfied: \begin{enumerate} \item $v\Vdash \phi$ for each world $v\in W$ such that $w\sim_a v$, \item for any $v,v'\in W$, if $v\nVdash\phi$ and $v'\Vdash\phi$, then $u_a(v)+d\le u_a(v')$, \item there is a world $v\in W$ such that $v\nVdash\phi$, \end{enumerate} \item $w\Vdash \S^d_a\phi$, if the following three conditions are satisfied: \begin{enumerate} \item $v\Vdash \phi$ for each world $v\in W$ such that $w\sim_a u$, \item for any worlds $v,v'\in W$, if $v\Vdash\phi$ and $v'\nVdash\phi$, then $u_a(v)+d\le u_a(v')$, \item there is a world $u\in W$ such that $u\nVdash\phi$. \end{enumerate} \end{enumerate} \end{definition} We have already defined utility functions for our Battle of Cuisines scenario, see Section~\ref{The Battle of Cuisines Scenario section}. In the two propositions below we use this scenario to illustrate utilitarian happiness modality. Note how Sanaz is much happier to be with Pavel in a Russian restaurant than she is to be with him in a restaurant. \begin{proposition}\label{oct27 Hs} $(x,x)\Vdash \H^1_s(\mbox{``Sanaz and Pavel are in the same restaurant''})$, where $x\in \{\mbox{Iranian},\mbox{Russian}\}$. \end{proposition} \begin{proof} We verify conditions (a), (b), and (c) from item 6 of Definition~\ref{sat-u}: \vspace{1mm} \noindent{\em Condition a:} Consider any epistemic world $(y,z)$ such that $(x,x)\sim_s (y,z)$. It suffices to show that $(y,z)\Vdash \mbox{``Sanaz and Pavel are in the same restaurant''}$. The latter is true because assumption $(x,x)\sim_s (y,z)$ implies that $x=y$ and $x=z$ in the perfect information setting of the Battle of Cuisines scenario. \vspace{1mm} \noindent{\em Condition b:} Consider any worlds $(y,z)$ and $(y',z')$ such that \begin{eqnarray} (y,z)\nVdash \mbox{``Sanaz and Pavel are in the same restaurant''},\label{nov2-a}\\ (y',z')\Vdash \mbox{``Sanaz and Pavel are in the same restaurant''}.\label{nov2-b} \end{eqnarray} Statement~(\ref{nov2-a}) implies that $u_s(y,z)=0$, see Table~\ref{example table figure}. Similarly, statement~(\ref{nov2-b}) implies that $u_s(y',z')\ge 1$. Therefore, $u_s(y,z)+1=1\le u_s(y',z')$. \vspace{1mm} \noindent{\em Condition c:} $(\mathrm{Russian},\mathrm{Iranian})\nVdash\mbox{``Sanaz and Pavel are in the same restaurant''}$. \end{proof} \begin{proposition}\label{nov2 Hs} $$(\mathrm{Russian},\mathrm{Russian})\Vdash \H^2_s(\mbox{``Sanaz and Pavel are in the Russian restaurant''}).$$ \end{proposition} \begin{proof} Conditions (a) and (c) from item 6 of Definition~\ref{sat-u} could be verified similarly to the proof of Proposition~\ref{oct27 Hs}. Below we verify condition (b). Consider any worlds $(y,z)$ and $(y',z')$ such that \begin{eqnarray} (y,z)\nVdash \mbox{``Sanaz and Pavel are in the Russian restaurant''},\label{nov2-c}\\ (y',z')\Vdash \mbox{``Sanaz and Pavel are in the Russian restaurant''}.\label{nov2-d} \end{eqnarray} Statement~(\ref{nov2-c}) implies that $u_s(y,z)\le 1$, see Table~\ref{example table figure}. Similarly, statement~(\ref{nov2-d}) implies that $u_s(y',z')= 3$. Therefore, $u_s(y,z)+2\le 1 + 2 = 3= u_s(y',z')$. \end{proof} \section{Goodness-Based Emotions}\label{Goodness-Based Emotions} Lorini and Schwarzentruber proposed a different framework for defining emotions~\cite{ls11ai}. Instead of specifying preference relations on the epistemic worlds they label some of worlds as desirable or ``good''. In such a setting they define modalities ``rejoice'' and ``disappointment'' that are similar to our modalities ``happiness'' and ``sadness''. In this section we compare their approach to ours. Although their framework endows agents with actions, it appears that actions are essential for defining regret and are less important for capturing rejoice and disappointment. In the definition below, we simplify Lorini and Schwarzentruber's framework to action-less models that we call epistemic model with goodness. \begin{definition}\label{epistemic model with goodness} A tuple $(W,\{\sim_a\}_{a\in\mathcal{A}},\{G_a\}_{a\in\mathcal{A}},\pi)$ is called an epistemic model with goodness if \begin{enumerate} \item $W$ is a set of epistemic worlds, \item $\sim_a$ is an ``indistinguishability'' equivalence relation on set $W$ for each agent $a\in\mathcal{A}$, \item $G_a\subseteq W$ is a nonempty set of ``good'' epistemic worlds for agent $a\in\mathcal{A}$, \item $\pi(p)$ is a subset of $W$ for each propositional variable $p$. \end{enumerate} \end{definition} To represent the gift example from Figure~\ref{example gift figure} as an epistemic model with goodness, we need to specify the sets of good epistemic worlds $G_s$ and $G_p$ of Sanaz and Pavel. A natural way to do this is to assume that $G_s=G_p=\{w\}$. In other words, the ideal outcome for both of them would be if the gift and the card arrives to the recipients. In the lottery example, the desirable outcome for each agent is when the agents wins the lottery. In other words, $G_s=\{u\}$, $G_p=\{w\}$, and $G_o=\{v\}$, see Figure~\ref{example lottery figure}. In the Battle of Cuisines example captured in Table~\ref{example table figure}, the choice of good epistemic worlds is not obvious. On one hand, we can assume that good worlds for both Sanaz and Pavel are the ones where they have positive pay-offs. In this case, $G_s=G_p=\{(\mathrm{Iranian},\mathrm{Iranian}),(\mathrm{Russian},\mathrm{Russian})\}$. Alternatively, we can choose the good worlds to be those where they get maximal pay-off. In that case, $G_s=\{(\mathrm{Russian},\mathrm{Russian})\}$ and $G_p=\{(\mathrm{Iranian},\mathrm{Iranian})\}$. Note that our epistemic models with preferences approach provides a more fine-grained semantics that does not force the choice between these two alternatives. In the definition below, we rephrase Lorini and Schwarzentruber's formal definitions of ``rejoice'' and ``disappointment'' in terms of epistemic models with goodness. We denote modalities ``rejoice'' and ``disappointment'' by $\H$ and $\S$ respectively to be consistent with the notations in the rest of this article. \begin{definition}\label{sat with goodness} For any world $w\in W$ of an epistemic model with goodness $(W,\{\sim_a\}_{a\in\mathcal{A}},\{G_a\}_{a\in\mathcal{A}},\pi)$ and any formula $\phi\in\Phi$, satisfaction relation $w\Vdash\phi$ is defined as follows: \begin{enumerate} \item $w\Vdash p$, if $w\in \pi(p)$, \item $w\Vdash\neg\phi$, if $w\nVdash\phi$, \item $w\Vdash\phi\to\psi$, if $w\nVdash\phi$ or $w\Vdash\psi$, \item $w\Vdash{\sf N}\phi$, if $u\Vdash \phi$ for each world $u\in W$, \item\label{item K} $w\Vdash{\sf K}_a\phi$, if $u\Vdash \phi$ for each world $u\in W$ such that $w\sim_a u$, \item\label{item H} $w\Vdash \H_a\phi$, if the following three conditions are satisfied: \begin{enumerate} \item $u\Vdash \phi$ for each world $u\in W$ such that $w\sim_a u$, \item $u\Vdash\phi$ for each world $u \in G_a$, \item there is a world $u\in W$ such that $u\nVdash\phi$, \end{enumerate} \item $w\Vdash \S_a\phi$, if the following three conditions are satisfied: \begin{enumerate} \item $u\Vdash \phi$ for each world $u\in W$ such that $w\sim_a u$, \item $u\nVdash\phi$ for each world $u \in G_a$, \item there is a world $u\in W$ such that $u\nVdash\phi$. \end{enumerate} \end{enumerate} \end{definition} Consider the discussed above epistemic model with goodness for the gift scenario in which $G_s=G_p=\{w\}$. It is relatively easy to see that all propositions that we proved in Section~\ref{gift scenario section} for preference-based semantics hold true under goodness-based semantics of modalities $\H$ and $\S$ given in Definition~\ref{sat with goodness}. The situation is different for the Battle of Cuisines scenario. If $\Vdash_1$ denotes the satisfaction relation of the epistemic model with goodness where $G_s=G_p=\{(\mathrm{Iranian},\mathrm{Iranian}),(\mathrm{Russian},\mathrm{Russian})\}$, then the following two propositions are true just like they are under our definition of happiness (see Proposition~\ref{sept25 Hs} and Proposition~\ref{oct19-rr}): \begin{proposition}\label{oct19-rr2} $$(\mathrm{Russian},\mathrm{Russian})\Vdash_1 \H_s(\mbox{``Sanaz and Pavel are in the same restaurant''}).$$ \end{proposition} \begin{proof} It suffices to verify conditions (a), (b), and (c) of item 6 of Definition~\ref{sat with goodness}: \vspace{1mm} \noindent{\em Condition a:} Since the Battle of the Cuisines is a setting with perfect information, it suffices to show that $$(\mathrm{Russian},\mathrm{Russian})\Vdash_1 (\mbox{``Sanaz and Pavel are in the same restaurant''}).$$ The last statement is true by the definition of the world $(\mathrm{Russian},\mathrm{Russian})$. \vspace{1mm} \noindent{\em Condition b:} Statement ``Sanaz and Pavel are in the same restaurant'' is satisfied in both good worlds: $(\mathrm{Iranian},\mathrm{Iranian})$ and $(\mathrm{Russian},\mathrm{Russian})$. \vspace{1mm} \noindent{\em Condition c:} Statement ``Sanaz and Pavel are in the same restaurant'' is not satisfied in the world $(\mathrm{Russian},\mathrm{Iranian})$. \end{proof} \begin{proposition} $$(\mathrm{Russian},\mathrm{Russian})\nVdash_1 \H_s(\mbox{``Sanaz is in the Russian restaurant''}).$$ \end{proposition} \begin{proof} Note that $(\mathrm{Iranian},\mathrm{Iranian})$ is a good world, in which statement ``Sanaz is in the Russian restaurant'' is not satisfied. Therefore, the statement of the proposition is true by item 6(b) of Definition~\ref{sat with goodness}. \end{proof} However, for the satisfaction relation $\Vdash_2$ of the epistemic model with goodness where $G_s=\{(\mathrm{Russian},\mathrm{Russian})\}$ and $G_p=\{(\mathrm{Iranian},\mathrm{Iranian})\}$, the situation is different: \begin{proposition}\label{oct20-a} $$(\mathrm{Russian},\mathrm{Russian})\Vdash_2 \H_s(\mbox{``Sanaz and Pavel are in the same restaurant''}).$$ \end{proposition} \begin{proof} The proof is similar to the proof of Proposition~\ref{oct19-rr2} except that in {\em Condition b} we only need to consider the world $(\mathrm{Russian},\mathrm{Russian})$. \end{proof} \begin{proposition}\label{oct20-b} $$(\mathrm{Russian},\mathrm{Russian})\Vdash_2 \H_s(\mbox{``Sanaz is in the Russian restaurant''}).$$ \end{proposition} \begin{proof} It suffices to verify conditions (a), (b), and (c) of item 6 of Definition~\ref{sat with goodness}: \vspace{1mm} \noindent{\em Condition a:} Since the Battle of the Cuisines is a setting with perfect information, it suffices to show that $$(\mathrm{Russian},\mathrm{Russian})\Vdash_2 (\mbox{``Sanaz is in the Russian restaurant''}).$$ The last statement is true by the definition of the world $(\mathrm{Russian},\mathrm{Russian})$. \vspace{1mm} \noindent{\em Condition b:} Note that in the current setting set $G_s$ contains only element $(\mathrm{Russian},\mathrm{Russian})$ and that $$(\mathrm{Russian},\mathrm{Russian})\Vdash_2 (\mbox{``Sanaz is in the Russian restaurant''}).$$ \vspace{1mm} \noindent{\em Condition c:} $(\mathrm{Iranian},\mathrm{Russian})\nVdash_2 (\mbox{``Sanaz is in the Russian restaurant''})$. \end{proof} We conclude this section by an observation that the Coherence of Potential Emotions axiom is not universally true under goodness-based semantics. Indeed, note that according to Proposition~\ref{oct20-a} and Proposition~\ref{oct20-b}, there is an epistemic worlds in which Sanaz is happy that ``Sanaz is in the Russian restaurant'' and there is an epistemic world in which she is happy that ``Sanaz and Pavel are in the same restaurant''. If the Coherence of Potential Emotions axiom holds in this setting, then one of these statements would imply the other, but neither of them does. \section{Canonical Model} In the rest of this article we prove strong completeness of our logical system with respect to the semantics given in Definition~\ref{sat}. As usual, the proof of the completeness is based on a construction of a canonical model. In this section, for any maximal consistent set of formulae $X\subseteq\Phi$, we define canonical epistemic model with preferences $M(X_0)=(W,\{\sim_a\}_{a\in\mathcal{A}},\{\prec_a\}_{a\in\mathcal{A}},\pi)$. As it is common in modal logic, we define worlds as maximal consistent sets of formulae. Since the meaning of modality ${\sf N}$ in our system is ``for all worlds'', we require all worlds in the canonical model to have the same ${\sf N}$-formulae. We achieve this through the following definition. \begin{definition}\label{canonical world definition} $W$ is the set of all such maximal consistent sets of formulae $Y$ that $\{\phi\in\Phi\;|\;{\sf N}\phi\in X_0\}\subseteq Y$. \end{definition} Note that although the above definition only requires all ${\sf N}$-formulae from set $X_0$ to be in set $Y$, it is possible to show that the converse is also true due to the presence of the Negative Introspection axiom for modality ${\sf N}$ in our system. \begin{lemma}\label{X0 in W lemma} $X_0\in W$. \end{lemma} \begin{proof} Consider any formula ${\sf N}\phi\in X_0$. By Definition~\ref{canonical world definition}, it suffices to show that $\phi\in X_0$. Indeed, the assumption ${\sf N}\phi\in X_0$ implies that $X_0\vdash\phi$ by the Truth axiom and the Modus Ponens inference rule. Therefore, $\phi\in X_0$ because set $X_0$ is maximal. \end{proof} \begin{definition}\label{canonical sim} For any worlds $w,u\in W$, let $w\sim_a u$ if $\phi\in u$ for each formula ${\sf K}_a\phi\in w$. \end{definition} Alternatively, one can define $w\sim_a u$ if sets $w$ and $u$ have the same ${\sf K}_a$-formulae. Our approach results in shorter proofs, but it requires to prove the following lemma. \begin{lemma}\label{canonical sim is equivalence relation lemma} Relation $\sim_a$ is an equivalence relation on set $W$. \end{lemma} \begin{proof} {\bf Reflexivity:} Consider any formula $\phi\in\Phi$. Suppose that ${\sf K}_a\phi\in w$. By Definition~\ref{canonical sim}, it suffices to show that $\phi\in w$. Indeed, assumption ${\sf K}_a\phi\in w$ implies $w\vdash\phi$ by the Truth axiom and the Modus Ponens inference rule. Therefore, $\phi\in w$ because set $w$ is maximal. \vspace{1mm} \noindent {\bf Symmetry:} Consider any epistemic worlds $w, u \in W$ such that $w \sim_a u$ and any formula ${\sf K}_a\phi \in u$. By Definition~\ref{canonical sim}, it suffices to show $\phi \in w$. Suppose the opposite. Then, $\phi \notin w$. Hence, $w \nvdash \phi$ because set $w$ is maximal. Thus, $w \nvdash {\sf K}_a \phi$ by the contraposition of the Truth axiom. Then, $\neg {\sf K}_a \phi \in w$ because set $w$ is maximal. Thus, $w \vdash {\sf K}_a \neg {\sf K}_a \phi$ by the Negative Introspection axiom and the Modus Ponens inference rule. Hence, ${\sf K}_a \neg {\sf K}_a \phi\in w$ because set $w$ is maximal. Then, $\neg {\sf K}_a \phi\in u$ by assumption $w\sim_a u$ and Definition~\ref{canonical sim}. Therefore, ${\sf K}_a\phi \notin u$ because set $w$ is consistent, which contradicts the assumption ${\sf K}_a\phi \in u$. \vspace{1mm} \noindent {\bf Transitivity:} Consider any epistemic worlds $w, u, v \in W$ such that $w \sim_a u$ and $u \sim_a v$ and any formula ${\sf K}_a\phi\in w$. By Definition~\ref{canonical sim}, it suffices to show $\phi\in v$. Assumption ${\sf K}_a\phi\in w$ implies $w \vdash {\sf K}_a {\sf K}_a \phi$ by Lemma~\ref{positive introspection lemma} and the Modus Ponens inference rule. Thus, ${\sf K}_a {\sf K}_a \phi \in w$ because set $w$ is maximal. Hence, ${\sf K}_a \phi \in u$ by the assumption $w \sim_a u$ and Definition~\ref{canonical sim}. Therefore, $\phi \in v$ by the assumption $u \sim_a v$ and Definition~\ref{canonical sim}. \end{proof} The next step in specifying the canonical model is to define preference relation $\prec_a$ for each agent $a\in\mathcal{A}$, which we do in Definition~\ref{canonical prec}. Towards this definition, we first introduce the ``emotional base'' $\Delta_a$ for each agent $a$. The set $\Delta_a$ contains a formula $\delta$ if agent $a$ could either be potentially happy about $\delta$ or potentially sad about $\neg\phi$. \begin{definition}\label{Delta a} $ \Delta_a = \{\delta\in\Phi\;|\; {\sf \overline{N}}\H_a\delta\in X_0\}\cup \{\delta\in\Phi\;|\; {\sf \overline{N}}\S_a\neg\delta\in X_0\} $. \end{definition} The next lemma holds because set $\Phi$ is countable. \begin{lemma}\label{Delta_a is countable} Set $\Delta_a$ is countable for each agent $a\in\mathcal{A}$. \qed \end{lemma} Next, we introduce a total pre-order $\sqsubseteq_a$ on emotional base $\Delta_a$ of each agent $a\in \mathcal{A}$. Note that this pre-order is different from canonical preference relation $\prec_a$ that we introduce in Definition~\ref{canonical prec}. \begin{definition}\label{sqsubseteq definition} For any agent $a\in\mathcal{A}$ and any two formulae $\delta,\delta'\in\Delta_a$, let $\delta\sqsubseteq \delta'$ if ${\sf N}(\delta\to\delta')\in X_0$. \end{definition} \begin{lemma}\label{sqsubseteq contraposition lemma} ${\sf N}(\neg\delta'\to\neg\delta)\in X_0$ for any agent $a\in\mathcal{A}$ and any two formulae $\delta,\delta'\in\Delta_a$ such that $\delta\sqsubseteq\delta'$. \end{lemma} \begin{proof} Formula $(\delta\to\delta')\to(\neg\delta'\to\neg\delta)$ is a propositional tautology. Thus, $\vdash {\sf N}((\delta\to\delta')\to(\neg\delta'\to\neg\delta))$ by the Necessitation inference rule. Hence, \begin{equation}\label{contraposition under N} \vdash{\sf N}(\delta\to\delta')\to{\sf N}(\neg\delta'\to\neg\delta) \end{equation} by the Distributivity axiom and the Modus Ponens inference rule. Suppose that $\delta\sqsubseteq\delta'$. Thus, ${\sf N}(\delta\to\delta')\in X_0$ by Definition~\ref{sqsubseteq definition}. Hence, $X_0\vdash {\sf N}(\neg\delta'\to\neg\delta)$ by statement~(\ref{contraposition under N}) and the Modus Ponens inference rule. Therefore, ${\sf N}(\neg\delta'\to\neg\delta)\in X_0$ because set $X_0$ is maximal. \end{proof} \begin{lemma}\label{sqsubseteq total pre-order lemma} For any agent $a\in\mathcal{A}$, relation $\sqsubseteq$ is a total pre-order on set $\Delta_a$. \end{lemma} \begin{proof} We need to show that relation $\sqsubseteq$ is reflexive, transitive, and total. \vspace{1mm} \noindent{\bf Reflexivity:} Consider an arbitrary formula $\delta\in\Phi$. By Definition~\ref{sqsubseteq definition}, it suffices to show that ${\sf N}(\delta\to\delta)\in X_0$. Indeed, formula $\delta\to\delta$ is a propositional tautology. Thus, $\vdash {\sf N}(\delta\to\delta)$ by the Necessitation inference rule. Therefore, ${\sf N}(\delta\to\delta)\in X_0$ because set $X_0$ is maximal. \vspace{1mm} \noindent{\bf Transitivity:} Consider arbitrary $\delta_1,\delta_2,\delta_3\in\Phi$ such that ${\sf N}(\delta_1\to\delta_2)\in X_0$ and ${\sf N}(\delta_2\to\delta_3)\in X_0$. By Definition~\ref{sqsubseteq definition}, it suffices to show that ${\sf N}(\delta_1\to\delta_3)\in X_0$. Indeed, note that formula $ (\delta_1\to\delta_2)\to ((\delta_2\to\delta_3)\to(\delta_1\to\delta_3) ) $ is a propositional tautology. Thus, $ \vdash {\sf N}((\delta_1\to\delta_2)\to ((\delta_2\to\delta_3)\to(\delta_1\to\delta_3) )) $ by the Necessitation inference rule. Hence, by the Distributivity axiom and the Modus Ponens inference rule, $ \vdash {\sf N}(\delta_1\to\delta_2)\to {\sf N}((\delta_2\to\delta_3)\to(\delta_1\to\delta_3) ) $. Then, $ X_0 \vdash {\sf N}((\delta_2\to\delta_3)\to(\delta_1\to\delta_3) ) $ by the assumption ${\sf N}(\delta_1\to\delta_2)\in X_0$ and the Modus Ponens inference rule. Thus, $ X_0 \vdash {\sf N}(\delta_2\to\delta_3)\to{\sf N}(\delta_1\to\delta_3) $ by the Distributivity axiom and the Modus Ponens inference rule. Hence, by the assumption ${\sf N}(\delta_2\to\delta_3)\in X_0$ and the Modus Ponens rule, $ X_0 \vdash {\sf N}(\delta_1\to\delta_3) $. Therefore, ${\sf N}(\delta_1\to\delta_3)\in X_0$ because set $X_0$ is maximal. \vspace{1mm} \noindent{\bf Totality:} Consider arbitrary formulae $\delta_1,\delta_2\in \Delta_a$. By Definition~\ref{sqsubseteq definition}, it suffices to show that either ${\sf N}(\delta_1\to\delta_2)\in X_0$ or ${\sf N}(\delta_2\to\delta_1)\in X_0$. By Definition~\ref{Delta a}, without loss of generality, we can assume that on the the following three cases takes place: \vspace{1mm} \noindent{\em Case I:} ${\sf \overline{N}}\H_a\delta_1, {\sf \overline{N}}\H_a\delta_2\in X_0$. Then, $X_0\vdash {\sf N}(\delta_1\to\delta_2)\vee {\sf N}(\delta_2\to\delta_1)$ by the first Coherence of Potential Emotions axiom and propositional reasoning. Therefore, because set $X_0$ is maximal, either ${\sf N}(\delta_1\to\delta_2)\in X_0$ or ${\sf N}(\delta_2\to\delta_1)\in X_0$. \vspace{1mm} \noindent{\em Case II:} ${\sf \overline{N}}\S_a\neg\delta_1, {\sf \overline{N}}\S_a\neg\delta_2\in X_0$. Similarly to the previous case, we can show that either ${\sf N}(\neg\delta_1\to\neg\delta_2)\in X_0$ or ${\sf N}(\neg\delta_2\to\neg\delta_1)\in X_0$. Without loss of generality, suppose that ${\sf N}(\neg\delta_1\to\neg\delta_2)\in X_0$. Note that formula $ (\neg\delta_1\to\neg\delta_2)\to(\delta_2\to\delta_1) $ is a propositional tautology. Thus, $ \vdash{\sf N}((\neg\delta_1\to\neg\delta_2)\to(\delta_2\to\delta_1)) $ by the Necessitation inference rule. Hence, $ \vdash{\sf N}(\neg\delta_1\to\neg\delta_2)\to{\sf N}(\delta_2\to\delta_1) $ by the Distributivity axiom and the Modus Ponens rule. Thus, $ X_0\vdash{\sf N}(\delta_2\to\delta_1) $ by the assumption ${\sf N}(\neg\delta_1\to\neg\delta_2)\in X_0$. Therefore, ${\sf N}(\delta_2\to\delta_1)\in X_0$ because set $X_0$ is maximal. \vspace{1mm} \noindent{\em Case III:} ${\sf \overline{N}}\H_a\delta_1,{\sf \overline{N}}\S_a\neg\delta_2\in X_0$. Thus, by the second Coherence of Potential Emotions axiom and propositional reasoning, $ X_0\vdash {\sf N}(\delta_1\to\neg\neg\delta_2) \vee {\sf N}(\neg\neg\delta_2\to \delta_1) $. Hence, either ${\sf N}(\delta_1\to\neg\neg\delta_2)\in X_0$ or ${\sf N}(\neg\neg\delta_2\to \delta_1)\in X_0$ because set $X_0$ is consistent. Then using an argument similar to the one in Case II and propositional tautologies $$ (\delta_1\to\neg\neg\delta_2) \to (\delta_1\to\delta_2) \mbox{ and } (\neg\neg\delta_2\to \delta_1) \to (\delta_2\to \delta_1) $$ one can conclude that either ${\sf N}(\delta_1\to\delta_2)\in X_0$ or ${\sf N}(\delta_2\to \delta_1)\in X_0$. \end{proof} We now are ready to define preference relation $\prec_a$ on epistemic worlds of the canonical model. \begin{definition}\label{canonical prec} $w\prec_a u$ if there is a formula $\delta\in \Delta_a$ such that $\delta\notin w$ and $\delta\in u$. \end{definition} Note that the transitivity of the relation $\prec_a$ is not obvious. We prove it as a part of the next lemma. \begin{lemma} $\prec_a$ is a strict partial order on $W$. \end{lemma} \begin{proof} {\bf Irreflexivity}. Suppose that $w\prec_a w$ for some world $w\in W$. Thus, by Definition~\ref{canonical prec}, there exists formula $\delta\in\Delta_a$ such that $\delta\notin w$ and $\delta\in w$, which is a contradiction. \noindent{\bf Transitivity}. Consider any worlds $w,u,v\in W$ such that $w\prec_a u$ and $u\prec_a v$. It suffices to prove that $w\prec_a v$. Indeed, by Definition~\ref{canonical prec}, assumptions $w\prec_a u$ and $u\prec_a v$ imply that there are formulae $\delta_1,\delta_2$ in $\Delta_a$ such that \begin{equation}\label{another four facts} \delta_1\notin w, \;\;\; \delta_1\in u, \;\;\; \delta_2\notin u, \;\;\; \mbox{and }\;\;\; \delta_2\in v. \end{equation} By Lemma~\ref{sqsubseteq total pre-order lemma}, either $\delta_1\sqsubseteq \delta_2$ or $\delta_2\sqsubseteq \delta_1$. We consider these two cases separately. \vspace{1mm} \noindent{\em Case I:} $\delta_1\sqsubseteq \delta_2$. Then, ${\sf N}(\delta_1\to\delta_2)\in X_0$ by Definition~\ref{canonical prec}. Hence, $\delta_1\to\delta_2\in u$ by Definition~\ref{canonical world definition}. Thus, $u\vdash \delta_2$ by the part $\delta_1\in u$ of statement~(\ref{another four facts}) and the Modus Ponens inference rule. Therefore, $\delta_2\in u$ because set $u$ is maximal, which contradicts the part $\delta_2\notin u$ of statement~(\ref{another four facts}). \vspace{1mm} \noindent{\em Case II:} $\delta_2\sqsubseteq \delta_1$. Then, ${\sf N}(\delta_2\to\delta_1)\in X_0$ by Definition~\ref{canonical prec}. Thus, $\delta_2\to\delta_1\in v$ by Definition~\ref{canonical world definition}. Hence, $v\vdash \delta_1$ by the part $\delta_2\in v$ of statement~(\ref{another four facts}) and the Modus Ponens inference rule. Then, $\delta_1\in v$ because set $v$ is maximal. Therefore, $w\prec_a v$ by Definition~\ref{canonical prec} and the part $\delta_1\notin w$ of statement~(\ref{another four facts}). \end{proof} \begin{definition}\label{canonical pi} $\pi(p)=\{w\in W\;|\;p\in w\}$. \end{definition} This concludes the definition of the canonical epistemic model with preferences $M(X_0)=(W,\{\sim_a\}_{a\in\mathcal{A}},\{\prec_a\}_{a\in\mathcal{A}},\pi)$. \section{Properties of a Canonical Model} As usual the proof of the completeness is centered around an ``induction'' or ``truth'' lemma. In our case, this is Lemma~\ref{induction lemma}. We precede this lemma with several auxiliary lemmas that are used in the induction step of the proof of Lemma~\ref{induction lemma}. For the benefit of the reader, we grouped these auxiliary lemmas into several subsections. Throughout this section up to and including Lemma~\ref{induction lemma}, we assume a fixed canonical model $M(X_0)$. \subsection{Properties of Modality ${\sf N}$} \begin{lemma}\label{N child all} For any worlds $w,u\in W$ and any formula $\phi\in\Phi$, if ${\sf N}\phi\in w$, then $\phi\in u$. \end{lemma} \begin{proof} Suppose that $\phi \notin u$. Thus, $u\nvdash \phi$ because set $u$ is maximal. Hence, ${\sf N}\phi\notin u$ by the Truth axiom. Then, ${\sf N}\N\phi\notin X_0$ by Definition~\ref{canonical world definition}. Thus, $X_0\nvdash{\sf N}\N\phi$ because set $X_0$ is maximal. Hence, ${\sf N}\phi\notin X_0$ by Lemma~\ref{positive introspection lemma}. Then, $\neg{\sf N}\phi\in X_0$ because set $X_0$ is maximal. Thus, $X_0\vdash {\sf N}\neg{\sf N}\phi$ by the Negative Introspection axiom and the Modus Ponens inference rule. Hence, ${\sf N}\neg{\sf N}\phi\in X_0$ because set $X_0$ is maximal. Then, $\neg{\sf N}\phi\in w$ by Definition~\ref{canonical world definition}. Therefore, ${\sf N}\phi\notin w$ because set $w$ is consistent. \end{proof} \begin{lemma}\label{N child exists} For any world $w\in W$ and any formula $\phi\in\Phi$, if ${\sf N}\phi\notin w$, then there is a world $u\in W$ such that $\phi\notin u$. \end{lemma} \begin{proof} Consider the set $ X=\{\neg\phi\}\cup\{\psi\;|\;{\sf N}\psi\in X_0\} $. We start by showing that set $X$ is consistent. Suppose the opposite. Then, there are formulae $ {\sf N}\psi_1,\dots, {\sf N}\psi_n \in X_0 $ such that $ \psi_1,\dots,\psi_n\vdash \phi $. Thus, $ {\sf N}\psi_1,\dots,{\sf N}\psi_n\vdash {\sf N}\phi $ by Lemma~\ref{superdistributivity lemma}. Hence, $ X_0\vdash {\sf N}\phi $ because $ {\sf N}\psi_1,\dots, {\sf N}\psi_n \in X_0 $. Then, $ X_0\vdash {\sf N}\N\phi $ by Lemma~\ref{positive introspection lemma} and the Modus Ponens inference rule. Thus, $ {\sf N}\N\phi \in X_0 $ because set $X_0$ is maximal. Hence, $ {\sf N}\phi\in w $ by Definition~\ref{canonical world definition} which contradicts the assumption ${\sf N}\phi\notin w$ of the lemma. Therefore, set $X$ is consistent. Let set $u$ be a maximum consistent extension of set $X$. Such set exists by Lemma~\ref{Lindenbaum's lemma}. Note that $u \in W $ by Definition~\ref{canonical world definition} and the choice of sets $X$ and $u$. Also, $\neg\phi\in X\subseteq u$ by the choice of sets $X$ and $u$. Therefore, $\phi\notin u$ because set $u$ is consistent. \end{proof} \subsection{Properties of Modality ${\sf K}$} \begin{lemma}\label{K child all} For any agent $a\in \mathcal{A}$, any worlds $w,u\in W$, and any formula $\phi\in\Phi$, if ${\sf K}_a\phi\in w$ and $w\sim_a u$, then $\phi\in u$. \end{lemma} \begin{proof} Assumptions ${\sf K}_a\phi\in w$ and $w\sim_a u$ imply $\phi\in u$ by Definition~\ref{canonical sim}. \end{proof} \begin{lemma}\label{K child exists} For any agent $a\in \mathcal{A}$, any world $w\in W$, and any formula $\phi\in\Phi$, if ${\sf K}_a\phi\notin w$, then there is a world $u\in W$ such that $w\sim_a u$ and $\phi\notin u$. \end{lemma} \begin{proof} First, we show that the following set of formulae is consistent \begin{equation}\label{july16-X} X=\{\neg\phi\}\cup\{\psi\;|\;{\sf K}_a\psi\in w\}\cup\{\chi\;|\;{\sf N}\chi\in X_0\}. \end{equation} Assume the opposite. Then, there are formulae \begin{equation}\label{july16-psi} {\sf K}_a\psi_1,\dots,{\sf K}_a\psi_m\in w \end{equation} and formulae \begin{equation}\label{july16-chi} {\sf N}\chi_1,\dots,{\sf N}\chi_n\in X_0 \end{equation} such that $$ \psi_1,\dots,\psi_m,\chi_1,\dots,\chi_n\vdash \phi. $$ Thus, by Lemma~\ref{superdistributivity lemma}, $$ {\sf K}_a\psi_1,\dots,{\sf K}_a\psi_m,{\sf K}_a\chi_1,\dots,{\sf K}_a\chi_n\vdash {\sf K}_a\phi. $$ Hence, by assumption~(\ref{july16-psi}), \begin{equation}\label{june29} w,{\sf K}_a\chi_1,\dots,{\sf K}_a\chi_n\vdash {\sf K}_a\phi. \end{equation} Consider any integer $i\le n$. Note that ${\sf N}\chi_i\to{\sf K}_a\chi_i$ is an instance of the Knowledge of Necessity axiom. Then, $\vdash {\sf N}({\sf N}\chi_i\to{\sf K}_a\chi_i)$ by the Necessitation inference rule. Thus, $\vdash {\sf N}\N\chi_i\to{\sf N}{\sf K}_a\chi_i$ by the Distributivity axiom and the Modus Ponens inference rule. Note that $\vdash {\sf N}\phi\to{\sf N}\N\phi$ by Lemma~\ref{positive introspection lemma}. Hence, $\vdash {\sf N}\chi_i\to{\sf N}{\sf K}_a\chi_i$ by the laws of propositional reasoning. Then, $X_0\vdash {\sf N}{\sf K}_a\chi$ by assumption~(\ref{july16-chi}). Thus, ${\sf N}{\sf K}_a\chi\in X_0$ because set $X_0$ is maximal. Hence, ${\sf K}_a\chi_i\in w$ by Definition~\ref{canonical world definition} for any integer $i\le n$. Then, statement~(\ref{june29}) implies that $w\vdash {\sf K}_a\phi$. Thus, ${\sf K}_a\phi\in w$ because set $w$ is maximal, which contradicts assumption ${\sf K}_a\phi\notin w$ of the lemma. Therefore, set $X$ is consistent. By Lemma~\ref{Lindenbaum's lemma}, set $X$ can be extended to a maximal consistent set $u$. Then, $\{\chi\;|\;{\sf N}\chi\in X_0\}\subseteq X\subseteq u$ by equation~(\ref{july16-X}). Thus, $u\in W$ by Definition~\ref{canonical world definition}. Also, $\{\psi\;|\;{\sf K}_a\psi\in w\}\subseteq X\subseteq u$ by equation~(\ref{july16-X}). Hence, $w\sim_a u$ by Definition~\ref{canonical sim}. Finally, $\neg\phi\in X\subseteq u$ also by equation~(\ref{july16-X}). Therefore, $\phi\notin u$ because set $u$ is consistent. \end{proof} \subsection{Common Properties of Modalities $\H$ and $\S$} Recall that by ${\sf E}$ we denote one of the two emotional modalities: $\H$ and $\S$. \begin{lemma} For any agent $a\in \mathcal{A}$, any worlds $w,u\in W$, and any formula $\phi\in\Phi$, if ${\sf E}_a\phi\in w$ and $w\sim_a u$, then $\phi\in u$. \end{lemma} \begin{proof} By Lemma~\ref{E to K} and the Modus Ponens inference rule, the assumption ${\sf E}_a\phi\in w$ implies $w\vdash{\sf K}_a\phi$. Thus, ${\sf K}_a\phi\in w$ because set $w$ is maximal. Therefore, $\phi\in u$ by Lemma~\ref{K child all} and the assumption $w\sim_a u$. \end{proof} \begin{lemma} For any world $w\in W$, and any formula ${\sf E}_a\phi\in w$, there is a world $u\in W$ such that $\phi\notin u$. \end{lemma} \begin{proof} By the Counterfactual axiom and the Modus Ponens inference rule, assumption ${\sf E}_a\phi\in w$ implies $w\vdash \neg{\sf N}\phi$. Thus, ${\sf N}\phi\notin w$ because set $w$ is consistent. Therefore, by Lemma~\ref{N child exists}, there is a world $u\in W$ such that $\phi\notin u$. \end{proof} \subsection{Properties of Modality $\H$} \begin{lemma}\label{H child all} For any agent $a\in \mathcal{A}$, any worlds $w,u,u'\in W$, and any formula $\phi\in\Phi$, if $\H_a\phi\in w$, $\phi\notin u$ and $\phi\in u'$, then $u\prec_a u'$. \end{lemma} \begin{proof} The assumption $\H_a\phi\in w$ implies $\neg\H_a\phi\notin w$ because set $w$ is consistent. Thus, ${\sf N}\neg\H_a\phi\notin X_0$ by Definition~\ref{canonical world definition} because $w\in W$. Hence, $\neg{\sf N}\neg\H_a\phi\in X_0$ because set $X_0$ is maximal. Then, ${\sf \overline{N}}\H_a\phi\in X_0$ by the definition of modality ${\sf \overline{N}}$. Thus, $\phi\in \Delta_a$ by Definition~\ref{Delta a}. Therefore, $u\prec_a u'$ by Definition~\ref{canonical prec} and the assumptions $\phi\notin u$ and $\phi\in u'$ of the lemma. \end{proof} \begin{lemma}\label{H children exist} For any agent $a\in \mathcal{A}$, any world $w\in W$, and any formula $\phi\in\Phi$, if $\H_a\phi\notin w$, ${\sf K}_a\phi\in w$, and ${\sf N}\phi\notin w$, then there are worlds $u,u'\in W$ such that $\phi\notin u$, $\phi\in u'$, and $u\not\prec_a u'$. \end{lemma} \begin{proof} By Lemma~\ref{sqsubseteq total pre-order lemma}, relation $\sqsubseteq$ forms a total pre-order on set $\Delta_a$. By Lemma~\ref{Delta_a is countable}, set $\Delta_a$ is countable. Thus, by the axiom of countable choice, there is an ordering of all formulae in set $\Delta_a$ that agrees with pre-order $\sqsubseteq$. Generally speaking, such ordering is not unique. We fix any such ordering: \begin{equation}\label{delta chain} \delta_0\sqsubseteq\delta_1\sqsubseteq\delta_2\sqsubseteq\delta_3\sqsubseteq\dots \end{equation} If set $\Delta_a$ is finite, the above ordering has some finite number $n$ of elements. In this case, the ordering is isomorphic to ordinal $n$. Otherwise, it is isomorphic to ordinal $\omega$. Let $\alpha$ be the ordinal which is the type of ordering~(\ref{delta chain}). Ordinal $\alpha$ is either finite or is equal to $\omega$. For any ordinal $k\le \alpha$, we consider set \begin{equation}\label{Yk definition} Y_k=\{\phi\}\cup\{\neg\delta_i\;|\; i<k\}\cup \{\psi\;|\;{\sf N}\psi\in X_0\}. \end{equation} \begin{claim}\label{trans induction lemma} If there is no finite ordinal $k<\alpha$ such that $Y_k$ is consistent and $Y_{k+1}$ is inconsistent, then $Y_\alpha$ is consistent. \end{claim} \begin{proof-of-claim} To prove that $Y_\alpha$ is consistent, it suffices to show that $Y_k$ is consistent for each ordinal $k\le \alpha$. We prove this by transfinite induction. \vspace{2mm} \noindent{\bf Zero Case:} Suppose that $Y_0$ is not consistent. Thus, there are formulae ${\sf N}\psi_1,\dots,{\sf N}\psi_n\in X_0$ such that $ \psi_1,\dots,\psi_n\vdash \neg\phi $. Hence, $ {\sf N}\psi_1,\dots,{\sf N}\psi_n\vdash {\sf N}\neg\phi $ by Lemma~\ref{superdistributivity lemma}. Then, $ X_0\vdash {\sf N}\neg\phi $ by the assumption ${\sf N}\psi_1,\dots,{\sf N}\psi_n\in X_0$. Thus, because set $X_0$ is maximal, \begin{equation}\label{zero case point} {\sf N}\neg\phi\in X_0. \end{equation} Hence, $\neg\phi\in w$, by Definition~\ref{canonical world definition}. Then, $w\vdash \neg{\sf K}_a\phi$ by the contraposition of the Truth axiom and propositional reasoning. Therefore, ${\sf K}_a\phi\notin w$ because set $w$ is consistent, which contradicts the assumption ${\sf K}_a\phi\in w$ of lemma. \vspace{2mm} \noindent{\bf Successor Case:} Suppose that set $Y_k$ is consistent for some $k<\alpha$. By the assumption of the claim, there is no finite ordinal $k<\alpha$ such that $Y_k$ is consistent and $Y_{k+1}$ is inconsistent. Therefore, set $Y_{k+1}$ is consistent. \vspace{2mm} \noindent{\bf Limit Case:} Suppose that set $Y_\omega$ is not consistent. Thus, there are formulae ${\sf N}\psi_1,\dots,{\sf N}\psi_n\in X_0$ and some finite $k<\omega$ such that $ \psi_1,\dots,\psi_n,\neg\delta_0,\dots,\neg\delta_{k-1}\vdash \neg\phi $. Therefore, set $Y_k$ is not consistent. \end{proof-of-claim} Let $k'$ be any finite ordinal $k'<\alpha$ such that $Y_{k'}$ is consistent and $Y_{k'+1}$ is inconsistent. If such finite ordinal does not exist, then let $k'$ be ordinal $\alpha$. Note that in either case, set $Y_{k'}$ is consistent by Claim~\ref{trans induction lemma}. Let $u'$ be any maximal consistent extension of set $Y_{k'}$. Such extension exists by Lemma~\ref{Lindenbaum's lemma}. Note that $\phi\in Y_{k'}\subseteq u'$ by equation~(\ref{Yk definition}) and the choice of set $u'$. \begin{claim}\label{u' in W claim} $u'\in W$. \end{claim} \begin{proof-of-claim} Consider any formula ${\sf N}\psi\in X_0$. By Definition~\ref{canonical world definition}, it suffices to show that $\psi\in u'$. Indeed, $\psi\in Y_{k'}$ by equation~(\ref{Yk definition}) and the assumption ${\sf N}\psi\in X_0$. Thus, $\psi\in u'$ because $Y_{k'}\subseteq u'$ by the choice of set $u'$. \end{proof-of-claim} Consider the following set of formulae: \begin{equation}\label{choice of Z equation} Z=\{\neg\phi\}\cup\{\delta_i\;|\;k'\le i<\alpha\}\cup \{\psi\;|\;{\sf N}\psi\in X_0\}. \end{equation} \begin{claim}\label{Z claim} Set $Z$ is consistent. \end{claim} \begin{proof-of-claim} We consider the following two cases separately: \noindent{\em Case 1:} $k'<\alpha$. Suppose that set $Z$ is not consistent. Thus, there are finite ordinals $m<\alpha$ and $n<\omega$ and formulae \begin{equation}\label{choice of psi} {\sf N}\psi_1,\dots{\sf N}\psi_n\in X_0 \end{equation} such that $k'\le m$ and $$ \delta_{k'},\delta_{k'+1},\dots,\delta_{m},\psi_1,\dots,\psi_n\vdash \phi. $$ Hence, by the Modus Ponens inference rule applied $m-k'$ times, $$ \delta_{k'},\delta_{k'}\to\delta_{k'+1}, \delta_{k'+1}\to\delta_{k'+2}, \delta_{k'+2}\to\delta_{k'+3}, \dots, \delta_{m-1}\to\delta_{m},\psi_1,\dots,\psi_n\vdash \phi. $$ Then, by Lemma~\ref{deduction lemma}, $$ \delta_{k'}\to\delta_{k'+1}, \delta_{k'+1}\to\delta_{k'+2}, \dots, \delta_{m-1}\to\delta_{m},\psi_1,\dots,\psi_n\vdash \delta_{k'}\to\phi. $$ Thus, by Lemma~\ref{superdistributivity lemma}, $$ {\sf N}(\delta_{k'}\to\delta_{k'+1}), {\sf N}(\delta_{k'+1}\to\delta_{k'+2}), \dots, {\sf N}(\delta_{m-1}\to\delta_{m}),{\sf N}\psi_1,\dots,{\sf N}\psi_n\vdash {\sf N}(\delta_{k'}\to\phi). $$ Recall that $\delta_{k'}\sqsubseteq\delta_{k'+1}\sqsubseteq\dots \sqsubseteq\delta_{m}$ by assumption~(\ref{delta chain}). Hence, it follows that ${\sf N}(\delta_{k'}\to\delta_{k'+1}), {\sf N}(\delta_{k'+1}\to\delta_{k'+2}), \dots, {\sf N}(\delta_{m-1}\to\delta_{m})\in X_0$ by Definition~\ref{sqsubseteq definition}. Then, $$ X_0,{\sf N}\psi_1,\dots,{\sf N}\psi_n\vdash {\sf N}(\delta_{k'}\to\phi). $$ Thus, by assumption~(\ref{choice of psi}), \begin{equation}\label{N delta to phi} X_0\vdash {\sf N}(\delta_{k'}\to\phi). \end{equation} At the same time, $k'<\alpha$ by the assumption of the case. Hence, set $Y_{k'+1}$ is not consistent by the choice of the finite ordinal $k'$. Then, by equation~(\ref{Yk definition}), there must exist formulae \begin{equation}\label{choice of psi prime} {\sf N}\psi'_1,\dots,{\sf N}\psi'_p\in X_0 \end{equation} such that $$ \neg\delta_{0},\neg\delta_{1},\neg\delta_{2},\dots,\neg\delta_{k'},\psi'_1,\dots,\psi'_p\vdash \neg\phi. $$ In other words, $$ \neg\delta_{k'},\neg\delta_{k'-1},\neg\delta_{k'-2},\dots,\neg\delta_{0},\psi'_1,\dots,\psi'_p\vdash \neg\phi. $$ Thus, by applying the Modus Ponens inference rule $k'$ times, $$ \neg\delta_{k'}, \neg\delta_{k'}\to\neg\delta_{k'-1},\neg\delta_{k'-1}\to \neg\delta_{k'-2},\dots,\neg\delta_{1}\to\neg\delta_{0},\psi'_1,\dots,\psi'_p\vdash \neg\phi. $$ Hence, by Lemma~\ref{deduction lemma}, $$ \neg\delta_{k'}\to\neg\delta_{k'-1},\neg\delta_{k'-1}\to \neg\delta_{k'-2},\dots,\neg\delta_{1}\to\neg\delta_{0},\psi'_1,\dots,\psi'_n\vdash \neg\delta_{k'}\to \neg\phi. $$ Then, by Lemma~\ref{superdistributivity lemma}, \begin{eqnarray*} &&{\sf N}(\neg\delta_{k'}\to\neg\delta_{k'-1}),{\sf N}(\neg\delta_{k'-1}\to \neg\delta_{k'-2}),\dots,{\sf N}(\neg\delta_{1}\to\neg\delta_{0}),\\ &&\hspace{65mm}{\sf N}\psi'_1,\dots,{\sf N}\psi'_n\vdash {\sf N}(\neg\delta_{k'}\to \neg\phi). \end{eqnarray*} Recall that $\delta_{0}\sqsubseteq\delta_{1}\sqsubseteq\dots \sqsubseteq\delta_{k'}$ by assumption~(\ref{delta chain}). Thus, it follows that ${\sf N}(\neg\delta_{1}\to\neg\delta_{0}), {\sf N}(\neg\delta_{2}\to\neg\delta_{1}), \dots, {\sf N}(\neg\delta_{k'}\to\neg\delta_{k'-1})\in X_0$ by Lemma~\ref{sqsubseteq contraposition lemma}. Hence, $$ X_0,{\sf N}\psi'_1,\dots,{\sf N}\psi'_n\vdash {\sf N}(\neg\delta_{k'}\to\neg\phi). $$ Then, by assumption~(\ref{choice of psi prime}), \begin{equation}\label{N neg delta to neg phi} X_0\vdash {\sf N}(\neg\delta_{k'}\to\neg\phi). \end{equation} Thus, by item 1 of Lemma~\ref{N biconditional lemma} and statement~(\ref{N delta to phi}), \begin{equation}\label{N biconditional statement} X_0\vdash {\sf N}(\delta_{k'}\leftrightarrow\phi). \end{equation} Note that $\delta_{k'}\in\Delta_a$ because (\ref{delta chain}) is an ordering of set $\Delta_a$. Hence, by Definition~\ref{Delta a}, either ${\sf \overline{N}}\H_a\delta_{k'}\in X_0$ or ${\sf \overline{N}}\S_a\neg\delta_{k'}\in X_0$. Then, by items 1 and 2 of Lemma~\ref{substitution lemma} and statement~(\ref{N biconditional statement}), either $X_0\vdash {\sf \overline{N}}\H_a\phi$ or $X_0\vdash {\sf \overline{N}}\S_a\neg\phi$. Thus, either $X_0\vdash {\sf N}{\sf \overline{N}}\H_a\phi$ or $X_0\vdash {\sf N}{\sf \overline{N}}\S_a\neg\phi$ by the definition of modality ${\sf \overline{N}}$, the Negative Introspection axiom, and the Modus Ponens inference rule. Hence, either ${\sf N}{\sf \overline{N}}\H_a\phi\in X_0$ or $ {\sf N}{\sf \overline{N}}\S_a\neg\phi\in X_0$ because set $X_0$ is maximal. Then, either ${\sf \overline{N}}\H_a\phi\in w$ or ${\sf \overline{N}}\S_a\neg\phi\in w$ by Definition~\ref{canonical world definition} and assumption $w\in W$ of the lemma. Thus, $w\vdash {\sf K}_a\phi\to\H_a\phi$ by the first Emotional Predictability axiom and propositional reasoning. Hence, $w\vdash \H_a\phi$ by assumption ${\sf K}_a\phi$ of the lemma and the Modus Ponens inference rule. Therefore, $\H_a\phi\in w$ because set $w$ is maximal, which contradicts assumption $\H_a\phi\notin w$ of the lemma. \noindent{\em Case 2:} $\alpha\le k'$. Recall that $k'\le\alpha$ by the choice of ordinal $k'$ made after the end of the proof of Claim~\ref{trans induction lemma}. Thus, $k'=\alpha$. Hence, $Z=\{\neg\phi\}\cup \{\psi\;|\;{\sf N}\psi\in X_0\}$ by equation~(\ref{choice of Z equation}). Then, inconsistency of set $Z$ implies that there are formulae \begin{equation}\label{choice of psi 1 psi n} {\sf N}\psi_1,\dots{\sf N}\psi_n\in X_0 \end{equation} such that $ \psi_1,\dots, \psi_n\vdash \phi $. Thus, $ {\sf N}\psi_1,\dots, {\sf N}\psi_n\vdash {\sf N}\phi $ by Lemma~\ref{superdistributivity lemma}. Hence, \begin{equation}\label{split point} X_0\vdash {\sf N}\phi \end{equation} by the assumption~(\ref{choice of psi 1 psi n}). Then, $ X_0\vdash {\sf N}\N\phi $ by Lemma~\ref{positive introspection lemma} and the Modus Ponens inference rule. Hence, ${\sf N}\N\phi\in X_0$ because set $X_0$ is maximal. Therefore, $ {\sf N}\phi\in w $ by Definition~\ref{canonical world definition}, which contradicts the assumption of the lemma. \end{proof-of-claim} Let $u$ be any maximal consistent extension of set $Z$. Note that $\neg\phi\in Z\subseteq u$ by equation~(\ref{choice of Z equation}) and the choice of set $u$. \begin{claim}\label{u W claim} $u\in W$. \end{claim} \begin{proof-of-claim} Consider any formula ${\sf N}\psi\in X_0$. By Definition~\ref{canonical world definition}, it suffices to show that $\psi\in u$. Indeed, $\psi\in Z$ by equation~(\ref{choice of Z equation}) and the assumption ${\sf N}\psi\in X_0$. Thus, $\psi\in u$ because $Z\subseteq u$ by the choice of set $u$. \end{proof-of-claim} \begin{claim}\label{u prec u' claim} $u\not\prec_a u'$. \end{claim} \begin{proof-of-claim} Suppose that $u\prec_a u'$. Thus, by Definition~\ref{canonical prec}, there is a formula $\delta\in\Delta_a$ such that $\delta\notin u$ and $\delta\in u'$. Recall that (\ref{delta chain}) is an ordering of the set $\Delta_a$. Hence, there must exist an integer $i<\alpha$ such that \begin{equation}\label{about u and u'} \delta_i\notin u \mbox{ and }\delta_i\in u'. \end{equation} We consider the following two cases separately: \noindent{\em Case 1:} $i< k'$. Then, $\neg\delta_i\in Y_{k'}\subseteq u'$ by equation~(\ref{Yk definition}) and the choice of set $u'$. Thus, $\delta_i\notin u'$ because set $u'$ is consistent, which contradicts to statement~(\ref{about u and u'}). \noindent{\em Case 2:} $k'\le i$. Then, $\delta_i\in Z\subseteq u$ by equation~(\ref{choice of Z equation}) and the choice of set $u$, which contradicts to statement~(\ref{about u and u'}). \end{proof-of-claim} This concludes the proof of the lemma. \end{proof} \subsection{Properties of Modality $\S$} \begin{lemma}\label{S child all} For any agent $a\in \mathcal{A}$, any worlds $w,u,u'\in W$, and any formula $\phi\in\Phi$, if $\S_a\phi\in w$, $\phi\in u$ and $\phi\notin u'$, then $u\prec_a u'$. \end{lemma} \begin{proof} Note that $\phi\leftrightarrow\neg\neg\phi$ is a propositional tautology. Thus, $\vdash{\sf N}(\phi\leftrightarrow\neg\neg\phi)$ by the Necessitation inference rule. Hence, $\vdash\S_a\phi\to\S_a\neg\neg\phi$ by the Substitution axiom and the Modus Ponens inference rule. Then, $w\vdash \S_a\neg\neg\phi$ by the Modus Ponens inference rule and the assumption $\S_a\phi\in w$ of the lemma. Thus, $\neg\S_a\neg\neg\phi\notin w$ because set $w$ is consistent. Hence, ${\sf N}\neg\S_a\neg\neg\phi\notin X_0$ by Definition~\ref{canonical world definition}. Then, $\neg{\sf N}\neg\S_a\neg\neg\phi\in X_0$ because set $X_0$ is maximal. Thus, ${\sf \overline{N}}\S_a\neg\neg\phi\in X_0$ by the definition of modality ${\sf \overline{N}}$. Hence, $\neg\phi\in \Delta_a$ by Definition~\ref{Delta a}. Therefore, $u\prec_a u'$ by Definition~\ref{canonical prec} and the assumptions $\neg\phi\notin u$ and $\neg\phi\in u'$ of the lemma. \end{proof} \begin{lemma}\label{S children exist} For any agent $a\in \mathcal{A}$, any world $w\in W$, and any formula $\phi\in\Phi$, if $\S_a\phi\notin w$, ${\sf K}_a\phi\in w$, and ${\sf N}\phi\notin w$, then there are worlds $u,u'\in W$ such that $\phi\in u$, $\phi\notin u'$, and $u\not\prec_a u'$. \end{lemma} \begin{proof} The proof of this lemma is similar to the proof of Lemma~\ref{H children exist}. Here we outline the differences. The choice of ordering~(\ref{delta chain}) and of ordinal $\alpha$ remains the same. Sets $Y_k$ for any ordinal $k\le \alpha$ is now defined as \begin{equation}\label{Yk definition S} Y_k=\{\neg\phi\}\cup\{\neg\delta_i\;|\; i<k\}\cup \{\psi\;|\;{\sf N}\psi\in X_0\}. \end{equation} This is different from equation~(\ref{Yk definition}) because set $Y_k$ now includes formula $\neg\phi$ instead of formula $\phi$. The statement of Claim~\ref{trans induction lemma} remains the same. The proof of this claim is also the same except for the Zero Case. In the Zero Case, the proof is similar to the original till equation~(\ref{zero case point}). Because set $Y_k$ now contains formula $\neg\phi$ instead of formula $\phi$, equation~(\ref{zero case point}) will now have the form ${\sf N}\phi\in X_0$. Thus, in our case, $X_0\vdash{\sf N}\N\phi$ by Lemma~\ref{positive introspection lemma} and the Modus Ponens inference rule. Hence, ${\sf N}\N\phi\in X_0$ because set $X_0$ is maximal. Then, ${\sf N}\phi\in w$ by Definition~\ref{canonical world definition}, which contradicts the assumption ${\sf N}\phi\notin w$ of the lemma. The statement and the proof of Claim~\ref{u' in W claim} remain the same. Set $Z$ will now be defined as \begin{equation}\label{new choice of Z equation} Z=\{\phi\}\cup\{\delta_i\;|\;k'\le i<\alpha\}\cup \{\psi\;|\;{\sf N}\psi\in X_0\}. \end{equation} This is different from equation~(\ref{choice of Z equation}) because set $Z$ now includes formula $\phi$ instead of formula $\neg\phi$. The statement of Claim~\ref{Z claim} remains the same. The Case 1 of the proof of this case is similar to the original proof of Claim~\ref{Z claim} till formula~(\ref{N neg delta to neg phi}), except for formula $\phi$ will be used instead of formula $\neg\phi$ and formula $\neg\phi$ instead of formula $\phi$ everywhere in that part of the proof. In particular formula~(\ref{N delta to phi}) will now have the form \begin{equation}\label{new N delta to phi} X_0\vdash {\sf N}(\delta_{k'}\to\neg\phi). \end{equation} and formula~(\ref{N neg delta to neg phi}) will now have the form \begin{equation}\label{new N neg delta to neg phi} X_0\vdash {\sf N}(\neg\delta_{k'}\to\phi). \end{equation} The argument after formula~(\ref{N neg delta to neg phi}) will change as follows. By item 2 of Lemma~\ref{N biconditional lemma} and statements ~(\ref{new N delta to phi}) and (\ref{new N neg delta to neg phi}), \begin{equation}\label{N biconditional statement} X_0\vdash {\sf N}(\delta_{k'}\leftrightarrow\neg\phi). \end{equation} Note that $\delta_{k'}\in\Delta_a$ because (\ref{delta chain}) is an ordering of set $\Delta_a$. Hence, by Definition~\ref{Delta a}, either ${\sf \overline{N}}\H_a\delta_{k'}\in X_0$ or ${\sf \overline{N}}\S_a\neg\delta_{k'}\in X_0$. Then, by items 1 or 3 of Lemma~\ref{substitution lemma} and statement~(\ref{N biconditional statement}), either $X_0\vdash {\sf \overline{N}}\H_a\neg\phi$ or $X_0\vdash {\sf \overline{N}}\S_a\phi$. Thus, either $X_0\vdash {\sf N}{\sf \overline{N}}\H_a\neg\phi$ or $X_0\vdash {\sf N}{\sf \overline{N}}\S_a\phi$ by the definition of modality ${\sf \overline{N}}$, the Negative Introspection axiom, and the Modus Ponens inference rule. Hence, either ${\sf N}{\sf \overline{N}}\H_a\neg\phi\in X_0$ or $ {\sf N}{\sf \overline{N}}\S_a\phi\in X_0$ because set $X_0$ is maximal. Then, either ${\sf \overline{N}}\H_a\neg\phi\in w$ or ${\sf \overline{N}}\S_a\phi\in w$ by Definition~\ref{canonical world definition} and assumption $w\in W$ of the lemma. Thus, $w\vdash {\sf K}_a\phi\to\S_a\phi$ by the second Emotional Predictability axiom and propositional reasoning. Hence, $w\vdash \S_a\phi$ by assumption ${\sf K}_a\phi$ of the lemma and the Modus Ponens inference rule. Therefore, $\S_a\phi\in w$ because set $w$ is maximal, which contradicts assumption $\S_a\phi\notin w$ of the lemma. The Case 2 of the proof of Claim~\ref{Z claim} will be similar to the original proof of Claim~\ref{Z claim} till formula~(\ref{split point}) except that formula except for formula $\phi$ will be used instead of formula $\neg\phi$ and formula $\neg\phi$ instead of formula $\phi$ everywhere in that part of the proof. Statement~(\ref{split point}) will now have the form $X_0\vdash {\sf N}\neg\phi$. From this point, the proof will continue as follows. Statement $X_0\vdash {\sf N}\neg\phi$ implies that ${\sf N}\neg\phi\in X_0$ because set $X_0$ is maximal. Then, $\neg\phi\in w$ by Definition~\ref{canonical world definition}. Hence, $w\vdash\neg{\sf K}_a\phi$ by the contraposition of the Truth axiom. Therefore, ${\sf K}_a\phi\notin w$ because set $w$ is consistent, which contradicts the assumption ${\sf K}_a\phi\in w$ of the lemma. The statements and the proofs of Claim~\ref{u W claim} and Claim~\ref{u prec u' claim} remain the same as in the original proof. \end{proof} \subsection{Final Steps} We are now ready to state and to prove the ``induction'' or ``truth'' lemma. \begin{lemma}\label{induction lemma} $w\Vdash \phi$ iff $\phi\in w$. \end{lemma} \begin{proof} We prove the lemma by structural induction on formula $\phi$. If $\phi$ is a propositional variable, then the required follows from Definition~\ref{canonical pi} and item 1 of Definition~\ref{sat}. If formula $\phi$ is a negation or an implication, then the statement of the lemma follows from the induction hypothesis using items 2 and 3 of Definition~\ref{sat} and the maximality and the consistency of the set $w$ in the standard way. Suppose that formula $\phi$ has the form ${\sf K}_a\psi$. \vspace{1mm} \noindent$(\Leftarrow):$ By Lemma~\ref{K child all}, assumption ${\sf K}_a\psi\in w$ implies that $\psi\in u$ for any world $u\in W$ such that $w\sim_a u$. Thus, by the induction hypothesis, $u\Vdash \psi$ for any world $u\in W$ such that $w\sim_a u$. Therefore, $w\Vdash{\sf K}_a\psi$ by item 5 of Definition~\ref{sat}. \vspace{1mm} \noindent$(\Rightarrow):$ Assume that ${\sf K}_a\psi\notin w$. Thus, by Lemma~\ref{K child exists}, there is a world $u\in W$ such that $w\sim_a u$ and $\psi\notin u$. Hence, $u\nVdash\psi$ by the induction hypothesis. Therefore, $w\nVdash{\sf K}_a\psi$ by item 5 of Definition~\ref{sat}. If formula $\phi$ has the form ${\sf N}\psi$, then the proof is similar to the case ${\sf K}_a\psi$ except that Lemma~\ref{N child all} and Lemma~\ref{N child exists} are used instead of Lemma~\ref{K child all} and Lemma~\ref{K child exists} respectively. Also, item 4 of Definition~\ref{sat} is used instead of item 5. Assume that formula $\phi$ has the form $\H_a\psi$. \vspace{1mm} \noindent$(\Leftarrow):$ Assume that $\H_a\psi\in w$. To prove that $w\Vdash\H_a\psi$, we verify conditions (a), (b), and (c) from item 6 of Definition~\ref{sat}. \begin{enumerate} \item[(a)] The assumption $\H_a\psi\in w$ implies $w\vdash{\sf K}_a\psi$ by Lemma~\ref{E to K} and the Modus Ponens inference rule. Thus, ${\sf K}_a\psi\in w$ because set $w$ is maximal. Hence, by Lemma~\ref{K child all}, for any world $u\in W$, if $\psi\in u$, then $w\sim_a u$ . Therefore, by the induction hypothesis, $u\Vdash \psi$ for any world $u\in W$ such that $w\sim_a u$. \item[(b)] By Lemma~\ref{H child all}, assumption $\H_a\psi\in w$ implies that for any worlds $u,u'\in W$, if $\psi\notin u$ and $\psi\in u'$, then $u\prec_a u'$. Thus, by the induction hypothesis, for any worlds $u,u'\in W$, if $u\nVdash\psi$ and $u'\Vdash\psi$, then $u\prec_a u'$. \item [(c)] By the Counterfactual axiom and the Modus Ponens inference rule, the assumption $\H_a\psi\in w$ implies that $w\vdash\neg{\sf N}\psi$. Thus, ${\sf N}\psi\notin w$ because set $w$ is consistent. Hence, by Lemma~\ref{N child exists}, there is a world $u\in W$ such that $\psi\notin u$. Therefore, $u\nVdash\psi$ by the induction hypothesis. \end{enumerate} \vspace{1mm} \noindent $(\Rightarrow):$ Assume that $\H_a\psi\notin w$. We consider the following three cases separately: \vspace{1mm} \noindent{\bf Case I:} ${\sf K}_a\psi\notin w$. Thus, by Lemma~\ref{K child exists}, there is a world $u\in W$ such that $w\sim_a u$ and $\psi\notin u$. Hence, $u\nVdash\psi$ by the induction hypothesis. Therefore, $w\nVdash\H_a\psi$ by item 6(a) of Definition~\ref{sat}. \vspace{1mm} \noindent{\bf Case II:} ${\sf N}\psi\in w$. Then, $\psi\in u$ for any world $u\in W$ by Lemma~\ref{N child all}. Thus, by the induction hypothesis, $u\Vdash \psi$ for any world $u\in W$. Therefore, $w\nVdash\H_a\psi$ by item 6(c) of Definition~\ref{sat}. \vspace{1mm} \noindent{\bf Case III:} ${\sf K}_a\psi\in w$ and ${\sf N}\psi\notin w$. Thus, by the assumption $\H_a\psi\notin w$ and Lemma~\ref{H children exist}, there are worlds $u,u'\in W$ such that $\psi\notin u$, $\psi\in u'$, and $u\not\prec_a u'$. Hence, $u\nVdash\psi$ and $u'\Vdash\psi$ by the induction hypothesis. Therefore, $w\nVdash\H_a\psi$ by item 6(b) of Definition~\ref{sat}. If formula $\phi$ has the form $\S_a\psi$, then the argument is similar to the one above, except that Lemma~\ref{S child all} and Lemma~\ref{S children exist} are used instead of Lemma~\ref{H child all} and Lemma~\ref{H children exist} respectively. \end{proof} \begin{theorem}[strong completeness] If $X\nvdash \phi$, then there is world $w$ of an epistemic model with preferences such that $w\Vdash\chi$ for each formula $\chi\in X$ and $w\nVdash \phi$. \end{theorem} \begin{proof} The assumption $X\nvdash \phi$ implies that set $X\cup\{\neg\phi\}$ is consistent. Thus, by Lemma~\ref{Lindenbaum's lemma}, there is a maximal consistent set $w$ such that $X\cup\{\neg\phi\}\subseteq w$. Consider canonical epistemic model with preferences $M(w)$. By Lemma~\ref{X0 in W lemma}, set $w$ is one of the worlds of this model. Then, $w\Vdash \chi$ for any formula $\chi\in X$ and $w\Vdash \neg\phi$ by Lemma~\ref{induction lemma}. Therefore, $w\nVdash \phi$ by item 2 of Definition~\ref{sat}. \end{proof} \section{Conclusion} In this article we proposed a formal semantics for happiness and sadness, proved that these two notions are not definable through each other and gave a complete logical system capturing the properties of these notions. The approach to happiness that we advocated could be captured by famous saying ``Success is getting what you want, happiness is wanting what you get''. Although popular, this view is not the only possible. As we mentioned in the introduction, some view happiness as ``getting what you want''. As defined in this article, happiness and sadness are grounded in agent's knowledge. We think that an interesting next step could be exploring belief-based happiness and sadness. A framework for beliefs, similar to our epistemic models with preferences, has been proposed by Liu~\cite{l11springer}. \bibliographystyle{elsarticle-num}
{'timestamp': '2021-01-05T02:19:02', 'yymm': '2101', 'arxiv_id': '2101.00485', 'language': 'en', 'url': 'https://arxiv.org/abs/2101.00485'}
arxiv
\section{Introduction} Pretrained language models (PLMs) such as BERT \citep{Devlin.2019}, GPT-2 \citep{Radford.2019}, XLNet \citep{Yang.2019}, ELECTRA \citep{Clark.2020}, and T5 \citep{Raffel.2020} have yielded substantial improvements on a range of NLP tasks. What linguistic properties do they have? Various studies have tried to illuminate this question, with a focus on syntax \citep{Hewitt.2019, Jawahar.2019} and semantics \citep{Ethayarajh.2019,Ettinger.2020, Vulic.2020}. One common characteristic of PLMs is their input segmentation: PLMs are based on fixed-size vocabularies of words and subwords that are generated by compression algorithms such as byte-pair encoding \citep{Gage.1994, Sennrich.2016} and WordPiece \citep{Schuster.2012, Wu.2016}. The segmentations produced by these algorithms are linguistically questionable at times \citep{Church.2020}, which has been shown to worsen performance on certain downstream tasks \citep{Bostrom.2020, Hofmann.2020c}. However, the wider implications of these findings, particularly with regard to the generalization capabilities of PLMs, are still poorly understood. Here, we address a central aspect of this issue, namely how the input segmentation affects the semantic representations of PLMs, taking BERT as the example PLM. We focus on derivationally complex words such as \texttt{superbizarre} since they exhibit systematic patterns on the lexical level, providing an ideal testbed for linguistic generalization. At the same time, the fact that low-frequency and out-of-vocabulary words are often derivationally complex \citep{Baayen.1991} makes our work relevant in practical settings, especially when many one-word expressions are involved, e.g., in query processing \citep{Kacprzak.2017}. \begin{figure} \centering \begin{subfigure}[b]{0.23\textwidth} \centering \includestandalone[width=\textwidth]{model_wordpiece \caption[]% {{\small BERT ($s_w$)}} \label{fig:bert-ws} \end{subfigure} \hspace{1mm} \begin{subfigure}[b]{0.23\textwidth} \centering \includestandalone[width=\textwidth]{model_derivational}% \caption[]% {{\small DelBERT ($s_d$)}} \label{fig:bert-ds} \end{subfigure} \caption[]{Basic experimental setup. BERT with WordPiece segmentation ($s_w$) mixes part of the stem \texttt{bizarre} with the prefix \texttt{super}, creating an association with \texttt{superb} (left panel). DelBERT with derivational segmentation ($s_d$), on the other hand, separates prefix and stem by a hyphen (right panel). The two likelihoods are averaged across 20 models trained with different random seeds. The average likelihood of the true class is considerably higher with DelBERT than with BERT. While \texttt{superbizarre} has negative sentiment, \texttt{applausive} is an example of a complex word with positive sentiment. } \label{fig:model} \end{figure} The topic of this paper is related to the more fundamental question of how PLMs represent the meaning of complex words in the first place. So far, most studies have focused on methods of representation extraction, using ad-hoc heuristics such as averaging the subword embeddings \citep{Pinter.2020b, Sia.2020, Vulic.2020} or taking the first subword embedding \citep{Devlin.2019, Heinzerling.2019, Martin.2020}. While not resolving the issue, we lay the theoretical groundwork for more systematic analyses by showing that PLMs can be regarded as serial dual-route models \citep{Caramazza.1988}, i.e., the meanings of complex words are either stored or else need to be computed from the subwords. \textbf{Contributions.} We present the first study examining how the input segmentation of PLMs, specifically BERT, affects their interpretations of derivationally complex English words. We show that PLMs can be interpreted as serial dual-route models, which implies that maximally meaningful input tokens should allow for the best generalization on new words. This hypothesis is confirmed by a series of semantic probing tasks on which derivational segmentation substantially outperforms BERT's WordPiece segmentation. This suggests that the generalization capabilities of PLMs could be further improved if a morphologically-informed vocabulary of input tokens were used. We also publish three large datasets of derivationally complex words with corresponding semantic properties.\footnote{We make our code and data available at \url{https://github.com/valentinhofmann/superbizarre}.} \section{How Are Complex Words Processed?} \subsection{Complex Words in Psycholinguistics} The question of how complex words are processed has been at the center of psycholinguistic research over the last decades (see \citet{Leminen.2019} for a recent review). Two basic processing mechanisms have been proposed: \textit{storage}, where the meaning of complex words is listed in the mental lexicon \citep{Manelis.1977, Butterworth.1983b, Feldman.1987, Bybee.1988, Stemberger.1994, Bybee.1995, Bertram.2000b}, and \textit{computation}, where the meaning of complex words is inferred based on the meaning of stem and affixes \citep{Taft.1975, Taft.1979, Taft.1981, Taft.1988, Taft.1991, Taft.1994, Rastle.2004, Taft.2004, Rastle.2008}. In contrasting with \textit{single-route} frameworks, \textit{dual-route} models allow for a combination of storage and computation. Dual-route models are further classified by whether they regard the processes of retrieving meaning from the mental lexicon and computing meaning based on stem and affixes as \textit{parallel}, i.e., both mechanisms are always activated \citep{Frauenfelder.1992, Schreuder.1995, Baayen.1997, Baayen.2000, Bertram.2000c, New.2004, Kuperman.2008, Kuperman.2009}, or \textit{serial}, i.e., the computation-based mechanism is only activated when the storage-based one fails \citep{Laudanna.1985, Burani.1987, Caramazza.1988, Burani.1992, Laudanna.1995, Alegre.1999b}. Outside the taxonomy presented so far are recent models that assume multiple levels of representation as well as various forms of interaction between them \citep{Racz.2015, Needle.2018}. In these models, sufficiently frequent complex words are stored together with representations that include their internal structure. Complex-word processing is driven by analogical processes over the mental lexicon \citep{Racz.2020}. \subsection{Complex Words in NLP and PLMs} \label{sec:complex-nlp} Most models of word meaning proposed in NLP can be roughly assigned to either the single-route or dual-route approach. Word embeddings that represent complex words as whole-word vectors \citep{Deerwester.1990, Mikolov.2013b, Mikolov.2013c, Pennington.2014} can be seen as single-route storage models. Word embeddings that represent complex words as a function of subword or morpheme vectors \citep{Schutze.1992b,Luong.2013} can be seen as single-route computation models. Finally, word embeddings that represent complex words as a function of subword or morpheme vectors as well as whole-word vectors \citep{Botha.2014, Qiu.2014, Bhatia.2016, Bojanowski.2017, Athiwaratkun.2018, Salle.2018} are most closely related to parallel dual-route approaches. Where are PLMs to be located in this taxonomy? PLMs represent many complex words as whole-word vectors (which are fully stored). Similarly to how character-based models represent word meaning \citep{Kim.2016, Adel.2017}, they can also store the meaning of frequent complex words that are segmented into subwords, i.e., frequent subword collocations, in their model weights. When the complex-word meaning is neither stored as a whole-word vector nor in the model weights, PLMs compute the meaning as a compositional function of the subwords. Conceptually, PLMs can thus be interpreted as serial dual-route models. While the parallelism has not been observed before, it follows logically from the structure of PLMs. The key goal of this paper is to show that the implications of this observation are borne out empirically. As a concrete example, consider the complex words \texttt{stabilize}, \texttt{realize}, \texttt{finalize}, \texttt{mobilize}, \texttt{tribalize}, and \texttt{templatize}, which are all formed by adding the verbal suffix \texttt{ize} to a nominal or adjectival stem. Taking BERT, specifically BERT\textsubscript{BASE} (uncased) \citep{Devlin.2019}, as the example PLM, the words \texttt{stabilize} and \texttt{realize} have individual tokens in the input vocabulary and are hence associated with whole-word vectors storing their meanings, including highly lexicalized meanings as in the case of \texttt{realize}. By contrast, the words \texttt{finalize} and \texttt{mobilize} are segmented into \texttt{final}, \texttt{\#\#ize} and \texttt{mob}, \texttt{\#\#ili}, \texttt{\#\#ze}, which entails that their meanings are not stored as whole-word vectors. However, both words have relatively high absolute frequencies of 2,540 (\texttt{finalize}) and 6,904 (\texttt{mobilize}) in the English Wikipedia, the main dataset used to pretrain BERT \citep{Devlin.2019}, which means that BERT can store their meanings in its model weights during pretraining.\footnote{Previous research suggests that such lexical knowledge is stored in the lower layers of BERT \citep{Vulic.2020}.} Notice this is even possible in the case of highly lexicalized meanings as for \texttt{mobilize}. Finally, the words \texttt{tribalize} and \texttt{templatize} are segmented into \texttt{tribal}, \texttt{\#\#ize} and \texttt{te}, \texttt{\#\#mp}, \texttt{\#\#lat}, \texttt{\#\#ize}, but as opposed to \texttt{finalize} and \texttt{mobilize} they do not occur in the English Wikipedia. As a result, BERT cannot store their meanings in its model weights during pretraining and needs to compute them from the meanings of the subwords. Seeing PLMs as serial dual-route models allows for a more nuanced view on the central research question of this paper: in order to investigate semantic generalization we need to investigate the representations of those complex words that activate the computation-based route. The words that do so are the ones whose meaning is neither stored as a whole-word vector nor in the model weights and hence needs to be computed compositionally as a function of the subwords (\texttt{tribalize} and \texttt{templatize} in the discussed examples). We hypothesize that the morphological validity of the segmentation affects the representational quality in these cases, and that the best generalization is achieved by maximally meaningful tokens. It is crucial to note this does not imply that the tokens have to be morphemes, but the segmentation boundaries need to coincide with morphological boundaries, i.e., groups of morphemes (e.g., \texttt{tribal} in the segmentation of \texttt{tribalize}) are also possible.\footnote{This is in line with substantial evidence from linguistics showing that frequent groups of morphemes can be treated as semantic wholes \citep{Stump.2017, Stump.2019}.} For \texttt{tribalize} and \texttt{templatize}, we therefore expect the segmentation \texttt{tribal}, \texttt{\#\#ize} (morphologically valid since all segmentation boundaries are morpheme boundaries) to result in a representation of higher quality than the segmentation \texttt{te}, \texttt{\#\#mp}, \texttt{\#\#lat}, \texttt{\#\#ize} (morphologically invalid since the boundaries between \texttt{te}, \texttt{\#\#mp}, and \texttt{\#\#lat} are not morpheme boundaries). On the other hand, complex words whose meanings are stored in the model weights (\texttt{finalize} and \texttt{mobilize} in the discussed examples) are expected to be affected by the segmentation to a much lesser extent: if the meaning of a complex word is stored in the model weights, it should matter less whether the specific segmentation activating that meaning is morphologically valid (\texttt{final}, \texttt{\#\#ize}) or not (\texttt{mob}, \texttt{\#\#ili}, \texttt{\#\#ze}).\footnote{We expect the distinction between storage and computation of complex-word meaning for PLMs to be a continuum. While the findings presented here are consistent with this view, we defer a more in-depth analysis to future work.} \section{Experiments} \begin{table*} [t!]\centering \resizebox{\linewidth}{!}{% \begin{tabular}{@{}llrllll@{}} \toprule {} & {} & {} & \multicolumn{2}{c}{Class 1} & \multicolumn{2}{c}{Class 2} \\ \cmidrule(lr){4-5} \cmidrule(l){6-7} Dataset & Dimension & $|\mathcal{D}|$ & Class & Examples & Class & Example \\ \midrule Amazon & Sentiment & 239,727 & \texttt{neg} & \texttt{overpriced}, \texttt{crappy} & \texttt{pos} & \texttt{megafavorite}, \texttt{applausive}\\ ArXiv & Topicality & 97,410 & \texttt{phys} & \texttt{semithermal}, \texttt{ozoneless} & \texttt{cs} & \texttt{autoencoded}, \texttt{rankable} \\ Reddit & Topicality & 85,362 & \texttt{ent} & \texttt{supervampires}, \texttt{spoilerful} & \texttt{dis} & \texttt{antirussian}, \texttt{immigrationism}\\ \bottomrule \end{tabular}} \caption{Dataset characteristics. The table provides information about the datasets such as the relevant semantic dimensions with their classes and example complex words. $|\mathcal{D}|$: number of complex words; \texttt{neg}: negative; \texttt{pos}: positive; \texttt{phys}: physics; \texttt{cs}: computer science; \texttt{ent}: entertainment; \texttt{dis}: discussion. } \label{tab:data-stats} \end{table*} \subsection{Setup} Analyzing the impact of different segmentations on BERT's semantic generalization capabilities is not straightforward since it is not clear a priori how to measure the quality of representations. Here, we devise a novel lexical-semantic probing task: we use BERT's representations for complex words to predict semantic dimensions, specifically sentiment and topicality (see Figure \ref{fig:model}). For sentiment, given the example complex word \texttt{superbizarre}, the task is to predict that its sentiment is negative. For topicality, given the example complex word \texttt{isotopize}, the task is to predict that it is used in physics. We confine ourselves to binary prediction, i.e., the probed semantic dimensions always consist of two classes (e.g., positive and negative). The extent to which a segmentation supports a solution of this task is taken as an indicator of its representational quality. More formally, let $\mathcal{D}$ be a dataset consisting of complex words $x$ and corresponding classes $y$ that instantiate a certain semantic dimension (e.g., sentiment). We denote with $s(x) = (t_1, \dots, t_k)$ the segmentation of $x$ into a sequence of $k$ subwords. We ask how $s$ impacts the capability of BERT to predict $y$, i.e., how $p(y|(s(x))$, the likelihood of the true semantic class $y$ given a certain segmentation of $x$, depends on different choices for $s$. The two segmentation methods we compare in this study are BERT's standard WordPiece segmentation \citep{Schuster.2012, Wu.2016}, $s_w$, and a derivational segmentation that segments complex words into stems and affixes, $s_d$. \subsection{Data} \label{sec:data} \begin{table*} [t!]\centering \resizebox{0.7\linewidth}{!}{% \begin{tabular}{@{}lrrrrrr@{}} \toprule {} & \multicolumn{2}{c}{Amazon} & \multicolumn{2}{c}{ArXiv} & \multicolumn{2}{c}{Reddit} \\ \cmidrule(lr){2-3} \cmidrule(lr){4-5} \cmidrule(l){6-7} Model & Dev & Test & Dev & Test & Dev & Test \\ \midrule DelBERT & \best{.635 $\pm$ .001} & \best{.639 $\pm$ .002} & \best{.731 $\pm$ .001} & \best{.723 $\pm$ .001} & \best{.696 $\pm$ .001} & \best{.701 $\pm$ .001} \\ BERT & \second{.619 $\pm$ .001} & \second{.624 $\pm$ .001} & .704 $\pm$ .001 & \second{.700 $\pm$ .002} & .664 $\pm$ .001 & .664 $\pm$ .003\\ \midrule Stem & .572 $\pm$ .003 & .573 $\pm$ .003 & \second{.705 $\pm$ .001} & .697 $\pm$ .001 & \second{.679 $\pm$ .001} & \second{.684 $\pm$ .002}\\ Affixes & .536 $\pm$ .008 & .539 $\pm$ .008 & .605 $\pm$ .001 & .603 $\pm$ .002 & .596 $\pm$ .001 & .596 $\pm$ .001\\ \bottomrule \end{tabular} } \caption{Results. The table shows the average performance as well as standard deviation (F1) of 20 models trained with different random seeds. Best result per column highlighted in gray, second-best in light gray.} \label{tab:performance} \end{table*} \begin{figure*}[t!] \centering \includegraphics[width=\linewidth]{results_convergence.png} \caption[]{Convergence analysis. The upper panels show the distributions of the number of epochs after which the models reach their maximum validation performance. The lower panels show the trajectories of the average validation performance (F1) across epochs. The plots are based on 20 models trained with different random seeds. The convergence statistics for DelBERT and BERT are directly comparable because the optimal learning rate is the same (see Appendix \ref{app:hyper}). DelBERT models reach their performance peak faster than BERT models.} \label{fig:convergence} \end{figure*} Since existing datasets do not allow us to conduct experiments following the described setup, we create new datasets in a weakly-supervised fashion that is conceptually similar to the method proposed by \citet{Mintz.2009}: we employ large datasets annotated for sentiment or topicality, extract derivationally complex words, and use the dataset labels to establish their semantic classes. For determining and segmenting derivationally complex words, we use the algorithm introduced by \citet{Hofmann.2020a}, which takes as input a set of prefixes, suffixes, and stems and checks for each word in the data whether it can be derived from a stem using a combination of prefixes and suffixes.\footnote{The distinction between inflectionally and derivationally complex words is notoriously fuzzy \citep{Haspelmath.2010, Hacken.2014}. We try to exclude inflection as far as possible (e.g., by removing problematic affixes such as \texttt{ing}) but are aware that a clear separation does not exist.} The algorithm is sensitive to morpho-orthographic rules of English \cite{Plag.2003}, e.g., when the suffix \texttt{ize} is removed from \texttt{isotopize}, the result is \texttt{isotope}, not \texttt{isotop}. We follow \citet{Hofmann.2020c} in using the prefixes, suffixes, and stems in BERT's WordPiece vocabulary as input to the algorithm. This means that all tokens used by the derivational segmentation are in principle also available to the WordPiece segmentation, i.e., the difference between $s_w$ and $s_d$ does not lie in the vocabulary per se but rather in the way the vocabulary is used. See Appendix \ref{app:segmentation} for details about the derivational segmentation. To get the semantic classes, we compute for each complex word which fraction of texts containing the word belongs to one of two predefined sets of dataset labels (e.g., reviews with four and five stars for positive sentiment) and rank all words accordingly. We then take the first and third tertiles of complex words as representing the two classes. We randomly split the words into 60\% training, 20\% development, and 20\% test. In the following, we describe the characteristics of the three datasets in greater depth. Table \ref{tab:data-stats} provides summary statistics. See Appendix \ref{app:preprocessing} for details about data preprocessing. \textbf{Amazon.} Amazon is an online e-commerce platform. A large dataset of Amazon reviews has been made publicly available \citep{Ni.2019}.\footnote{\url{https://nijianmo.github.io/amazon/index.html}} We extract derivationally complex words from reviews with one or two (\texttt{neg}) as well as four or five stars (\texttt{pos}), discarding three-star reviews for a clearer separation \citep{Yang.2017}. \textbf{ArXiv.} ArXiv is an open-access distribution service for scientific articles. Recently, a dataset of all papers published on ArXiv with associated metadata has been released.\footnote{\url{https://www.kaggle.com/Cornell-University/arxiv}} For this study, we extract all articles from physics (\texttt{phys}) and computer science (\texttt{cs}), which we identify using ArXiv's subject classification. We choose physics and computer science since we expect large topical distances for these classes (compared to alternatives such as mathematics and computer science). \textbf{Reddit.} Reddit is a social media platform hosting discussions about various topics. It is divided into smaller communities, so-called subreddits, which have been shown to be a rich source of derivationally complex words \citep{Hofmann.2020b}. \citet{Hofmann.2020c} have published a dataset of derivatives found on Reddit annotated with the subreddits in which they occur.\footnote{\url{https://github.com/valentinhofmann/dagobert}} Inspired by a content-based subreddit categorization scheme,\footnote{\url{https://www.reddit.com/r/TheoryOfReddit/comments/1f7hqc/the_200_most_active_subreddits_categorized_by}} we define two groups of subreddits, an entertainment set (\texttt{ent}) consisting of the subreddits \texttt{anime}, \texttt{DestinyTheGame}, \texttt{funny}, \texttt{Games}, \texttt{gaming}, \texttt{leagueoflegends}, \texttt{movies}, \texttt{Music}, \texttt{pics}, and \texttt{videos}, as well as a discussion set (\texttt{dis}) consisting of the subreddits \texttt{askscience}, \texttt{atheism}, \texttt{conspiracy}, \texttt{news}, \texttt{Libertarian}, \texttt{politics}, \texttt{science}, \texttt{technology}, \texttt{TwoXChromosomes}, and \texttt{worldnews}, and extract all derivationally complex words occurring in them. We again expect large topical distances for these classes. Given that the automatic creation of the datasets necessarily introduces noise, we measure human performance on 100 randomly sampled words per dataset, which ranges between 71\% (Amazon) and 78\% (ArXiv). These values can thus be seen as an upper bound on performance. \begin{figure*}[t!] \centering \includegraphics[width=\linewidth]{results_freq.png} \caption[]{Frequency analysis. The plots show the average performance (accuracy) of 20 BERT and DelBERT models trained with different random seeds for complex words of low ($f \leq 5$), mid ($5 < f \leq 500$), and high ($f > 500$) frequency. On all three datasets, BERT performs similarly or better than DelBERT for complex words of high frequency but worse for complex words of low and mid frequency.} \label{fig:frequency} \end{figure*} \subsection{Models} We train two main models on each binary classification task: BERT with the standard WordPiece segmentation ($s_w$) and BERT using the derivational segmentation ($s_d$), a model that we refer to as DelBERT (\textbf{De}rivation \textbf{l}everaging \textbf{BERT}). BERT and DelBERT are identical except for the way in which they use the vocabulary of input tokens (but the vocabulary itself is also identical for both models). The specific BERT variant we use is BERT\textsubscript{BASE} (uncased) \citep{Devlin.2019}. For the derivational segmentation, we follow previous work by \citet{Hofmann.2020c} in separating stem and prefixes by a hyphen. We further follow \citet{Casanueva.2020} and \citet{Vulic.2020} in mean-pooling the output representations for all subwords, excluding BERT's special tokens. The mean-pooled representation is then fed into a two-layer feed-forward network for classification. To examine the relative importance of different types of morphological units, we train two additional models in which we ablate information about stems and affixes, i.e., we represent stems and affixes by the same randomly chosen input embedding.\footnote{For affix ablation, we use two different input embeddings for prefixes and suffixes.} We finetune BERT, DelBERT, and the two ablated models on the three datasets using 20 different random seeds. We choose F1 as the evaluation measure. See Appendix \ref{app:hyper} for details about implementation and hyperparameters. \subsection{Results} \label{sec-results} DelBERT ($s_d$) outperforms BERT ($s_w$) by a large margin on all three datasets (Table \ref{tab:performance}). It is interesting to notice that the performance difference is larger for ArXiv and Reddit than for Amazon, indicating that the gains in representational quality are particularly large for topicality. What is it that leads to DelBERT's increased performance? The ablation study shows that models using only stem information already achieve relatively high performance and are on par or even better than the BERT models on ArXiv and Reddit. However, the DelBERT models still perform substantially better than the stem models on all three datasets. The gap is particularly pronounced for Amazon, which indicates that the interaction between the meaning of stem and affixes is more complex for sentiment than for topicality. This makes sense from a linguistic point of view: while stems tend to be good cues for the topical associations of a complex word, sentiment often depends on semantic interactions between stems and affixes. For example, while the prefix \texttt{un} turns the sentiment of \texttt{amusing} negative, it turns the sentiment of \texttt{biased} positive. Such effects involving negation and antonymy are known to be challenging for PLMs \citep{Ettinger.2020, Kassner.2020} and might be one of the reasons for the generally lower performance on Amazon.\footnote{Another reason for the lower performance on sentiment is that the datasets were created automatically (see Section~\ref{sec:data}), and hence many complex words do not directly carry information about sentiment or topicality. The density of such words is higher for sentiment than topicality since the topic of discussion affects the likelihoods of most content words.} The performance of models using only affixes is much lower. \subsection{Quantitative Analysis} \label{sec:quant-analysis} \begin{figure*} \centering \begin{subfigure}[h]{\textwidth} \centering \includegraphics[width=\textwidth]{results_prefixes_top.png} \caption[]% {{Topicality prediction}} \label{fig:results-top} \vspace{0.3cm} \end{subfigure} \begin{subfigure}[h]{\textwidth} \centering \includegraphics[width=\textwidth]{results_prefixes_sent.png} \caption[]% {{Sentiment prediction}} \label{fig:results-sent} \end{subfigure} \caption[]{Accuracy increase of DelBERT compared to BERT for prefixes. The plots show the accuracy increase as a function of the proportion of morphologically incorrect WordPiece segmentations (topicality prediction) and as ordered boxplot pairs centered on the median accuracy of BERT (sentiment prediction). Negative values mean that the DelBERT models have a lower accuracy than the BERT models for a certain prefix.} \label{fig:prefixes} \end{figure*} To further examine how BERT ($s_w$) and DelBERT ($s_d$) differ in the way they infer the meaning of complex words, we perform a convergence analysis. We find that the DelBERT models reach their peak in performance faster than the BERT models (Figure \ref{fig:convergence}). This is in line with our interpretation of PLMs as serial dual-route models (see Section \ref{sec:complex-nlp}): while DelBERT operates on morphological units and can combine the subword meanings to infer the meanings of complex words, BERT's subwords do not necessarily carry lexical meanings, and hence the derivational patterns need to be stored by adapting the model weights. This is an additional burden, leading to longer convergence times and substantially worse overall performance. Our hypothesis that PLMs can use two routes to process complex words (storage in weights and compositional computation based on input embeddings), and that the second route is blocked when the input segmentation is not morphological, suggests the existence of frequency effects: BERT might have seen frequent complex words multiple times during pretraining and stored their meaning in the model weights. This is less likely for infrequent complex words, making the capability to compositionally infer the meaning (i.e., the computation route) more important. We therefore expect the difference in performance between DelBERT (which should have an advantage on the computation route) and BERT to be larger for infrequent words. To test this hypothesis, we split the complex words of each dataset into three bins of low ($f \leq 5$), mid ($5 < f \leq 500$), and high ($f > 500$) absolute frequencies, and analyze how the performance of BERT and DelBERT differs on the three bins. For this and all subsequent analyses, we merge development and test sets and use accuracy instead of F1 since it makes comparisons across small sets of data points more interpretable. The results are in line with our hypothesis (Figure \ref{fig:frequency}): BERT performs worse than DelBERT on complex words of low and mid frequencies but achieves very similar (ArXiv, Reddit) or even better (Amazon) accuracies on high-frequency complex words. These results strongly suggest that two different mechanisms are involved, and that BERT has a disadvantage for complex words that do not have a high frequency. At the same time, the slight advantage of BERT on high-frequency complex words indicates that it has high-quality representations of these words in its weights, which DelBERT cannot exploit since it uses a different segmentation. \begin{table*} [t!]\centering \resizebox{\linewidth}{!}{% \begin{tabular}{@{}llllrlr@{}} \toprule Dataset & $x$ & $y$ & $s_d(x)$ & $\mu_p$ & $s_w(x)$ & $\mu_p$ \\ \midrule \multirow{3}{*}{Amazon} & \texttt{applausive} & \texttt{pos} & \texttt{applause, \#\#ive} & .847 & \texttt{app, \#\#laus, \#\#ive}& .029\\ & \texttt{superannoying} & \texttt{neg} & \texttt{super, -, annoying} & .967 & \texttt{super, \#\#ann, \#\#oy, \#\#ing} & .278\\ & \texttt{overseasoned} & \texttt{neg} & \texttt{over, -, seasoned} & .956 & \texttt{overseas, \#\#oned} & .219\\ \midrule \multirow{3}{*}{ArXiv}& \texttt{isotopize} & \texttt{phy} & \texttt{isotope, \#\#ize} & .985 & \texttt{iso, \#\#top, \#\#ize} & .039\\ & \texttt{antimicrosoft} & \texttt{cs} & \texttt{anti, -, microsoft} & .936 & \texttt{anti, \#\#mic, \#\#ros, \#\#oft} & .013\\ & \texttt{inkinetic} & \texttt{phy} & \texttt{in, -, kinetic} & .983 & \texttt{ink, \#\#ine, \#\#tic} & .035\\ \midrule \multirow{3}{*}{Reddit} & \texttt{prematuration} &\texttt{dis} & \texttt{premature, \#\#ation} & .848 & \texttt{prem, \#\#at, \#\#uration} & .089\\ & \texttt{nonmultiplayer}& \texttt{ent} & \texttt{non, -, multiplayer} & .950 & \texttt{non, \#\#mu, \#\#lt, \#\#ip, \#\#layer} & .216\\ & \texttt{promosque} & \texttt{dis} & \texttt{pro, -, mosque} & .961 & \texttt{promo, \#\#sque} & .066 \\ \bottomrule \end{tabular}} \caption{Error analysis. The table gives example complex words that are consistently classified correctly by DelBERT and incorrectly by BERT. $x$: complex word; $y$: semantic class; $s_d(x)$: derivational segmentation; $\mu_p$: average likelihood of true semantic class across 20 models trained with different random seeds; $s_w(x)$: WordPiece segmentation. For the complex words shown, $\mu_p$ is considerably higher with DelBERT than with BERT.} \label{tab:qual-analysis} \end{table*} We are further interested to see whether the affix type has an impact on the relative performance of BERT and DelBERT. To examine this question, we measure the accuracy increase of DelBERT as compared to BERT for individual affixes, averaged across datasets and random seeds. We find that the increase is almost twice as large for prefixes ($\mu = .023$, $\sigma= .017$) than for suffixes ($\mu = .013$, $\sigma= .016$), a difference that is shown to be significant by a two-tailed Welch's $t$-test ($d = .642$, $t(82.97) = 2.94$, $p < .01$).\footnote{We use a Welch's instead of Student's $t$-test since it does not assume that the distributions have equal variance.} Why is having access to the correct morphological segmentation more advantageous for prefixed than suffixed complex words? We argue that there are two key factors at play. First, the WordPiece tokenization sometimes generates the morphologically correct segmentation, but it does so with different frequencies for prefixes and suffixes. To detect morphologically incorrect segmentations, we check whether the WordPiece segmentation keeps the stem intact, which is in line with our definition of morphological validity (Section \ref{sec:complex-nlp}) and provides a conservative estimate of the error rate. For prefixes, the WordPiece tokenization is seldom correct (average error rate: $\mu = .903$, $\sigma = .042$), whereas for suffixes it is correct about half the time ($\mu = .503$, $\sigma = .213$). Hence, DelBERT gains a greater advantage for prefixed words. Second, prefixes and suffixes have different linguistic properties that affect the prediction task in unequal ways. Specifically, whereas suffixes have both syntactic and semantic functions, prefixes have an exclusively semantic function and always add lexical-semantic meaning to the stem \citep{Giraudo.2003, Beyersmann.2015}. As a result, cases such as \texttt{unamusing} where the affix boundary is a decisive factor for the prediction task are more likely to occur with prefixes than suffixes, thus increasing the importance of a morphologically correct segmentation.\footnote{Notice that there are suffixes with similar semantic effects (e.g., \texttt{less}), but they are less numerous.} Given the differences between sentiment and topicality prediction, we expect variations in the relative importance of the two identified factors: (i) in the case of sentiment the advantage of $s_d$ should be maximal for affixes directly affecting sentiment; (ii) in the case of topicality its advantage should be the larger the higher the proportion of incorrect segmentations for a particular affix, and hence the more frequent the cases where DelBERT has access to the stem while BERT does not. To test this hypothesis, we focus on predictions for prefixed complex words. For each dataset, we measure for individual prefixes the accuracy increase of the DelBERT models as compared to the BERT models, averaged across random seeds, as well as the proportion of morphologically incorrect segmentations produced by WordPiece. We then calculate linear regressions to predict the accuracy increases based on the proportions of incorrect segmentations. This analysis shows a significant positive correlation for ArXiv ($R^2 = .304$, $F(1, 41)= 17.92$, $p < 0.001$) and Reddit ($R^2 = .270$, $F(1, 40)= 14.80$, $p < 0.001$) but not for Amazon ($R^2 = .019$, $F(1, 41)= .80$, $p = .375$), which is in line with our expectations (Figure \ref{fig:results-top}). Furthermore, ranking the prefixes by accuracy increase for Amazon confirms that the most pronounced differences are found for prefixes that can change the sentiment such as \texttt{non}, \texttt{anti}, \texttt{mal}, and \texttt{pseudo} (Figure \ref{fig:results-sent}). \subsection{Qualitative Analysis} Besides quantitative factors, we are interested in identifying qualitative contexts in which DelBERT has a particular advantage compared to BERT. To do so, we filter the datasets for complex words that are consistently classified correctly by DelBERT and incorrectly by BERT. Specifically, we compute for each word the average likelihood of the true semantic class across DelBERT and BERT models, respectively, and rank words according to the likelihood difference between both model types. Examining the words with the most extreme differences, we observe three classes (Table \ref{tab:qual-analysis}). First, the addition of a suffix is often connected with morpho-orthographic changes (e.g., the deletion of a stem-final \texttt{e}), which leads to a segmentation of the stem into several subwords since the truncated stem is not in the WordPiece vocabulary (\texttt{applausive}, \texttt{isotopize}, \texttt{prematuration}). The model does not seem to be able to recover the meaning of the stem from the subwords. Second, the addition of a prefix has the effect that the word-internal (as opposed to word-initial) form of the stem would have to be available for proper segmentation. Since this form rarely exists in the WordPiece vocabulary, the stem is segmented into several subwords (\texttt{superannoying}, \texttt{antimicrosoft}, \texttt{nonmultiplayer}). Again, it does not seem to be possible for the model to recover the meaning of the stem. Third, the segmentation of prefixed complex words often fuses the prefix with the first characters of the stem (\texttt{overseasoned}, \texttt{inkinetic}, \texttt{promosque}). This case is particularly detrimental since it not only makes it difficult to recover the meaning of the stem but also creates associations with unrelated meanings, sometimes even opposite meanings as in the case of \texttt{superbizarre}. The three classes thus underscore the difficulty of inferring the meaning of complex words from the subwords when the whole-word meaning is not stored in the model weights and the subwords are not morphological. \section{Related Work} Several recent studies have examined how the performance of PLMs is affected by their input segmentation. \citet{Tan.2020} show that tokenizing inflected words into stems and inflection symbols allows BERT to generalize better on non-standard inflections. \citet{Bostrom.2020} pretrain RoBERTa with different tokenization methods and find tokenizations that align more closely with morphology to perform better on a number of tasks. \citet{Ma.2020} show that providing BERT with character-level information also leads to enhanced performance. Relatedly, studies from automatic speech recognition have demonstrated that morphological decomposition improves the perplexity of language models \citep{Fang.2015, Jain.2020}. Whereas these studies change the vocabulary of input tokens (e.g., by adding special tokens), we show that even when keeping the pretrained vocabulary fixed, employing it in a morphologically correct way leads to better performance.\footnote{There are also studies that analyze morphological aspects of PLMs without a focus on questions surrounding segmentation \citep{Edmiston.2020, Klemen.2020}.} Most NLP studies on derivational morphology have been devoted to the question of how semantic representations of derivationally complex words can be enhanced by including morphological information \citep{Luong.2013, Botha.2014, Qiu.2014, Bhatia.2016, Cotterell.2018}, and how affix embeddings can be computed \citep{Lazaridou.2013, Kisselew.2015, Pado.2016}. \citet{Cotterell.2017}, \citet{Vylomova.2017}, and \citet{Deutsch.2018} propose sequence-to-sequence models for the generation of derivationally complex words. \citet{Hofmann.2020c} address the same task using BERT. In contrast, we analyze how different input segmentations affect the semantic representations of derivationally complex words in PLMs, a question that has not been addressed before. \section{Conclusion} We have examined how the input segmentation of PLMs, specifically BERT, affects their interpretations of derivationally complex words. Drawing upon insights from psycholinguistics, we have deduced a conceptual interpretation of PLMs as serial dual-route models, which implies that maximally meaningful input tokens should allow for the best generalization on new words. This hypothesis was confirmed by a series of semantic probing tasks on which DelBERT, a model using derivational segmentation, consistently outperformed BERT using WordPiece segmentation. Quantitative and qualitative analyses further showed that BERT's inferior performance was caused by its inability to infer the complex-word meaning as a function of the subwords when the complex-word meaning was not stored in the weights. Overall, our findings suggest that the generalization capabilities of PLMs could be further improved if a morphologically-informed vocabulary of input tokens were used. \section*{Acknowledgements} This work was funded by the European Research Council (\#740516) and the Engineering and Physical Sciences Research Council (EP/T023333/1). The first author was also supported by the German Academic Scholarship Foundation and the Arts and Humanities Research Council. We thank the reviewers for their helpful comments.
{'timestamp': '2021-06-03T02:25:42', 'yymm': '2101', 'arxiv_id': '2101.00403', 'language': 'en', 'url': 'https://arxiv.org/abs/2101.00403'}
arxiv
\section{Abstract} \label{submission} There has been a tremendous rise in technological advances in the field of automobiles and autonomous vehicles. With the increase in the number of driven vehicles, the safety concerns with the same have also risen. The cases of accidents and life-threatening injuries have skyrocketed. It has become a necessity to provide adequate safety measures in automobiles. This project aims to develop a prototype for a smart vehicle system that provides real-time location of the vehicle on detection of a crash and alert the police station and relatives of the user, it has a panic button feature for a passenger’s safety. We also demonstrate a mechanism for cabin monitoring and an interactive interface between a user and a car, where the user can inquire about the temperature, humidity, and other variables inside the car remotely by sending a text message to the GSM module which is present in the car. The GSM module connects to the Arduino, which fetches the readings from sensors attached to it and sends it back to the user through a text message. We show the integration of MQ3 Alcohol sensor with Arduino for drunk driving prevention. \section{Introduction} \label{submission} Driver safety has been an important feature in automobiles that have been made compulsion in various countries. An increasing number of amateur rash drivers, careless driving, and delayed access to first aid to victims has been a major cause of deaths. Cases of harassment, robbery in cabs are rising with more people using modern-day cab services. Driver fatigue monitoring, accident prevention measures, GPS-based location and nearest hospital alert, smart braking systems, smart airbags, etc. are some of the features currently implemented in a few of the high-end luxury-level vehicles. There hasn't been a cost-efficient model developed for the low-end budget cars. It is important to provide accessible safety measures in the vehicle to minimize the risk of loss of life. This project aims to develop a cost-efficient smart vehicle system that can help aid the cause. Figure \ref{BlockDiagram} shows the block diagram for our prototype. The primary objective of this project is to show how various sensors can be integrated to the Arduino or any microcontroller system, how to communicate with such a system remotely using technologies like GSM and GPS technology, send commands to inquire about the sensor readings and perform desired actions by using the actuators connected to the system. We have developed a low-cost prototype to demonstrate our ideas and create a baseline implementation for research purposes in this relatively new domain of the Internet of Things. With the recent developments in the capacity to process enormous amount of data from sensors, as well as communication technologies such as 5G, we believe our ideas can be scaled and deployed in real-time. The scripts have been made publicly available to the research community for further development \href{https://github.com/Abhishek0697/IoT_SmartCar}{here}. In what follows, we discuss the related prior work for such a problem in the next section (3), followed by defining the Experimental Setup (4) and discussing our novel approaches in section (5), followed with its results and discussion in section (6). Finally, we end the discussion with conclusion and future directions in the last section (7). \begin{figure} \vskip 0.2in \begin{center} \centerline{\includegraphics[width=\columnwidth]{Images/BlockDiagram.png}} \caption{Block Diagram of Proposed Model} \label{BlockDiagram} \end{center} \vskip -0.4in \end{figure} \section{Related Work} According to a Statistical Report \cite{indianexpress_2016} published by the Department of Roads and Highways Transport on Vehicle Mishaps in the country in 2016, the country has recorded 4,60,852 accidents in the year resulting in 1,45,685 deaths. Approximately 423 people died in 1,227 vehicle accidents every day. The data also states that at least 16 deaths occurring in vehicle mishaps out of 55 accidents in every hour in a particular period were primarily because victims were unable to receive suitable treatment within time. Thus, if an alert system is made and an alarm is raised, it might become possible to save many lives. There has been prior work in the area of using GSM and GPS systems along with microcontrollers \cite{shinde2015real} developed a similar tracking system using an Embedded Linux board namely Raspberry Pi and a GSM SIM900A module. The objective of their tracker was to raise an alert whenever the vehicle deviated from the predefined route which was set in the Raspberry Pi by the user. It also had features for sending notifications when the vehicle exceeded a set speed limit. \cite{saaid2014vehicle} implemented a vehicle location finder using a similar combination of GSM and GPS systems particularly for the task of vehicle thefts. \begin{figure}[t] \vskip 0.2in \begin{center} \centerline{\includegraphics[width=6cm, height = 6 cm]{Images/GSMSIM900A.PNG}} \caption{GSM SIM 900A module} \label{GSMSIM900A} \end{center} \vskip -0.4in \end{figure} The use of panic buttons in vehicles is a idea which hasn't been deployed in real-life applications yet. According to the newspaper article \cite{hindustantimes_2016}, the Parliament of India will make it compulsory from 1st of April 2018 for all public transport vehicles which include buses and cabs to have a location tracker device and one or more panic buttons to alert the authorities in case of an emergency. Although, the government has not made the installation of cameras in these vehicles mandatory, primarily citing privacy concerns and due to the factor that it will generate tremendous amounts of data every second. The technology to process such huge data sets is currently unavailable. However, with the development in Internet of Things, in the future, this might be possible using Vehicle to Vehicle Communications. Nowadays, a large population of people chooses to travel by cabs and hence, keeping in mind the safety of the commuters, it is the need of the hour for developing such products. Another study by \cite{deutsche_welle} mentions that according to National Crime Records Bureau (NCRB) report, drunk driving was a major factor in road accidents. 99 per cent of the fatal accidents that occur on the Highways are due to drunk driving and there is no check on this. Majority of these accidents involved trucks since the truck drivers drive irresponsibly when they are fully drunk. Until and unless the nation starts a new system of checking drunk driving on the highways, these fatalities cannot be reduced, as mentioned by a Joint Commissioner of Police. The current system of Drunk driver checking requires traffic police to make people blow into the breath-analyzers. However, it is not sufficient to check every instance of drunk driving cases due to the presence of an enormous number of vehicles on roads and especially outside cities and highways. Thus, an automatic monitoring system is needed to tackle this problem. \begin{figure} \vskip 0.2in \begin{center} \centerline{\includegraphics[width=7cm, height=6cm]{Images/Basic_at_commands.png}} \caption{Basic AT commands used with GSM module} \label{Basic} \end{center} \vskip -0.4in \end{figure} \section{Experimental Setup} \subsection{GSM SMS Alert System} SIM900A Modem is built with Dual Band GSM/ GPRS based SIM900A modem from SIMCOM. It works on frequencies 900/ 1800 MHz SIM900A can search these two bands automatically. The baud rate is configurable from 1200-115200 through AT command. This is a complete GSM module in an SMT type and designed with a very powerful single-chip processor integrating AMR926EJ-S core, allowing you to benefit from small dimensions and cost-effective solutions. Figure \ref{GSMSIM900A} shows a GSM SIM900A module. \begin{figure}[t] \vskip 0.2in \begin{center} \centerline{\includegraphics[width=4cm, height=4cm]{Images/Neo6mGPSmodule.PNG}} \caption{Neo 6m GPS module} \label{GPS} \end{center} \vskip -0.4in \end{figure} \begin{figure}[t] \vskip 0.2in \centerline{\includegraphics[width=6cm, height = 4 cm]{Images/AccidentDetectionPrinciple.PNG}} \caption{Triggering of Airbag circuitry and Accident Alert} \label{Alert} \vskip -0.in \end{figure} \subsection{GPS Tracking} The NEO-6m module shown in Figure \ref{GPS} is a stand-alone GPS receiver featuring the high-performance u-blox 6 positioning engines. It is a flexible and cost-effective receiver that offers numerous connectivity options in a mini 160 x 122 x 24 cm package. It has a compact architecture and power and memory options which makes NEO-6m modules optimal for space constraint, low-cost devices. It has an acquisition engine, and 2 million effective correlators, and can make enormous parallel frequency searches, thus it can find a satellite within a small time. This 50-channel u-blox 6 positioning engine gives a Time to First Fix of around 1-2 seconds. It has an anti-jamming technology, Eeprom for storing settings which gives these receivers fantastic navigation performance even when placed in extremely difficult environments. \subsection{Arduino Uno Development Board} Arduino Uno is a development board based on a dual-inline-package ATmega328 AVR microcontroller \cite{mazidi20058051}. It has 20 digital input/ output pins, 6 of them can be used as Pulse Width Modulated \cite{holtz1992pulsewidth} outputs and 6 can be used as analog inputs. It has a 16 MHz crystal, a USB port, an ICSP header. Programs can be loaded onto it from the Arduino computer program software which is an open-source IDE. The Arduino has a vast support community, which makes it a very easy way to get started working with it. \begin{figure}[t] \vskip 0.2in \begin{center} \centerline{\includegraphics[width=6cm, height = 4 cm]{Images/SW420ImpactSensor.PNG}} \caption{SW420 Impact Sensor } \label{SW420} \end{center} \vskip -0.4in \end{figure} \begin{figure}[t] \vskip 0.2in \begin{center} \centerline{\includegraphics[width=4cm, height = 3.5 cm]{Images/MQ3AlcoholSensor.PNG}} \caption{MQ3 Ethanol Sensor} \label{MQ3} \end{center} \vskip -0.4in \end{figure} \section{Proposed Methodology} \subsection{Accident Detection} When a car hits something with a strong force, it starts to decelerate very rapidly. An Impact Sensor detects the change of velocity/amount of vibration. If the impact is great enough, the impact sensor triggers the airbag circuit and at the same time, it signals the Arduino to send an alert. Thus, when the impact is severe, the Arduino extracts the location by signalling the GPS module which connects with the GPS satellites and retrieves the location of the car. This location co-ordinates along with a google map link are sent to the designated mobile number in an SMS form through the GSM module. The SW420 sensor module gives outputs as ‘1’s or ‘0’s depending on vibration, tilt, and external force applied to it. In absence of vibration, this module gives logic ‘0’ as output and in presence of vibration, it gives logic ‘1’ as output. It has sensitivity control on the board. Figure \ref{SW420} shows the SW420 impact sensor which we have used in our prototype. \subsection{Passenger Safety} A panic button is placed such that whenever a passenger feels terror and discomfort due to certain reasons, an alert message is raised by sending an SMS on pressing the button. There can be multiple panic buttons placed at different spots in the vehicle and connected to the Arduino. \subsection{Drunk Driver Prevention} In this proposed system, an MQ-3 Ethanol Sensor as in Figure \ref{MQ3} is placed on the steering of the car or seat belt of the driver seat, such that it can monitor the percentage of alcohol in the breath of the driver. If it is found to be higher than set limits, then the Arduino signals the GSM to send an alert for the same to the driver’s predefined safety number (such as a home number). Measures can also include not to start the car engine unless the alcohol percentage reduces. When the user exhales, any ethanol present in their breath is oxidized to acetic acid. At the cathode, oxygen from the atmosphere is reduced. The overall reaction is the oxidation of ethyl alcohol. The charge flow produced by this reaction is measured and resistance is calculated, which results in the different levels of intoxication that the Arduino will determine. \begin{figure} \vskip 0.2in \begin{center} \centerline{\includegraphics[width=4cm, height=4cm]{Images/Rainsensormodule.jpg}} \caption{Rain Sensor Module} \label{Rain Sensor Module} \end{center} \vskip -0.4in \end{figure} \subsection{Rain Sensing Automatic Wiper} Car wipers in existing models are controlled manually by the driver. Some of the high-end cars have this feature, but due to cost factors, they have not yet made their way into normal vehicles. A cost-effective version of it is proposed in this project which includes a rain-drop sensor shown in Figure \ref{Rain Sensor Module} connected to the microcontroller, which is Arduino in this case. The rain sensor detects rain and sends the corresponding signal to the Arduino. This signal is then processed by the Arduino to take the desired action. The rain sensor consists of nickel tracks which when gets connected by water droplets in between the two tracks, the circuit gets connected and it detects rain. The raindrop sensor module is low cost and precise for raindrop detection. Its sensitivity can be changed by rotating the screw on the board. It has a digital output pin to indicate whether water is present or not and an analog output pin to give a measure of the intensity of water. The module has a power indicator led and separate control board. A servo motor primarily contains a suitable motor, a gear reduction unit, a position measurement sensor, an control circuitry. Servo motor is a highly precise motor in terms of rotating angle. These are lightweight, low cost, compact motors that can be easily integrated into any circuits. The DC motor is connected to the gear unit which gives feedback to the position sensor. The potentiometer adjusts displacement according to the present position of the motor shaft. As the resistance changes, the differential voltage is generated. A PWM wave is given to the control wire which is transformed into voltage and is compared to the signal generated from the position sensor module. The control pin is connected to the Arduino’s PWM enabled pins. \begin{figure} \vskip 0.2in \begin{center} \centerline{\includegraphics[width=\columnwidth]{Images/final_prototype.jpg}} \caption{Demonstration of Prototype} \label{model} \end{center} \vskip -0.2in \end{figure} \begin{figure} \vskip 0.2in \begin{center} \centerline{\includegraphics[width=6cm, height = 9 cm]{Images/AccidentAlert.PNG}} \caption{SMS sent for Accident detection} \label{Alert} \end{center} \vskip -0.4in \end{figure} \section{Results and Discussion} Figure \ref{model} shows the prototype we have developed for demonstration. Figure \ref{Alert} shows the screenshot of an alert sent by our system on detection of an accident. The text message has information about the location coordinates of the car. The message could be sent to a police station or an designated relative by presetting the number in the system. Similarly, Figure \ref{Panic} shows the screenshot of the message delivered when the panic button in the vehicle is pressed. It has the location coordinated and the link to open it on the Google Map. In addition to these alerts, various other information can be sent in case of an emergency by modifying the code in the system. \begin{figure} \vskip 0.2in \begin{center} \centerline{\includegraphics[width=6cm, height = 9 cm]{Images/PanicButtonAlert.PNG}} \caption{Panic Button Alert } \label{Panic} \end{center} \vskip -0.4in \end{figure} \section{Conclusion and Future Directions} The sensors and equipment proposed in this prototype are low cost and efficient to a great extent, however in order to integrate this features with an existing vehicle's embedded system, a much more compact unit need to be built, which can be added on-chip. We believe that with the development of more high quality and accurate sensors, much more desirable and reliable outputs can be obtained. The main purpose of our demonstrations was to put forward our research ideas with the hope of being further developed by the community and finally being scaled and deployed by the autonomous vehicle industry. \FloatBarrier
{'timestamp': '2021-01-05T02:19:12', 'yymm': '2101', 'arxiv_id': '2101.00496', 'language': 'en', 'url': 'https://arxiv.org/abs/2101.00496'}
arxiv
\section{Introduction} \label{sec:intro} Pooling layers are essential in convolutional neural networks (CNNs) to decrease the size of activation maps. They reduce the computational requirements of the network while also achieving spatial invariance, and increase the receptive field of subsequent convolutions \cite{chen2017dual,real2019regularized,xie2017aggregated}. A range of pooling methods has been proposed, each with different properties (see Section~\ref{sec:related}). Most architectures use maximum or average pooling, both of which are fast and memory-efficient but leave room for improvement in terms of retaining important information in the activation map. \begin{figure*}[ht] \centering \includegraphics[width=\textwidth]{figures/Pooling_types_w_R.pdf} \caption{\textbf{Pooling variants}. $\mathbf{R}$ is the set of pixel values in the kernel neighborhood. (a,b) \textbf{Average and maximum pooling} are based on averaging and maximum activation selection in a kernel. (c) \textbf{Power Average pooling} ($L_{p}$)~\cite{estrach2014signal,gulcehre2014learned} is proportional to average pooling raised to a power ($p$). The output is equal to max-pool for $p \rightarrow \infty$, and sum pooling when $p = 1$. (d) \textbf{Stochastic pooling}~\cite{zeiler2013stochastic} outputs a randomly selected activation from the kernel region. (e) \textbf{Stochastic Spatial Sampling} (S3Pool)~\cite{zhai2017s3pool} samples random horizontal and vertical regions given a specified stride. (f) \textbf{Local Importance Pooling} (LIP)~\cite{gao2019lip} uses a trainable sub-net $G$ to enhance specific features. (g) \textbf{SoftPool} (ours) exponentially weighs the effect of activations using a softmax kernel.} \label{fig:softpool_dist} \vspace{-1em} \end{figure*} We introduce \textit{SoftPool}, a kernel-based pooling method that uses the softmax weighted sum of activations. We demonstrate that SoftPool largely preserves descriptive activation features, while remaining computationally and memory-efficient. Owing to better feature preservation, models that include SoftPool consistently show improved classification performance compared to their original implementations. We make the following contributions: \begin{itemize} \item We introduce SoftPool: a novel pooling method based on softmax normalization that can be used to downsample 2D (image) and 3D (video) activation maps. \item We demonstrate how SoftPool outperforms other pooling methods in preserving the original features, measured using image similarity. \item Experimental results on image and video classification tasks show consistent improvement when replacing the original pooling layers by SoftPool. \end{itemize} The remainder of the paper is structured as follows. We first discuss related work on feature pooling. We then detail SoftPool (Section~\ref{sec:methodology}) and evaluate it in terms of feature loss and image and video classification performance over multiple pooling methods and architectures (Section~\ref{sec:experiments}). \section{Related Work} \label{sec:related} \textbf{Pooling for hand-crafted features}. Downsampling is a widely used technique in hand-coded feature extraction methods. In Bag-of-Words (BoW) \cite{csurka2004visual}, images were viewed as collections of local patches, pooled and encoded as vectors \cite{wang2010locality}. Combinations with Spatial Pyramid Matching \cite{lazebnik2006beyond} aimed to preserve spatial information. Later works considered the selection of the maximum SIFT features in a spatial region \cite{yang2009linear}. Pooling has primarily been linked to the use of max-pooling, because of the feature robustness of biological max-like cortex signals \cite{serre2005object}. Boureau \textit{et al.} \cite{boureau2010theoretical} studied maximum and average pooling in terms of their robustness and usability, and found max-pooling to produce representative results in low feature activation settings. \textbf{Pooling in CNNs}. Pooling has also been adapted to learned feature approaches, as seen in early works in CNNs \cite{lecun1998gradient}. The main benefit of pooling has traditionally been the creation of condensed feature representations which reduce the computational requirements and enable the creation of larger and deeper architectures \cite{simonyan2014very,szegedy2015going}. Recent efforts have focused on preserving relevant features during downsampling. An overview of a number of popular pooling methods appears in Figure~\ref{fig:softpool_dist}. Initial approaches include stochastic pooling \cite{zeiler2013stochastic}, which uses a probabilistic weighted sampling of activations within a kernel region. Mixed pooling based on maximum and average pooling has been used either probabilistically \cite{yu2014mixed} or through a combination of portions from each method \cite{lee2016generalizing}. Based on the combination of averaging and maximization, Power Average ($L_{p}$) pooling \cite{estrach2014signal,gulcehre2014learned} utilizes a learned parameter $p$ to determine the relative importance of both methods. When $p=1$, the local sum is used, while $p\rightarrow \infty$ corresponds to max-pooling. More recent approaches have considered grid-sampling methods. In S3Pool \cite{zhai2017s3pool}, the downsampled outputs stem from randomly sampling the rows and columns of the original feature map grid. Methods that depend on learned weights include Detail Preserving Pooling (DPP, \cite{saeedan2018detail}) that uses average pooling while enhancing activations with above-average values. Local Importance Pooling (LIP, \cite{gao2019lip}) utilizes learned weights as a sub-network attention-based mechanism. Other learned pooling approaches such as Ordinal Pooling \cite{deliege2019ordinal}, which order kernel pixels in discerningly and assigning them trainable weights. More recently, Zhao and Snoek \cite{zhao2021liftpool} proposed a pooling technique named LiftPool based on the use of four different learnable sub-bands of the input. The produced output is composed by a mixture of the discovered sub-bands. \begin{figure*}[ht] \includegraphics[width=\textwidth]{figures/experiments.pdf} \caption{\textbf{Examples of maximum, average and soft pooling}. Images are $1200 \times 1200$ pixels with the $3\times$ pooled equivalents reduced to 12.5\% of the original size. Image selection was based on overall contrast (I, III, V, VIII, XII), color (II, IV, VI, IX), detail (III, V, X, XI, XII) and texture (II, VII). Images on the bottom row are zoomed-in regions. A high resolution version of the regions appears alongside a detailed discussion in \textsection \textcolor{red}{1} of the Supplementary Material. } \label{fig:softpool_examples} \vspace{-.9em} \end{figure*} Most of the aforementioned methods rely on different combinations of maximum and average pooling. Instead of combining existing methods, our work is based on a softmax weighting approach to preserve the basic properties of the input while amplifying feature activations of greater intensity. SoftPool does not require trainable parameters, thus is independent to the training data used. Moreover, it is significantly more computational and memory efficient compared to learned approaches. In contrast to max-pooling, our approach is differentiable. Gradients are obtained for each input during backpropagation, which improves neural connectivity during training. Through the weighted softmax, pooled regions are also less susceptible to vanishing local kernel activations, a common issue with average pooling. We demonstrate the effects of SoftPool in Figure~\ref{fig:softpool_examples}, where the zoomed-in regions show that features are not completely lost as with hard-max selection, or suppressed by the overall region through averaging. \section{SoftPool Downsampling} \label{sec:methodology} We start by formally introducing the forward flow of information in SoftPool and the gradient calculation during backpropagation. We consider a local region ($\mathbf{R}$) in an activation map ($\mathbf{a}$) with dimension $C \times H \times W$ with $C$ the number of channels, $H$ the height and $W$ the width of the activation map. For simplicity of notation, we omit the channel dimension and assume that $\mathbf{R}$ is the set of indices corresponding to the activations in the 2D spatial region under consideration. For a pooling filter of size $k \times k$, we consider $|\mathbf{R}| = k^2$ activations. The output of the pooling operation is $\tilde{\mathbf{a}}_R$ and the corresponding gradients are denoted with $\nabla\mathbf{\tilde{a}}_i$. \subsection{Exponential maximum kernels} \label{sec:methodology::softmax} SoftPool is influenced by the cortex neural simulations of Riesenhuber and Poggio \cite{riesenhuber1999hierarchical} as well as the early pooling experiments with hand-coded features of Boureau \textit{et al.} \cite{boureau2010theoretical}. The proposed method is based on the natural exponent ($e$) which ensures that large activation values will have greater effect on the output. The operation is differentiable, which implies that all activations within the local kernel neighborhood will be assigned a proportional gradient, of at least a minimum value, during backpropagation. This is in contrast to pooling methods that employ hard-max or average pooling. SoftPool utilizes the smooth maximum approximation of the activations within kernel region $\mathbf{R}$. Each activation $\mathbf{a}_i$ with index $i$ is applied a weight $\mathbf{w}_{i}$ that is calculated as the ratio of the natural exponent of that activation with respect to the sum of the natural exponents of all activations within neighborhood $\textbf{R}$: \begin{equation} \label{eq:weight} \mathbf{w}_i=\frac{e^{\mathbf{a}_i}}{\sum\limits_{j \in \mathbf{R}}e^{\mathbf{a}_j}} \end{equation} The weights are used as non-linear transforms in conjunction with the value of the corresponding activation. Higher activations become more dominant than lower-valued ones. Because most pooling operations are performed in high-dimensional feature spaces, highlighting the activations with greater effect is a more balanced approach than simply selecting the average or maximum. In the latter case, discarding the majority of the activations presents the risk of losing important information. Conversely, an equal contribution of activations in average pooling can correspond to local intensity reductions by considering the overall regional feature intensity equally. The output value of the SoftPool operation is produced through a standard summation of all weighted activations within the kernel neighborhood $\mathbf{R}$: \begin{equation} \tilde{\mathbf{a}} =\sum\limits_{i \in \mathbf{R}}\mathbf{w}_{i}*\mathbf{a}_{i} \end{equation} In comparison to other max- and average-based pooling approaches, using the softmax of regions produces normalized results with a probability distribution proportional to the values of each activation with respect to the neighboring activations for the kernel region. This is in direct contrast to popular maximum activation value selection or averaging all activations over the kernel region, where the output activations are not regularized. A full forward and backward information flow is shown in Figure~\ref{fig:softpool}. \begin{figure}[ht] \centering \includegraphics[width=\linewidth]{figures/softpool_kernel.pdf} \caption{\textbf{SoftPool calculation}. In forward operation, in \textcolor{orange}{orange}, the kernel uses the exponential softmax value of each activation as weight and calculates the weighted sum for region $\mathbf{R}$. These weights are also used for the gradients ($\nabla \tilde{\mathbf{a}}_{i}$), in \textcolor{bblue}{blue}. Activation gradients are proportional to the calculated softmax weights.} \label{fig:softpool} \vspace{-.5em} \end{figure} \subsection{Gradient calculation} \label{sec:methodology::gradients} During the update phase in training, gradients of all network parameters are updated based on the error derivatives calculated at the proceeding layer. This creates a chain of updates, when backpropagating throughout the entire network architecture. In SoftPool, gradient updates are proportional to the weights calculated during the forward pass. As softmax is differentiable, unlike maximum or stochastic pooling methods, during backpropagation, a minimum non-zero weight will be assigned to every positive activation within a kernel region. This enables the calculation of a gradient for every non-zero activation in that region, as shown in Figure~\ref{fig:softpool}. In our implementation of SoftPool, we use finite ranges of possible values given a precision level (i.e., half, single or double) as detailed in \textsection \textcolor{red}{7} of the Supplementary Material. We retain the differentiable nature of softmax by assigning a lower arithmetic limit given the number of bits used by each type preventing arithmetic underflow. \subsection{Feature preservation} \label{sec:methodology::feature_preservation} An integral goal of sub-sampling is the preservation of representative features in the input, while simultaneously minimizing the overall resolution. Creating unrepresentative downsampled versions of the original inputs can be harmful to the overall model's performance as the representation of the input is detrimental for the task. Currently widely used pooling techniques can be ineffective in certain cases, as shown in Figures~\ref{fig:softpool_examples} \& \ref{fig:sim_tests}. Average pooling decreases the effect of all activations in the region equally, while max pooling selects only the single highest activation in the region. SoftPool falls between the two, as all activations in the region contribute to the final output, with higher activations are more dominant than lower ones. This balances the effects of both average and max pooling, while leveraging the beneficial properties of both. \subsection{Spatio-temporal kernels} \label{sec:methodology::spacetime} CNNs have also been extended to 3D inputs to include additional dimensions such as depth and time. To accommodate these inputs, we extend SoftPool to include an additional dimension. For an input activation map $\mathbf{a}$ of $C \times H \times W \times T$, with $T$ the temporal extent, we transform the 2D spatial kernel region $\textbf{R}$ to a 3D spatio-temporal region with an additional third temporal dimension. The produced output holds condensed spatio-temporal information. Issues that arise with the introduction of the temporal dimension are discussed and illustrated in \textsection \textcolor{red}{3} of the Supplementary Material. With the added dimension, desired pooling properties such as limited loss of information, a differentiable function, and low computational and memory overhead are even more important. \begin{figure*}[ht] \centering \begin{overpic}[width=\textwidth]{figures/Pooling_comparison_examples.pdf} \put (24.7,9.7) {\tiny{Original (HR)}} \put (33.1,9.7) {\tiny{Average}} \put (39.4,9.7) {\tiny{Maximum}} \put (47.0,9.7) {\tiny{S3}\cite{zhai2017s3pool}} \put (24.5,0.8) {\tiny{Stochastic} \cite{zeiler2013stochastic}} \put (32.5,0.8) {\tiny{$L_{p}$} \cite{gulcehre2014learned}} \put (39.5,0.8) {\tiny{Gate} \cite{lee2016generalizing}} \put (45.15,0.8) {\tiny{SoftPool \textbf{(ours)}}} \put (73.1,9.7) {\tiny{Original (HR)}} \put (81.5,9.7) {\tiny{Average}} \put (87.8,9.7) {\tiny{Maximum}} \put (95.4,9.7) {\tiny{S3}\cite{zhai2017s3pool}} \put (72.9,0.8) {\tiny{Stochastic} \cite{zeiler2013stochastic}} \put (80.9,0.8) {\tiny{$L_{p}$} \cite{gulcehre2014learned}} \put (87.9,0.8) {\tiny{Gate} \cite{lee2016generalizing}} \put (93.55,0.8) {\tiny{SoftPool \textbf{(ours)}}} \end{overpic} \vspace{-4mm} \caption{ \textbf{Visual comparisons over pooling methods}. Both images are from Urban100 \cite{huang2015single}. Left image (\textit{img024}) shows high contrasting borders/edges. Right image (\textit{img078}) presents the inverse of high local values within an overall low-valued region.} \label{fig:sim_tests} \vspace{-.5em} \end{figure*} \begin{table*}[t] \centering \resizebox{\textwidth}{!}{% \begin{tabular}{cl|cc|cc|cc|cc|cc|cc|cc|cc|cc} \hline & \multirow{3}{*}{Pooling method} & \multicolumn{6}{c|}{DIV2K \cite{agustsson2017ntire}} & \multicolumn{6}{c|}{Urban100 \cite{huang2015single}} & \multicolumn{6}{c}{Manga109 \cite{matsui2017sketch}} \\[.3em] & & \multicolumn{2}{c|}{$k=2$} & \multicolumn{2}{c|}{$k=3$} & \multicolumn{2}{c|}{$k=5$} & \multicolumn{2}{c|}{$k=2$} & \multicolumn{2}{c|}{$k=3$} & \multicolumn{2}{c|}{$k=5$} & \multicolumn{2}{c|}{$k=2$} & \multicolumn{2}{c|}{$k=3$} & \multicolumn{2}{c}{$k=5$} \\[.2em]\cline{3-20} & & SSIM & PSNR & SSIM & PSNR & SSIM & PSNR & SSIM & PSNR & SSIM & PSNR & SSIM & PSNR & SSIM & PSNR & SSIM & PSNR & SSIM & PSNR \\[.2em] \hline \parbox[t]{2mm}{\multirow{3}{*}{\rotatebox[origin=c]{90}{}}} & Average & 0.714 & 51.247 & 0.578 & 44.704 & 0.417 & 29.223 & 0.691 & 50.380 & 0.563 & 41.745 & 0.372 & 28.270 & 0.695 & 54.326 & 0.582 & 43.657 & 0.396 & 29.862 \\[.15em] & Maximum & 0.685 & 49.826 & 0.370 & 41.944 & 0.358 & 22.041 & 0.662 & 48.266 & 0.528 & 40.709 & 0.330 & 20.654 & 0.671 & 50.085 & 0.544 & 41.128 & 0.324 & 22.307 \\[.15em] & Pow-average & 0.419 & 35.587 & 0.286 & 26.329 & 0.178 & 16.567 & 0.312 & 31.911 & 0.219 & 24.698 & 0.124 & 15.659 & 0.381 & 29.248 & 0.276 & 18.874 & 0.160 & 9.266 \\[.15em] & Sum & 0.408 & 35.153 & 0.268 & 26.172 & 0.193 & 17.315 & 0.301 & 31.657 & 0.208 & 24.735 & 0.123 & 15.243 & 0.374 & 30.169 & 0.271 & 20.150 & 0.168 & 13.081 \\[.15em]\cline{1-20} \parbox[t]{2mm}{\multirow{4}{*}{\rotatebox[origin=c]{90}{Trainable}}} & $L_{p}$ \cite{gulcehre2014learned} & 0.686 & 49.912 & 0.542 & 43.083 & 0.347 & 25.139 & 0.676 & 48.508 & 0.534 & 39.986 & 0.326 & 26.365 & 0.675 & 51.721 & 0.561 & 41.824 & 0.367 & 27.469 \\[.15em] & Gate \cite{lee2016generalizing} & 0.689 & 50.104 & 0.560 & 43.437 & 0.353 & 25.672 & 0.675 & 49.769 & 0.537 & 40.422 & 0.328 & 26.731 & 0.679 & 51.980 & 0.569 & 42.127 & 0.374 & 27.754 \\[.15em] & Lite-S3DPP \cite{saeedan2018detail} & 0.702 & 50.598 & 0.562 & 44.076 & 0.396 & 27.421 & 0.684 & 49.947 & 0.551 & 40.813 & 0.365 & 27.136 & 0.691 & 52.646 & 0.573 & 42.794 & 0.386 & 28.598 \\[.15em] & LIP \cite{gao2019lip} & 0.711 & 50.831 & 0.559 & 44.432 & 0.401 & 28.285 & 0.689 & 50.266 & 0.558 & 41.159 & 0.370 & 27.849 & 0.689 & 53.537 & 0.579 & 43.018 & 0.391 & 29.331 \\[.15em]\cline{1-20} \parbox[t]{2mm}{\multirow{2}{*}{\rotatebox[origin=c]{90}{Stoch.}}} & Stochastic \cite{zeiler2013stochastic} & 0.631 & 45.362 & 0.479 & 39.895 & 0.295 & 21.314 & 0.616 & 44.342 & 0.463 & 37.223 & 0.286 & 19.358 & 0.583 & 46.274 & 0.427 & 39.259 & 0.255 & 22.953 \\[.3em] & S3 \cite{zhai2017s3pool} & 0.609 & 44.760 & 0.454 & 39.326 & 0.280 & 20.773 & 0.608 & 44.239 & 0.459 & 36.965 & 0.272 & 19.645 & 0.576 & 46.613 & 0.426 & 39.866 & 0.232 & 23.242 \\[.3em] \cline{1-20} \parbox[t]{2mm}{\rotatebox[origin=c]{90}{~}} & SoftPool (Ours) & \textbf{0.729} & \textbf{51.436} & \textbf{0.594} & \textbf{44.747} & \textbf{0.421} & \textbf{29.583} & \textbf{0.694} & \textbf{50.687} & \textbf{0.578} & \textbf{41.851} & \textbf{0.394} & \textbf{28.326} & \textbf{0.704} & \textbf{54.563} & \textbf{0.586} & \textbf{43.782} & \textbf{0.403} & \textbf{30.114} \\[.15em] \end{tabular} } \caption{\textbf{Quantitative results on benchmark high-res datasets}. Best results from each similarity measure are denoted in \textbf{bold}.} \label{tab:times_ssim_psnr} \vspace{-1em} \end{table*} \section{Experimental Results} \label{sec:experiments} We first evaluate the information loss for various pooling operators. We compare the downsampled outputs to the original inputs using standard similarity measures (Section~\ref{sec:experiments::similarity}). We also investigate each pooling operator's computation and memory overhead (Section~\ref{sec:experiments::latency}). We then focus on the classification performance gain when using SoftPool in a range of popular CNN architectures and in comparison to other pooling methods (Section~\ref{sec:experiments::imagenet}). We also perform an ablation study where we replace max-pooling operations by SoftPool operations in an InceptionV3 architecture (Section~\ref{sec:experiments::multi-layer}). Finally, we demonstrate the merits of SoftPool for spatio-temporal data by focusing on action recognition in video (Section~\ref{sec:experiments::video}). Additionally, we investigate how transfer learning performance is affected when SoftPool is used. \subsection{Experimental settings} \label{sec:experiments::settings} \textbf{Datasets}. For our experiments with images, we employ five different datasets for the tasks of image quality quantitative evaluation and classification. For image quality and similarity assessment we use high-resolution DIV2K \cite{agustsson2017ntire}, Urban100 \cite{huang2015single}, Manga109 \cite{matsui2017sketch}, and Flicker2K \cite{agustsson2017ntire}. ImageNet1K \cite{ILSVRC15} is used for the classification task. For video-based action recognition, we use the large-scale HACS \cite{zhao2019hacs} and Kinetics-700 \cite{carreira2019short} datasets. Our transfer learning experiments are performed on the UCF-101 \cite{soomro2012ucf101} dataset. \textbf{Training implementation details}. For the image classification task, we perform random region selection of $294 \times 294$ height and width, which was then resized to $224 \times 224$. We use an initial learning rate of 0.1 with an SGD optimizer and a step-wise learning rate reduction every 40 epochs for a total of 100 epochs. The epochs number was chosen as no further improvements were observed for any of the models. We also set the batch size to 256 across all models. For our experiments on videos, we use a multigrid training scheme \cite{wu2020multigrid}, with frame sizes between 4--16 and frame crops of 90--256 depending on the cycle. On average, the video inputs are of size $8 \times 160 \times 160$. With the multigrid scheme, the batch sizes are between 64 and 2048 with each size counter-equal to the input size in every step to match the memory use. We use the same learning rate, optimizer, learning rate schedule and maximum number of epochs as in the image-based experiments. \begin{table*}[t] \centering \resizebox{\linewidth}{!}{% \begin{tabular}{l|c|c|cc|cc|cc} \hline \multirow{2}{*}{Model} & Params & \multirow{2}{*}{GFLOP} & \multicolumn{2}{c|}{Original} & \multicolumn{2}{c|}{SoftPool (pre-train)} & \multicolumn{2}{c}{SoftPool (from scratch)} \\ & (M) & & top-1 & top-5 & top-1 & top-5 & top-1 & top-5 \\ \hline ResNet18 & 11.7 & 1.83 & 69.76 & 89.08 & 70.56 (\textcolor{applegreen}{+0.80}) & 89.89 (\textcolor{applegreen}{+0.81}) & \textbf{71.27} (\textcolor{applegreen}{+1.51}) & \textbf{90.16} (\textcolor{applegreen}{+1.08})\\[0.1em] ResNet34 & 21.8 & 3.68 & 73.30 & 91.42 & 74.03 (\textcolor{applegreen}{+0.73}) & 91.85 (\textcolor{applegreen}{+0.43}) & \textbf{74.67} (\textcolor{applegreen}{+1.37}) & \textbf{92.30} (\textcolor{applegreen}{+0.88})\\[0.1em] ResNet50 & 25.6 & 4.14 & 76.15 & 92.87 & 76.60 (\textcolor{applegreen}{+0.45}) & 93.15 (\textcolor{applegreen}{+0.28}) & \textbf{77.35} (\textcolor{applegreen}{+1.17}) & \textbf{93.63} (\textcolor{applegreen}{+0.76})\\[0.1em] ResNet101 & 44.5 & 7.87 & 77.37 & 93.56 & 77.74 (\textcolor{applegreen}{+0.37}) & 93.99 (\textcolor{applegreen}{+0.43}) & \textbf{78.32} (\textcolor{applegreen}{+0.95}) & \textbf{94.21} (\textcolor{applegreen}{+0.65})\\[0.1em] ResNet152 & 60.2 & 11.61 & 78.31 & 94.06 & 78.73 (\textcolor{applegreen}{+0.42}) & 94.47 (\textcolor{applegreen}{+0.41}) & \textbf{79.24} (\textcolor{applegreen}{+0.92}) & \textbf{94.72} (\textcolor{applegreen}{+0.66})\\[0.1em] \hline DenseNet121 & 8.0 & 2.90 & 74.65 & 92.17 & 75.27 (\textcolor{applegreen}{+0.57}) & 92.60 (\textcolor{applegreen}{+0.43}) & \textbf{75.88} (\textcolor{applegreen}{+1.23}) & \textbf{92.92} (\textcolor{applegreen}{+0.75})\\[0.1em] DenseNet161 & 28.7 & 7.85 & 77.65 & 93.80 & 78.12 (\textcolor{applegreen}{+0.47}) & 94.15 (\textcolor{applegreen}{+0.35}) & \textbf{78.72} (\textcolor{applegreen}{+0.93}) & \textbf{94.41} (\textcolor{applegreen}{+0.61})\\[0.1em] DenseNet169 & 14.1 & 3.44 & 76.00 & 93.00 & 76.49 (\textcolor{applegreen}{+0.49}) & 93.38 (\textcolor{applegreen}{+0.38}) & \textbf{76.95} (\textcolor{applegreen}{+0.95}) & \textbf{93.76} (\textcolor{applegreen}{+0.76})\\[0.1em] \hline ResNeXt50 32x4d & 25.0 & 4.29 & 77.62 & 93.70 & 78.23 (\textcolor{applegreen}{+0.61}) & 93.97 (\textcolor{applegreen}{+0.27}) & \textbf{78.48} (\textcolor{applegreen}{+0.86}) & \textbf{93.37} (\textcolor{applegreen}{+0.67})\\[0.1em] ResNeXt101 32x8d & 88.8 & 7.89 & 79.31 & 94.28 & 78.89 (\textcolor{applegreen}{+0.58}) & 94.73 (\textcolor{applegreen}{+0.45}) & \textbf{80.12} (\textcolor{applegreen}{+0.81}) & \textbf{94.88} (\textcolor{applegreen}{+0.60})\\[0.1em] \hline Wide-ResNet50 & 68.9 & 11.46 & 78.51 & 94.09 & 79.14 (\textcolor{applegreen}{+0.63}) & 94.51 (\textcolor{applegreen}{+0.42}) & \textbf{79.52} (\textcolor{applegreen}{+1.01}) & \textbf{94.85} (\textcolor{applegreen}{+0.76})\\[0.1em] \end{tabular} } \caption{\textbf{Trained from scratch and pre-trained pairwise comparisons of top-1 and top-5 accuracies} on ImageNet1K between the original networks and the same networks with pooling replaced by SoftPool.} \label{tab:ImageNet_pre_retrained} \vspace{-1em} \end{table*} \subsection{Downsampling similarity} \label{sec:experiments::similarity} We first assess the information loss of various pooling operations. We compare the original inputs with the downsampled outputs in terms of similarity. We use three of the most widely used kernel sizes (i.e., $k \! \times \! k$, with $k = \{2,3,5\})$. Our experiments are based on two standardized image similarity evaluation metrics \cite{wang2004image}: \textbf{Structural Similarity Index Measure (SSIM)} is used between the original and downsampled images. SSIM is based on the computation of a luminance, contrast and structural term. Larger index values correspond to larger structural similarities between the images compared. \textbf{Peak Signal-to-Noise Ratio (PSNR)} measures the compression quality of the resulting image based on the Mean Squared Error (MSE) inverse between the weighted averages of their channels. PSNR depends on the MSE with higher values relate to lower errors between the two images. Visual examples of different compression methods are shown in Figure~\ref{fig:sim_tests}. The proposed SoftPool method can represent regions with borders between low and high frequencies better than other methods, shown by the border of the black bar in the left image. The inverse also hold true for a high-frequency location within an overall low-frequency region as shown in the left image. In such cases, max and stochastic-based methods \cite{gulcehre2014learned,zeiler2013stochastic,zhai2017s3pool} over-amplify pixel locations in the subsampled volumes while these pixels are completely lost in the downsampled volume through average and gate \cite{lee2016generalizing} cases. In contrast, SoftPool shows the ability to preserve such patterns as also shown in Figure~\ref{fig:softpool_op}. In Tables~\ref{tab:times_ssim_psnr} and \ref{tab:compute_flicker}, we show the average SSIM and PSNR values obtained on DIV2K \cite{agustsson2017ntire}, Urban100 \cite{huang2015single}, Manga109 \cite{matsui2017sketch}, and Flicker2K \cite{agustsson2017ntire} high-resolution datasets over different kernel sizes. For both measures, SoftPool outperforms all other methods by a reasonable margin. Notably, it significantly outperforms non-trainable and stochastic methods. The randomized strategy of stochastic methods does not effectively allow their use as a standalone method as they lack non-linear operations. Trainable approaches are bounded by both the image types they have been trained on as well as on the discovered channel correlations during pooling. \begin{table}[t] \centering \resizebox{\linewidth}{!}{% \begin{tabular}{l|c|c|cc|cc|cc} \hline \multirow{3}{*}{Pooling} & \multirow{2}{*}{CPU (ms)} & \multirow{2}{*}{CUDA (ms)} & \multicolumn{6}{c}{Flicker2K\cite{agustsson2017ntire}} \\[.3em] & & & \multicolumn{2}{c|}{$k=2$} & \multicolumn{2}{c|}{$k=3$} & \multicolumn{2}{c}{$k=5$} \\[.2em]\cline{4-9} & ($\downarrow$ F / $\uparrow$ B) & ($\downarrow$ F / $\uparrow$ B) & SSIM & PSNR & SSIM & PSNR & SSIM & PSNR\\[.2em] \hline Avg & 9 / 49 & 14 / 76 & 0.709 & 51.786 & 0.572 & 44.246 & 0.408 & 28.957\\[.15em] Max & 91 / 152 & 195 / 267 & 0.674 & 47.613 & 0.385 & 40.735 & 0.329 & 21.368 \\[.15em] Pow-avg & 74 / 329 & 120 / 433 & 0.392 & 34.319 & 0.271 & 26.820 & 0.163 & 15.453\\[.15em] Sum & 26 / 163 & 79 / 323 & 0.386 & 34.173 & 0.265 & 26.259 & 0.161 & 15.218\\[.15em]\cline{1-9} $L_{p}$ \cite{gulcehre2014learned} & 116 / 338 & 214 / 422 & 0.683 & 48.617 & 0.437 & 42.079 & 0.341 & 24.432\\[.15em] Gate \cite{lee2016generalizing} & 245 / 339 & 327 / 540 & 0.687 & 49.314 & 0.449 & 42.722 & 0.358 & 25.687 \\[.15em] DPP \cite{saeedan2018detail} & 427 / 860 & 634 / 1228 & 0.691 & 50.586 & 0.534 & 43.608 & 0.385 & 27.430 \\[.15em] LIP \cite{gao2019lip} & 134 / 257 & 258 / 362 & 0.696 & 50.947 & 0.548 & 43.882 & 0.390 & 28.134 \\[.15em]\cline{1-9} Stoch. \cite{zeiler2013stochastic} & 162 / 341 & 219 / 485 & 0.625 & 46.714 & 0.474 & 38.365 & 0.264 & 21.428 \\[.3em] S3 \cite{zhai2017s3pool} & 233 / 410 & 345 / 486 & 0.611 & 46.547 & 0.476 & 37.706 & 0.252 & 21.363 \\[.3em] \cline{1-9} SoftPool & 31 / 156 & 56 / 234 & \textbf{0.721} & \textbf{52.356} & \textbf{0.587} & \textbf{44.893} & \textbf{0.416} & \textbf{29.341} \\[.15em] \end{tabular} } \caption{\textbf{Latency and pixel similarity}. Latency times are averaged over ImageNet1K \cite{ILSVRC15}.\vspace{-0.2em}} \label{tab:compute_flicker} \vspace{-1.1em} \end{table} \subsection{Latency and memory use} \label{sec:experiments::latency} Memory and latency costs of pooling operations are largely overlooked as a single operation has negligible latency times and memory consumption. However, because of the parallelization of deep learning models, operations may be performed thousands of times per step. Eventually, a slow or memory-intensive pooling operation can have a detrimental effect on the performance. \begin{figure}[t] \centering \includegraphics[width=\linewidth]{figures/softpool_example.pdf} \caption{\textbf{Results after SoftPool pooling with different kernel and stride sizes}. Image (\textit{img003}) is from Urban100 \cite{huang2015single}.} \label{fig:softpool_op} \vspace{-1.2em} \end{figure} To test the computation and memory overhead, we report running-time memory use and inference on both CPU and GPU (CUDA) in Table~\ref{tab:compute_flicker}. We detail our testing environment and implementation in \textsection \textcolor{red}{7} of the Supplementary Material. From Table~\ref{tab:compute_flicker} we observe that our implementation of SoftPool achieves low inference times for both CPU- and CUDA-based operations, while remaining memory-efficient. This is because the method allows parallelization and is simple to compute within a region. SoftPool is second only to average pooling in terms of latency and memory use as operations can be performed in-place at the tensor. \subsection{Classification performance on ImageNet1K} \label{sec:experiments::imagenet} We investigate whether classification accuracy improves as a result of SoftPool's superior ability to retain information. We replace the original pooling layers in ResNet \cite{he2016deep}, DenseNet \cite{huang2017densely}, ResNeXt \cite{xie2017aggregated} and wide-ResNet \cite{zagoruyko2016wide} networks. These models were chosen because of their wide use. We consider two distinct settings. In the \textit{from scratch} setting, we replace the pooling operators of the original models by SoftPool and train with weights randomly initialized. In the \textit{pre-trained} setting, we replace pooling layers of the original trained networks and evaluate the effects of the layer change on the ImageNet1K validation set without further training. Results of both settings appear in Table~\ref{tab:ImageNet_pre_retrained}. Networks trained from scratch with pooling layers replaced by SoftPool yield consistent accuracy improvements over the original networks. The same trend is also visible for the pre-trained networks for which the models have been trained with their original pooling methods. We now discuss the results per CNN architecture family. \textbf{ResNet} \cite{he2016deep}. By training from scratch with SoftPool, an average top-1 accuracy improvement of 1.17\% is observed with a maximum of 1.51\% on ResNet18. When replacing pooling layers on pre-trained networks, we obtain an average of +0.59\% accuracy. All ResNet-based models only include a single pooling operation after the first convolution. Thus, results are based on a single layer replacement which emphasizes the merits of using SoftPool. \begin{table}[t] \centering \resizebox{\linewidth}{!}{% \begin{tabular}{l|c|cc} \hline Model & pooling replacement & statistic ($\chi ^{2}$) & p-value ($\rho$)\\[.2em] \hline ResNet18 & \multirow{5}{*}{Max $\rightarrow$ SoftPool} & $90.08$ & $2.28e^{-21}$ \\[.15em] ResNet34 & & $15.04$ & $1.05e^{-4}$ \\[.15em] ResNet50 & & $61.80$ & $3.80e^{-15}$ \\[.15em] ResNet101 & & $23.13$ & $1.51e^{-6}$ \\[.15em] ResNet152 & & $50.29$ & $1.32e^{-12}$ \\[.15em] \hline DenseNet121 & \multirow{3}{*}{Avg+Max $\rightarrow$ SoftPool} & $411.02$ & $2.19^{-91}$\\[.15em] DenseNet161 & & $46.52$ & $9.06e^{-12}$ \\[.15em] DenseNet169 & & $27.32$ & $1.72e^{-7}$ \\[.15em] \hline ResNeXt50 32x4d & \multirow{2}{*}{Max $\rightarrow$ SoftPool} & $45.13$ & $1.85e^{-11}$ \\[.15em] ResNeXt101 32x8d & & $695.87$ & $2.36e^{-53}$ \\[.15em] \hline wide-ResNet50 & Max $\rightarrow$ SoftPool & $39.41$ & $3.43e^{-10}$ \\[.15em] \hline InceptionV1 & \multirow{2}{*}{Max $\rightarrow$ SoftPool} & $106.41$ & $5.98e^{-25}$ \\[.15em] InceptionV3 & & $80.19$ & $3.39e^{-19}$ \\[.15em] \end{tabular} } \caption{\textbf{McNemar's} \cite{edwards1948note,mcnemar1947note} \textbf{statistical significance for pooling substitution results correlation}. The top-1 accuracies on ImageNet1K val set from Tables~\ref{tab:ImageNet_pre_retrained}, \ref{tab:pooling_imagenet_tests} and \ref{tab:inception_tests_progressive} are used. A detailed view of the statistics is presented in \textsection \textcolor{red}{6} in the Supplementary Material.} \label{tab:mcnemar_stat_sign} \vspace{-0.5em} \end{table} \textbf{DenseNet} \cite{huang2017densely}. Based on the DenseNet overall architecture that incorporates five pooling operations, we replace the max pooling operation that follows after the first layer and average pooling layers between Dense blocks with our proposed method. Top-1 accuracy gains are in the 0.93--1.23\% range when training from scratch and 0.47--0.57\% with substitution on pre-trained networks. The top-5 accuracy follows similar incremental trends. The largest increment in both settings is observed for DenseNet121. \textbf{ResNeXt} \cite{xie2017aggregated}. Average of 0.83\% top-1 accuracy improvement when trained from scratch. The best model, ResNeXt101 32x8d, achieves 80.12\% top-1 accuracy (+0.81\%) and 94.88\% top-5 accuracy (+0.60\%) with SoftPool. On the pre-trained settings, we note average improvements of +0.59\% on top-1 and +0.36\% top-5 accuracies. We again note these accuracies come by a replacement of their only pooling operation after the first convolution layer and without additional training. \textbf{Wide-Resnet-50} \cite{zagoruyko2016wide}. We observe top-1 and top-5 accuracy increases of 1.01\% and 0.76\% when trained from scratch with SoftPool. The initialized network also achieves improvements with +0.63\% top-1 and +0.42\% top-5. \begin{table}[t] \centering \resizebox{\linewidth}{!}{% \begin{tabular}{lccccccc} \hline \multirow{2}{*}{Pooling} & \multicolumn{7}{c}{Networks} \\[0.2em]\cline{2-8} \rule{0pt}{50pt} & \rotatebox{35}{\parbox{2mm}{ResNet18\;\cite{he2016deep}}} & \rotatebox{35}{\parbox{2mm}{ResNet34\;\cite{he2016deep}}} & \rotatebox{35}{\parbox{2mm}{ResNet50\;\cite{he2016deep}}} & \rotatebox{35}{\parbox{2mm}{ResNeXt50\;\cite{xie2017aggregated}}} & \rotatebox{35}{\parbox{2mm}{DenseNet121\;\cite{huang2017densely}}} & \rotatebox{35}{\parbox{2mm}{InceptionV1\;\cite{szegedy2015going}}} & \\[0.2em]\cline{1-7} \multirow{2}{*}{Original} & (Max) & (Max) & (Max) & (Max) & (Avg+Max) & (Max) & \\[0.1em] & 69.76 & 73.30 & 76.15 & 77.62 & 74.65 & 69.78 & \\[0.2em]\cline{1-7} Stochastic \cite{zeiler2013stochastic} & 70.13 & 73.34 & 76.11 & 77.71 & 74.84 & 70.14 & \\[0.1em] S3 \cite{zhai2017s3pool} & 70.15 & 73.56 & 76.24 & 77.82 & 74.85 & 70.17 & \\[0.2em]\cline{1-7} $L_{p}$ \cite{lee2016generalizing} & 70.45 & 73.74 & 76.56 & 77.86 & 74.93 & 70.32 & \\[0.1em] Gate \cite{gulcehre2014learned} & 70.74 & 73.68 & 76.75 & 77.98 & 74.88 & 70.52 & \\[0.1em] DPP \cite{saeedan2018detail} & 70.86 & 74.25 & 77.09 & 78.20 & 75.37 & 70.95 & \\[0.1em] LIP \cite{gao2019lip} & 70.83 & 73.95 & 77.13 & 78.14 & 75.31 & 70.77 & \\[0.2em]\cline{1-7} SoftPool \textbf{(ours)} & \textbf{71.27} & \textbf{74.67} & \textbf{77.35} & \textbf{78.48} & \textbf{75.88} & \textbf{71.43} & \:\:\:\:\:\:\: \\ \end{tabular} } \caption{\textbf{Pooling layer substitution} top-1 accuracy for a variety of pooling methods. Experiments were performed on Imagenet1K.} \label{tab:pooling_imagenet_tests} \vspace{-1.2em} \end{table} \begin{table}[t] \centering \resizebox{\linewidth}{!}{% \begin{tabular}{lcccccccc} \hline \multirow{2}{*}{Layer} & \multicolumn{8}{c}{Pooling layer substitution with SoftPool} \\\cline{2-9} & N & I & II & III & IV & V & VI & VII\\ \hline $pool_{1}$ & & \checkmark & \checkmark & \checkmark & \checkmark & \checkmark & \checkmark & \checkmark \\ $pool_{2}$ & & & \checkmark & \checkmark & \checkmark & \checkmark & \checkmark & \checkmark \\ $mixed \; 5_{b-d}$ & & & & \checkmark & \checkmark & \checkmark & \checkmark & \checkmark \\ $mixed \; 6_{a}$ & & & & & \checkmark & \checkmark & \checkmark & \checkmark \\ $mixed \; 6_{b-e}$ & & & & & & \checkmark & \checkmark & \checkmark \\ $mixed \; 7_{a}$ & & & & & & & \checkmark & \checkmark \\ $mixed \; 7_{b-d}$ & & & & & & & & \checkmark \\ \hline Top-1 (\%) & 77.45 & 77.93 & 78.14 & 78.37 & 78.42 & 78.65 & 78.83 & \textbf{79.04} \\ Top-5 (\%) & 93.56 & 93.61 & 93.68 & 93.74 & 93.78 & 93.84 & 93.90 & \textbf{93.98} \\ \end{tabular} } \caption{\textbf{Progressive layer substitution for InceptionV3}. Experiments are performed on ImageNet1K. Column numbers refer to the number of replaced pooling layers, marked with \checkmark.} \label{tab:inception_tests_progressive} \vspace{-1.2em} \end{table} \begin{table*}[t] \begin{threeparttable}[t] \centering \resizebox{\textwidth}{!}{% \begin{tabular}{lccccccc} \hline \multirow{2}{*}{Model} & \multirow{2}{*}{GFLOPs} & \multicolumn{2}{c}{HACS} & \multicolumn{2}{c}{Kinetics-700} & \multicolumn{2}{c}{UCF-101} \\ & & top-1(\%) & top-5(\%) & top-1(\%) & top-5(\%) & top-1(\%) & top-5(\%) \\ \hline r3d-50 \cite{kataoka2020would}$^{**}$ & 53.16 & 78.36 & 93.76 & 49.08 & 72.54 & 93.13 & 96.29 \\ r3d-101 \cite{kataoka2020would}$^{**}$ & 78.52 & 80.49 & 95.18 & 52.58 & 74.63 & 95.76 & 98.42 \\ r(2+1)d-50 \cite{tran2018closer}$^{**}$ & 50.04 & 81.34 & 94.51 & 49.93 & 73.40 & 93.92 & 97.84 \\ I3D \cite{carreira2017quo}$^{\ddagger *}$ & 55.27 & 79.95 & 94.48 & 53.01 & 69.19 & 92.45 & 97.62 \\ ir-CSN-101 \cite{tran2019video}$^{\ddagger \dagger}$ & 17.26 & N/A & N/A & 54.66 & 73.78 & 95.13 & 97.85 \\ MF-Net \cite{chen2018multifiber}$^{\dagger *}$ & 22.50 & 78.31 & 94.62 & 54.25 & 73.38 & 93.86 & 98.37 \\ SlowFast r3d-50 \cite{feichtenhofer2019slowfast}$^{\ddagger \dagger}$ & 36.71 & N/A & N/A & 56.17 & 75.57 & 94.62 & 98.75 \\ SRTG r3d-50 \cite{stergiou2021learn}$^{\dagger \dagger}$ & 53.22 & 80.36 & 95.55 & 53.52 & 74.17 & 96.85 & 98.26 \\ SRTG r(2+1)d-50 \cite{stergiou2021learn}$^{\dagger \dagger}$ & 50.10 & 83.77 & 96.56 & 54.17 & 74.62 & 95.99 & 98.20 \\ SRTG r3d-101 \cite{stergiou2021learn}$^{\dagger \dagger}$ & 78.66 & 81.66 & 96.37 & 56.46 & 76.82 & 97.32 & 99.56 \\ \hline r3d-50 with SoftPool (Ours) & 53.16 & 79.82 & 94.64 & 50.36 & 73.72 & 93.90 & 97.02 \\ SRTG r(2+1)d-50 with SoftPool (Ours) & 50.10 & \textbf{84.78} & \textbf{97.72} & 55.27 & 75.44 & 96.46 & 98.73 \\ SRTG r3d-101 with SoftPool (Ours) & 78.66 & 83.28 & 97.04 & \textbf{57.76} & \textbf{77.84} & \textbf{98.06} & \textbf{99.82} \\ \hline \end{tabular}% } \begin{tablenotes} \item[$**$] re-implemented models trained from scratch. $\dagger \dagger$ models and weights from official repositories. $\ddagger *$ unofficial models trained from scratch. \item[$\ddagger \dagger$] models from unofficial repositories with official weights. $\dagger *$ official models trained from scratch. \end{tablenotes} \end{threeparttable}% \vspace{0.8mm} \caption{\textbf{Action recognition top-1 and top-5 accuracy for HACS, Kinetics-700 and UCF-101}. Models are trained on HACS and fine-tuned for Kinetics-700 and UCF-101, except for ir-CSN-101 and SlowFast r3d-50 (see text). N/A means no trained model was provided. \label{table:video_accuracies} } \vspace{-1.3em} \end{table*} These combined experiments demonstrate that by replacing a single pooling layer (ResNet, ResNeXt and Wide-ResNet) or only five pooling layers (DenseNet) with SoftPool operations leads to a modest but important increase in accuracy. To understand whether these improvements are statistically significant, we performed a McNemar's test \cite{edwards1948note,mcnemar1947note} to calculate the probabilities ($\rho$) of marginal homogeneity between the original and the SoftPool-replaced networks. The results are summarized in Table~\ref{tab:mcnemar_stat_sign} for the models obtained in the \textit{from scratch} setting. As shown for all networks, $\rho \! \ll \! 0.01$ which corresponds to confidence $\gg \! 99\%$ that the improved results are indeed due to the different pooling operations. \textbf{Memory and computation requirements}. We also summarize the number of parameters and GLOPs in Table~\ref{tab:ImageNet_pre_retrained}. SoftPool does not include trainable variables and thus does not affect the number of parameters, in contrast to recent pooling methods \cite{gao2019lip,gulcehre2014learned,kobayashi2019global,saeedan2018detail}. We also depart from these methods as the number of GFLOPs remains the same as the maximum and average pooling that we replace. \textbf{Pooling method comparisons}. In Table~\ref{tab:pooling_imagenet_tests}, we compare multiple pooling methods across six networks. All networks were trained from scratch. SoftPool performs similarly to learnable approaches without requiring additional convolutions, while outperforming stochastic methods. These classification accuracies correlate with image similarities in Table~\ref{tab:times_ssim_psnr}. This enforces the notion that pooling methods that retain information will also improve classification accuracy. \subsection{Multi-layer ablation study} \label{sec:experiments::multi-layer} In order to better understand how SoftPool affects the network performance at different depths, we use an InceptionV3 model \cite{szegedy2016rethinking} which integrates pooling in its layer structure. We systematically replace the max-pool operations within Inception blocks at different network layers. From the top-1 and top-5 results summarized in Table~\ref{tab:inception_tests_progressive}, we observe that the accuracy increases with the number of pooling layers that are replaced with SoftPool. An average increase of 0.23\% in top-1 accuracy is obtained with single layer replacements. The final top-1 accuracy surge between the original network with max-pool (N) and the SoftPool model (VII) is +1.59\%. This shows that SoftPool can be used as direct replacement regardless of the network depth. \subsection{Classification performance on video data} \label{sec:experiments::video} Finally, we demonstrate the merits of SoftPool in handling spatio-temporal data. Specifically, we address action recognition in videos where the input to the network is a stack of subsequent video frames. Representing time-based features stands as a major challenge in action recognition research \cite{stergiou2019analyzing}. The main challenge in space-time data downsampling is the inclusion of key temporal information without impacting the spatial quality of the input. In this experiment, we use popular time-inclusive networks and replace the original pooling methods with SoftPool. Most space-time networks extend 2D convolutions to 3D to account for the temporal dimension. They use stacks of frames as inputs. For the tested networks with SoftPool, the only modification is that we use SoftPool to deal with the additional input dimension (see Section~\ref{sec:methodology::spacetime}). We trained most architectures from scratch on HACS \cite{zhao2019hacs} using the implementations provided by the authors. Results for Kinetics-700 and UCF-101 are fine-tuned from the HACS-trained models. We make exceptions for ir-CSN-101 and SlowFast, for which we used the networks trained for Kinetics-700 that were provided by the authors. ir-CSN-101 \cite{tran2019video} is pre-trained on IG65M \cite{ghadiyaram2019large}, a large dataset consisting of 65M video that is not publicly available. SlowFast \cite{feichtenhofer2019slowfast} is pre-trained on the full ImageNet dataset. Results appear in Table~\ref{table:video_accuracies}. For three architectures, we report the performance on both the vanilla models and their counterparts with all pooling operations replaced by SoftPool. For r3d-50, a ResNet with 3D convolutions, using SoftPool increases the top-1 classification accuracy by 1.46\%. The accuracy performance also increases with 1.00\% and 1.63\% for the two SRTG models \cite{stergiou2021learn}. For the SRTG model with ResNet-(2+1) backbone, we achieve state-of-the-art performance on HACS. Also when using spatio-temporal data, SoftPool does not add computational complexity (GFLOPS), as demonstrated in Table~\ref{table:video_accuracies}. For the performance on Kinetics-700, we observe important performance gains. An average of 1.22\% increase in top-1 accuracy is shown for the three models that have their pooling operations substituted by SoftPool. The best performing model is SRTG r3d-101 with SoftPool, which achieves a top-1 accuracy of 57.76\% and a top-5 accuracy score 77.84\%. These models also outperform state-of-the-art models such as SlowFast r3d-50 and ir-CSN-101. When fine-tuning on UCF-101, the average accuracy gain is 0.66\% despite an almost saturated performance. SRTG r3d-101 with SoftPool is the best performing model with a top-1 accuracy of 98.06\% and top-5 of 99.82\%. \section{Conclusions} \label{sec:conclusions} We have introduced SoftPool, a novel pooling method that can better preserve informative features and, consequently, improves classification performance in CNNs. SoftPool uses the softmax of inputs within a kernel region where each of the activations has a proportional effect on the output. Activation gradients are relative to the weights assigned to them. Our operation is differentiable, which benefits efficient training. SoftPool does not require additional parameters nor increases the number of performed operations. We have shown the merits of the proposed approach through experimentation on image similarity tasks as well as on the classification of image and video datasets. We believe that the increase in classification performance combined with the low computation and memory requirements make SoftPool an excellent replacement for current pooling operations, including max and average pooling. {\small \bibliographystyle{ieee_fullname}
{'timestamp': '2021-03-19T01:15:50', 'yymm': '2101', 'arxiv_id': '2101.00440', 'language': 'en', 'url': 'https://arxiv.org/abs/2101.00440'}
arxiv
\section{Introduction} Many Question-Answering (QA) datasets including Natural Questions (NQ) \citep{kwiatkowski-etal-2019-natural} and SQuAD 2.0 \citep{rajpurkar-etal-2018-know} contain questions that are \textit{unanswerable}. While unanswerable questions constitute a large part of existing QA datasets (e.g., 51\% of NQ, 36\% of SQuAD 2.0), their treatment remains primitive. That is, (closed-book) QA systems label these questions as \textit{Unanswerable} without detailing why, as in \ref{answerable-vs-unanswerable}: \ex. \label{answerable-vs-unanswerable} \a. \textbf{Answerable Q:} Who is the current monarch of the UK? \\ System: Elizabeth II. \b. \label{answerable-vs-unanswerable-b} \textbf{Unanswerable Q:} Who is the current monarch of France? \\ System: Unanswerable. Unanswerability in QA arises due to a multitude of reasons including retrieval failure and malformed questions \citep{kwiatkowski-etal-2019-natural}. We focus on a subset of unanswerable questions---namely, questions containing failed \textit{presuppositions} (background assumptions that need to be satisfied). \begin{figure*}[t] \centering \includegraphics[width=1\textwidth]{figs/presups_diagram.pdf} \caption{A comparison of existing closed-book QA pipelines (left) and the proposed QA pipeline in this work (right). The gray part of the pipeline is only manually applied in this work to conduct headroom analysis.} \label{fig:presups-diagram} \end{figure*} Questions containing failed presuppositions do not receive satisfactory treatment in current QA. Under a setup that allows for \textit{Unanswerable} as an answer (as in several closed-book QA systems; Figure~\ref{fig:presups-diagram}, left), the best case scenario is that the system correctly identifies that a question is unanswerable and gives a generic, unsatisfactory response as in \ref{answerable-vs-unanswerable-b}. Under a setup that does not allow for \textit{Unanswerable} (e.g., open-domain QA), a system's attempt to answer these questions results in an inaccurate accommodation of false presuppositions. For example, Google answers the question \textit{Which linguist invented the lightbulb?} with \textit{Thomas Edison}, and Bing answers the question \textit{When did Marie Curie discover Uranium?} with \textit{1896} (retrieved Jan 2021). These answers are clearly inappropriate, because answering these questions with \textit{any} name or year endorses the false presuppositions \textit{Some linguist invented the lightbulb} and \textit{Marie Curie discovered Uranium}. Failures of this kind are extremely noticeable and have recently been highlighted by social media \citep{munroe2020}, showing an outsized importance regardless of their effect on benchmark metrics. We propose a system that takes presuppositions into consideration through the following steps (Figure~\ref{fig:presups-diagram}, right): \begin{enumerate} \itemsep -2pt \item \textbf{Presupposition generation:} \textit{Which linguist invented the lightbulb?} $\rightarrow$ \textit{Some linguist invented the lightbulb.} \item \textbf{Presupposition verification:} \textit{Some linguist invented the lightbulb.} $\rightarrow$ Not verifiable \item \textbf{Explanation generation:} (\textit{Some linguist invented the lightbulb}, Not verifiable) $\rightarrow$ \textit{This question is unanswerable because there is insufficient evidence that any linguist invented the lightbulb.} \end{enumerate} \begin{table*}[t] \centering \resizebox{2.08\columnwidth}{!}{ \begin{tabular}{llll} \toprule Cause of unanswerability & \% & Example Q & Comment \\\midrule Unverifiable presupposition & 30\% & \textit{what is the stock symbol for mars candy} & Presupposition \textit{`stock symbol for mars candy exists'} fails \\ \midrule Reference resolution failure & 9\% & \textit{what kind of vw jetta do i have} & The system does not know who `i' is \\ Retrieval failure & 6\% & \textit{when did the salvation army come to australia} & Page retrieved was \textit{Safe Schools Coalition Australia} \\ Subjectivity & 3\% & \textit{what is the perfect height for a model} & Requires subjective judgment \\ Commonsensical & 3\% & \textit{where does how to make an american quilt take place} & Document contains no evidence that the movie took place \\ & & & somewhere, but it is commonsensical that it did \\\midrule Actually answerable & 8\% & \textit{when do other cultures celebrate the new year} & The question was actually answerable given the document\\ Not a question/Malformed question & 3\% & \textit{where do you go my lovely full version} & Not an actual question\\ \bottomrule \end{tabular} } \caption{Example causes of unanswerability in NQ. \% denotes the percentage of questions that both annotators agreed to be in the respective cause categories.} \label{table:unanswerableq-analysis} \end{table*} \noindent Our contribution can be summarized as follows: \begin{itemize} \itemsep -1pt \item We identify a subset of unanswerable questions---questions with failed presuppositions---that are not handled well by existing QA systems, and quantify their role in naturally occurring questions through an analysis of the NQ dataset (S\ref{sec:presups}, S\ref{sec:unanswerability-analysis}). \item We outline how a better QA system could handle questions with failed presuppositions, and validate that the oracle behavior of this proposed system is more satisfactory to users than the oracle behavior of existing systems through a user preference study (S\ref{sec:user-study}). \item We propose a novel framework for handling presuppositions in QA, breaking down the problem into three parts (see steps above), and evaluate progress on each (S\ref{sec:approach}). We then integrate these steps end-to-end into a competitive QA model and achieve modest gains (S\ref{sec:e2e}). \end{itemize} \section{Presuppositions} \label{sec:presups} Presuppositions are implicit assumptions of utterances that interlocutors take for granted. For example, if I uttered the sentence \textit{I love my hedgehog}, it is assumed that I, the speaker, do in fact own a hedgehog. If I do not own one (hence the presupposition fails), uttering this sentence would be inappropriate. Questions may also be inappropriate in the same way when they contain failed presuppositions, as in the question \textit{Which linguist invented the lightbulb?}. Presuppositions are often associated with specific words or syntactic constructions (`triggers'). We compiled an initial list of presupposition triggers based on \citeauthor{levinson_1983} (\citeyear{levinson_1983}: 181--184) and \citet{van1992presupposition},\footnote{We note that it is a simplifying view to treat all triggers under the banner of presupposition; see \citet{karttunen2016presupposition}.} and selected the following triggers based on their frequency in NQ (>> means `presupposes'): \begin{itemize} \itemsep -2pt \item Question words (\textit{what, where, who...}): \textit{Who did Jane talk to?} >> \textit{Jane talked to someone.} \item Definite article (\textit{the}): \textit{I saw the cat} >> \textit{There exists some contextually salient, unique cat.} \item Factive verbs (\textit{discover, find out, prove...}): \textit{I found out that Emma lied.} >> \textit{Emma lied}. \item Possessive \textit{'s}: \textit{She likes Fred's sister.} >> \textit{Fred has a sister.} \item Temporal adjuncts (\textit{when, during, while...}): \textit{I was walking when the murderer escaped from prison.} >> \textit{The murderer escaped from prison.} \item Counterfactuals (\textit{if} + past): \textit{I would have been happier if I had a dog.} >> \textit{I don't have a dog.} \end{itemize} \noindent Our work focuses on presuppositions of questions. We assume presuppositions \textit{project} from \textit{wh}-questions---that is, presuppositions (other than the presupposition introduced by the interrogative form) remain constant under \textit{wh}-questions as they do under negation (e.g., \textit{I don't like my sister} has the same possessive presupposition as \textit{I like my sister}). However, the projection problem is complex; for instance, when embedded under other operators, presuppositions can be overtly denied (\citeauthor{levinson_1983} \citeyear{levinson_1983}: 194). See also \citet{schlenker2008presupposition}, \citet{abrusan2011presuppositional}, \citet{schwarz2018decomposing}, \citet{theiler2020epistemic}, \textit{i.a.,} for discussions regarding projection patterns under \textit{wh}-questions. We adopt the view of \citet{strawson1950referring} that definite descriptions presuppose both existence and (contextual) uniqueness, but this view is under debate. See \citet{coppock2012weak}, for instance, for an analysis of \textit{the} that does not presuppose existence and presupposes a weaker version of uniqueness. Furthermore, we currently do not distinguish predicative and argumental definites. \paragraph{Presuppositions and unanswerability.} Questions containing failed presuppositions are often treated as unanswerable in QA datasets. An example is the question \textit{What is the stock symbol for Mars candy?} from NQ. This question is not answerable with any description of a stock symbol (that is, an answer to the \textit{what} question), because Mars is not a publicly traded company and thus does not have a stock symbol. A better response would be to point out the presupposition failure, as in \textit{There is no stock symbol for Mars candy}. However, statements about negative factuality are rarely explicitly stated, possibly due to reporting bias \citep{gordon2013reporting}. Therefore, under an extractive QA setup as in NQ where the answers are spans from an answer source (e.g., a Wikipedia article), it is likely that such questions will be unanswerable. Our proposal is based on the observation that the denial of a failed presupposition ($\neg$P) can be used to explain the unanswerability of questions (Q) containing failed presuppositions (P), as in \ref{ex:neg-presup}. \ex. \label{ex:neg-presup} \textbf{Q: }Who is the current monarch of France?\\ \textbf{P:} There is a current monarch of France.\\ \textbf{$\neg$P:} There is no such thing as a current monarch of France. An answer that refers to the presupposition, such as $\neg$P, would be more informative compared to both \textit{Unanswerable} \ref{answerable-vs-unanswerable-b} and an extractive answer from documents that are topically relevant but do not mention the false presupposition. \section{Analysis of Unanswerable Questions} \label{sec:unanswerability-analysis} \begin{table*}[t] \centering \resizebox{1.7\columnwidth}{!}{ \begin{tabular}{ll} \toprule \multicolumn{2}{c}{Question: \textit{where can i buy a japanese dwarf flying squirrel}} \\\midrule\midrule Simple unanswerable & \textit{This question is unanswerable.} \\\midrule Presupposition failure-based & \makecell[l]{\textit{This question is unanswerable because we could not verify that you can}\\ \textit{buy a Japanese Dwarf Flying Squirrel anywhere.}} \\\midrule Extractive explanation & \makecell[l]{\textit{This question is unanswerable because it grows to a length of 20 cm (8 in)}\\ \textit{and has a membrane connecting its wrists and ankles which enables it to}\\\textit{glide from tree to tree.}} \\\midrule DPR rewrite & \makecell[l]{\textit{After it was returned for the second time, the original owner, referring to} \\ \textit{it as ``the prodigal gnome", said she had decided to keep it and would} \\ \textit{ not sell it on Ebay again.}} \\ \bottomrule \end{tabular} } \caption{Systems (answer types) compared in the user preference study and examples.} \label{table:answer-types} \end{table*} \begin{figure*}[t] \centering \includegraphics[width=1\textwidth]{figs/cc-comparisons.pdf} \caption{Results of the user preference study. Chart labels denote the two systems being compared (S1 vs. S2). } \label{fig:sxs-results} \end{figure*} First, to quantify the role of presupposition failure in QA, two of the authors analyzed 100 randomly selected unanswerable $wh$-questions in the NQ development set.\footnote{The NQ development set provides 5 answer annotations per question---we only looked at questions with 5/5 Null answers here.} The annotators labeled each question as \textit{presupposition failure} or \textit{not presupposition failure}, depending on whether its unanswerability could be explained by the presence of an unverifiable presupposition with respect to the associated document. If the unanswerability could not be explained in terms of presupposition failure, the annotators provided a reasoning. The Cohen's $\kappa$ for inter-annotator agreement was 0.586. We found that 30\% of the analyzed questions could be explained by the presence of an unverifiable presupposition in the question, considering only the cases where both annotators were in agreement (see Table~\ref{table:unanswerableq-analysis}).\footnote{$wh$-questions constitute $\sim$69\% of the NQ development set, so we expect the actual portion of questions with presupposition failiure-based explanation to be $\sim$21\%.} After adjudicating the reasoning about unanswerability for the non-presupposition failure cases, another 21\% fell into cases where presupposition failure could be partially informative (see Table~\ref{table:unanswerableq-analysis} and Appendix~\ref{app:partially-useful-failures} for details). The unverifiable presuppositions were triggered by question words (19/30), the definite article \textit{the} (10/30), and a factive verb (1/30). \section{User Study with Oracle Explanation} \label{sec:user-study} Our hypothesis is that statements explicitly referring to failed presuppositions can better\footnote{We define \textit{better} as user preference in this study, but other dimensions could also be considered such as trustworthiness.} speak to the unanswerability of corresponding questions. To test our hypothesis, we conducted a side-by-side comparison of the oracle output of our proposed system and the oracle output of existing (closed-book) QA systems for unanswerable questions. We included two additional systems for comparison; the four system outputs compared are described below (see Table~\ref{table:answer-types} for examples): \begin{table*}[t] \centering \resizebox{2.07\columnwidth}{!}{ \begin{tabular}{llll} \toprule Question (input) & Template & Presupposition (output) \\\midrule \textit{\underline{which} philosopher advocated the idea of return to nature} & some \_\_ & some \textit{philosopher advocated the idea of return to nature}\\ \textit{when was it \underline{discovered} that the sun rotates} & \_\_ & \textit{the sun rotates} \\ \textit{when is \underline{the} year of the cat in chinese zodiac} & \_\_ exists & \textit{`year of the cat in chinese zodiac'} exists \\ \textit{when is \underline{the} year of the cat in chinese zodiac} & \_\_ is contextually unique & \textit{`year of the cat in chinese zodiac'} is contextually unique \\ \textit{what do the colors on ecuador\underline{'s} flag mean} & \_\_ has \_\_ & \textit{`ecuador'} has \textit{`flag'} \\ \bottomrule \end{tabular} } \caption{Example input-output pairs of our presupposition generator. Text in italics denotes the part taken from the original question, and the plain text is the part from the generation template. All questions are taken from NQ.} \label{table:generator-examples} \end{table*} \begin{itemize} \itemsep -2pt \item \textbf{Simple unanswerable:} A simple assertion that the question is unanswerable (i.e., \textit{This question is unanswerable}). This is the oracle behavior of closed-book QA systems that allow \textit{Unanswerable} as an answer. \item \textbf{Presupposition failure-based explanation:} A denial of the presupposition that is unverifiable from the answer source. This takes the form of either \textit{This question is unanswerable because we could not verify that...} or \textit{...because it is unclear that...} depending on the type of the failed presupposition. See Section~\ref{subsec:exp-generation} for more details. \item \textbf{Extractive explanation:} A random sentence from a Wikipedia article that is topically related to the question, prefixed by \textit{This question is unanswerable because....} This system is introduced as a control to ensure that length bias is not in play in the main comparison (e.g., users may \textit{a priori} prefer longer, topically-related answers over short answers). That is, since our system, \textbf{Presupposition failure-based explanation}, yields strictly longer answers than \textbf{Simple unanswerable}, we want to ensure that our system is not preferred merely due to length rather than answer quality. \item \textbf{Open-domain rewrite:} A rewrite of the non-oracle output taken from the demo\footnote{\url{http://qa.cs.washington.edu:2020/}} of Dense Passage Retrieval (DPR; \citealt{karpukhin2020dense}), a competitive open-domain QA system. This system is introduced to test whether presupposition failure can be easily addressed by expanding the answer source, since a single Wikipedia article was used to determine presupposition failure. If presupposition failure is a problem particular only to closed-book systems, a competitive open-domain system would suffice to address this issue. While the outputs compared are not oracle, this system has an advantage of being able to refer to all of Wikipedia. The raw output was rewritten to be well-formed, so that it was not unfairly disadvantaged (see Appendix~\ref{app:dpr-rewrite}). \end{itemize} \paragraph{Study.} We conducted a side-by-side study with 100 unanswerable questions. These questions were unanswerable questions due to presupposition failure, as judged independently and with high confidence by two authors.\footnote{Hence, this set did not necessarily overlap with the randomly selected unanswerable questions from Section~\ref{sec:unanswerability-analysis}; we wanted to specifically find a set of questions that were representative of the phenomena we address in this work.} We presented an exhaustive binary comparison of four different types of answers for each question (six binary comparisons per question). We recruited five participants on an internal crowdsourcing platform at Google, who were presented with all binary comparisons for all questions. All comparisons were presented in random order, and the sides that the comparisons appeared in were chosen at random. For each comparison, the raters were provided with an unanswerable question, and were asked to choose the system that yielded the answer they preferred (either \textit{System 1} or \textit{2}). They were also given the options \textit{Both answers are good/bad}. See Appendix~\ref{app:sxs-task} for additional details about the task setup. \paragraph{Results.} Figure~\ref{fig:sxs-results} shows the user preferences for the six binary comparisons, where blue and gray denote preferences for the two systems compared. We find that presupposition-based answers are preferred against all three answer types with which they were compared, and prominently so when compared to the oracle behavior of existing closed-book QA systems (4th chart, Presup. vs. No Explanation). This supports our hypothesis that presupposition failure-based answers would be more satisfactory to the users, and suggests that building a QA system that approaches the oracle behavior of our proposed system is a worthwhile pursuit. \section{Model Components} \label{sec:approach} Given that presupposition failure accounts for a substantial proportion of unanswerable questions (Section~\ref{sec:unanswerability-analysis}) and our proposed form of explanations is useful (Section~\ref{sec:user-study}), how can we build a QA system that offers such explanations? We decompose this task into three smaller sub-tasks: presupposition generation, presupposition verification, and explanation generation. Then, we present progress towards each subproblem using NQ.\footnote{Code and data will be available at\\\url{https://github.com/google-research/google-research/presup-qa}} We use a templatic approach for the first and last steps. The second step involves verification of the generated presuppositions of the question against an answer source, for which we test four different strategies: zero-shot transfer from Natural Language Inference (NLI), an NLI model finetuned on verification, zero-shot transfer from fact verification, and a rule-based/NLI hybrid model. Since we used NQ, our models assume a closed-book setup with a single document as the source of verification. \subsection{Step 1: Presupposition Generation} \label{subsec:presup-generation} \paragraph{Linguistic triggers.} \noindent Using the linguistic triggers discussed in Section~\ref{sec:presups}, we implemented a rule-based generator to templatically generate presuppositions from questions. See Table~\ref{table:generator-examples} for examples, and Appendix~\ref{app:generator-template} for a full list. \paragraph{Generation.} The generator takes as input a constituency parse tree of a question string from the Berkeley Parser \citep{petrov-etal-2006-learning} and applies trigger-specific transformations to generate the presupposition string (e.g., taking the sentential complement of a factive verb). If there are multiple triggers in a single question, all presuppositions corresponding to the triggers are generated. Thus, a single question may have multiple presuppositions. See Table~\ref{table:generator-examples} for examples of input questions and output presuppositions. \paragraph{How good is our generation?} We analyzed 53 questions and 162 generated presuppositions to estimate the quality of our generated presuppositions. This set of questions contained at least 10 instances of presuppositions pertaining to each category. One of the authors manually validated the generated presuppositions. According to this analysis, 82.7\% (134/162) presuppositions were valid presuppositions of the question. The remaining cases fell into two broad categories of error: ungrammatical (11\%, 18/162) or grammatical but not presupposed by the question (6.2\%, 10/162). The latter category of errors is a limitation of our rule-based generator that does not take semantics into account, and suggests an avenue by which future work can yield improvements. For instance, we uniformly apply the template \textit{`A'} has \textit{`B'}\footnote{We used a template that puts possessor and possessee NPs in quotes instead of using different templates depending on posessor/possessee plurality (e.g., \textit{A \_\_ has a \_\_}/\textit{A \_\_ has \_\_}/\textit{\_\_ have a \_\_}/\textit{\_\_ have \_\_}).} for presuppositions triggered by \textit{'s}. While this template works well for cases such as \textit{Elsa's sister} >> \textit{`Elsa' has `sister'}, it generates invalid presuppositions such as \textit{Bachelor's degree} >> \#\textit{`Bachelor' has `degree'}. Finally, the projection problem is another limitation. For example, \textit{who does pip believe is estella's mother} has an embedded possessive under a nonfactive verb \textit{believe}, but our generator would nevertheless generate \textit{`estella' has `mother'}. \begin{table*}[t] \centering \resizebox{2\columnwidth}{!}{ \begin{tabular}{lll} \toprule Model & Macro F1 & Acc. \\\midrule\midrule Majority class & 0.44 & 0.78 \\\midrule Zero-shot NLI (ALBERT MNLI + Wiki sentences) & 0.50 & 0.51 \\ Zero-shot NLI (ALBERT QNLI + Wiki sentences) & 0.55 & 0.73 \\ Zero-shot FEVER (KGAT + Wiki sentences) & 0.54 & 0.66 \\ Finer-tuned NLI (ALBERT QNLI + Wiki sentences) & 0.58 & 0.76 \\\midrule Rule-based/NLI hybrid (ALBERT QNLI + Wiki presuppositions) & 0.58 & 0.71 \\ Rule-based/NLI hybrid (ALBERT QNLI + Wiki sentences + Wiki presuppositions) & 0.59 & 0.77 \\ Finer-tuned, rule-based/NLI hybrid (ALBERT QNLI + Wiki sentences + Wiki presuppositions) & \textbf{0.60} & \textbf{0.79} \\ \bottomrule \end{tabular} } \caption{Performance of verification models tested. Models marked with `Wiki sentence' use sentences from Wikipedia articles as premises, and `Wiki presuppositions', generated presuppositions from Wikipedia sentences.} \label{table:verification-results} \end{table*} \subsection{Step 2: Presupposition Verification} The next step is to verify whether presuppositions of a given question is verifiable from the answer source. The presuppositions were first generated using the generator described in Section~\ref{subsec:presup-generation}, and then manually repaired to create a verification dataset with gold presuppositions. This was to ensure that verification performance is estimated without a propagation of error from the previous step. Generator outputs that were not presupposed by the questions were excluded. To obtain the verification labels, two of the authors annotated 462 presuppositions on their binary verifiability (\textit{verifiable/not verifiable}) based on the Wikipedia page linked to each question (the links were provided in NQ). A presupposition was labeled \textit{verifiable} if the page contained any statement that either asserted or implied the content of the presupposition. The Cohen's $\kappa$ for inter-annotator agreement was 0.658. The annotators reconciled the disagreements based on a post-annotation discussion to finalize the labels to be used in the experiments. We divided the annotated presuppositions into development ($n=234$) and test ($n=228$) sets.\footnote{The dev/test set sizes did not exactly match because we kept presuppositions of same question within the same split, and each question had varying numbers of presuppositions.} We describe below four different strategies we tested. \paragraph{Zero-shot NLI.} NLI is a classification task in which a model is given a premise-hypothesis pair and asked to infer whether the hypothesis is entailed by the premise. We formulate presupposition verification as NLI by treating the document as the premise and the presupposition to verify as the hypothesis. Since Wikipedia articles are often larger than the maximum premise length that NLI models can handle, we split the article into sentences and created $n$ premise-hypothesis pairs for an article with $n$ sentences. Then, we aggregated these predictions and labeled the hypothesis (the presupposition) as verifiable if there are at least $k$ sentences from the document that supported the presupposition. If we had a perfect verifier, $k=1$ would suffice to perform verification. We used $k=1$ for our experiments, but $k$ could be treated as a hyperparameter. We used ALBERT-xxlarge \citep{Lan2020ALBERT} finetuned on MNLI \citep{williams-etal-2018-broad} and QNLI \citep{wang2018glue} as our NLI model. \paragraph{Finer-tuned NLI.} Existing NLI datasets such as QNLI contain a broad distribution of entailment pairs. We adapted the model further to the distribution of entailment pairs that are specific to our generated presuppositions (e.g., \textit{Hypothesis: NP is contextually unique}) through additional finetuning (i.e., \textit{finer-tuning}). Through crowdsourcing on an internal platform, we collected entailment labels for 15,929 (presupposition, sentence) pairs, generated from 1000 questions in NQ and 5 sentences sampled randomly from the corresponding Wikipedia pages. We continued training the model fine-tuned on QNLI on this additional dataset to yield a finer-tuned NLI model. Finally, we aggregated per-sentence labels as before to get verifiability labels for (presupposition, document) pairs. \paragraph{Zero-shot FEVER.} FEVER is a fact verification task proposed by \citet{thorne-etal-2018-fever}. We formulate presupposition verification as a fact verification task by treating the Wikipedia article as the evidence source and the presupposition as the claim. While typical FEVER systems have a document retrieval component, we bypass this step and directly perform evidence retrieval on the article linked to the question. We used the Graph Neural Network-based model of \citet{liu-etal-2020-fine} (KGAT) that achieves competitive performance on FEVER. A key difference between KGAT and NLI models is that KGAT can consider pieces of evidence jointly, whereas with NLI, the pieces of evidence are verified independently and aggregated at the end. For presuppositions that require multihop reasoning, KGAT may succeed in cases where aggregated NLI fails---e.g., for uniqueness. That is, if there is no sentence in the document that bears the same uniqueness presupposition, one would need to reason over all sentences in the document. \paragraph{Rule-based/NLI hybrid.} We consider a rule-based approach where we apply the same generation method described in Section~\ref{sec:approach} to the Wikipedia documents to extract the presuppositions of the evidence sentences. The intended effect is to extract content that is directly relevant to the task at hand---that is, we are making the presuppositions of the documents explicit so that they can be more easily compared to presuppositions being verified. However, a na{\"i}ve string match between presuppositions of the document and the questions would not work, due to stylistic differences (e.g., definite descriptions in Wikipedia pages tend to have more modifiers). Hence, we adopted a hybrid approach where the zero-shot QNLI model was used to verify (document presupposition, question presupposition) pairs. \paragraph{Results.} Our results (Table~\ref{table:verification-results}) suggest that presupposition verification is challenging to existing models, partly due to class imbalance. Only the model that combines finer-tuning and rule-based document presuppositions make modest improvement over the majority class baseline (78\% $\rightarrow$ 79\%). Nevertheless, gains in F1 were substantial for all models (44\% $\rightarrow$ 60\% in best model), showing that these strategies do impact verifiability, albeit with headroom for improvement. QNLI provided the most effective zero-shot transfer, possibly because of domain match between our task and the QNLI dataset---they are both based on Wikipedia. The FEVER model was unable to take advantage of multihop reasoning to improve over (Q)NLI, whereas using document presuppositions (Rule-based/NLI hybrid) led to gains over NLI alone. \begin{table*}[t] \centering{ \resizebox{2\columnwidth}{!}{ \begin{tabular}{lccccc} \toprule Model & Average F1 & Long answer F1 & Short answer F1 & Unans. Acc & Unans. F1 \\\midrule ETC (our replication) & 0.645 & 0.742 & 0.548 & 0.695 & 0.694\\ + Presuppositions (flat) & 0.641 & 0.735 & 0.547 & 0.702 & 0.700 \\ + Verification labels (flat) & 0.645 & 0.742 & 0.547 & 0.687 & 0.684\\ + Presups + labels (flat) & 0.643 & \textbf{0.744} & 0.544 & 0.702 & 0.700\\ + Presups + labels (structured) & \textbf{0.649} & 0.743 & \textbf{0.555} & \textbf{0.703} & \textbf{0.700}\\ \bottomrule \end{tabular} }} \caption{Performance on NQ development set with ETC and ETC augmented with presupposition information. We compare our augmentation results against our own replication of \citet{ainslie2020etc} (first row).} \label{table:augmented-results} \end{table*} \subsection{Step 3: Explanation Generation} \label{subsec:exp-generation} We used a template-based approach to explanation generation: we prepended the templates \textit{This question is unanswerable because we could not verify that...} or \textit{...because it is unclear that...} to the unverifiable presupposition \ref{ex:generation}. Note that we worded the template in terms of \textit{unverifiability} of the presupposition, rather than asserting that it is false. Under a closed-book setup like NQ, the only ground truth available to the model is a single document, which leaves a possibility that the presupposition is verifiable outside of the document (except in the rare occasion that it is refuted by the document). Therefore, we believe that unverifiability, rather than failure, is a phrasing that reduces false negatives. \ex. \label{ex:generation} \textbf{Q:} \textit{when does back to the future part 4 come out}\\ \textbf{Unverifiable presupposition:} there is some point in time that \textit{back to the future part 4 comes out}\\ \textbf{Simple prefixing:} This question is unanswerable because we could not verify that \textit{there is some point in time that back to the future part 4 comes out}. For the user study (Section~\ref{sec:user-study}), we used a manual, more fluent rewrite of the explanation generated by simple prefixing. In future work, fluency is a dimension that can be improved over templatic generation. For example, for \ref{ex:generation}, a fluent model could generate the response: \textit{This question is unanswerable because we could not verify that Back to the Future Part 4 will ever come out}. \section{End-to-end QA Integration} \label{sec:e2e} While the 3-step pipeline is designed to generate explanations for unanswerability, the generated presuppositions and their verifiability can also provide useful guidance even for a standard extractive QA system. They may prove useful both to unanswerable and answerable questions, for instance by indicating which tokens of a document a model should attend to. We test several approaches to augmenting the input of a competitive extractive QA system with presuppositions and verification labels. \paragraph{Model and augmentation.} We used Extended Transformer Construction (ETC) \citep{ainslie2020etc}, a model that achieves competitive performance on NQ, as our base model. We adopted the configuration that yielded the best reported NQ performance among ETC-base models.\footnote{The reported results in \citet{ainslie2020etc} are obtained using a custom modification to the inference procedure that we do not incorporate into our pipeline, since we are only interested in the relative gains from presupposition verification.} We experiment with two approaches to encoding the presupposition information. First, in the \emph{flat model}, we simply augment the input question representation (token IDs of the question) by concatenating the token IDs of the generated presuppositions and the verification labels (0 or 1) from the ALBERT QNLI model. Second, in the \emph{structured model} (Figure~\ref{fig:etc}), we take advantage of the global input layer of ETC that is used to encode the discourse units of large documents like paragraphs. Global tokens \emph{attend} (via self-attention) to all tokens of their internal text, but for other text in the document, they only attend to the corresponding global tokens. We add one global token for each presupposition, and allow the presupposition tokens to only attend to each other and the global token. The value of the global token is set to the verification label (0 or 1). \paragraph{Metrics.} We evaluated our models on two sets of metrics: NQ performance (Long Answer, Short Answer, and Average F1) and Unanswerability Classification (Accuracy and F1).\footnote{Here, we treated $\geq 4$ Null answers as unanswerable, following the definition in \citet{kwiatkowski-etal-2019-natural}.} We included the latter because our initial hypothesis was that sensitivity to presuppositions of questions would lead to better handling of unanswerable questions. The ETC NQ model has a built-in answer type classification step which is a 5-way classification between \{\textit{Unanswerable, Long Answer, Short Answer, Yes, No}\}. We mapped the classifier outputs to binary answerability labels by treating the predicted label as \textit{Unanswerable} only if its logit was greater than the sum of all other options. \paragraph{Results and Discussion} Table~\ref{table:augmented-results} shows that augmentations that use only the presuppositions or only the verification labels do not lead to gains in NQ performance over the baseline, but the presuppositions do lead to gains on Unanswerability Classification. When both presuppositions and their verifiability are provided, we see minor gains in Average F1 and Unanswerability Classification.\footnote{To contextualize our results, a recently published NQ model \citep{ainslie2020etc} achieved a gain of around $\sim$2\%.} For Unanswerability Classification, the improved accuracy is different from the baseline at the 86\% (flat) and 89\% (structured) confidence level using McNemar's test. The main bottleneck of our model is the quality of the verification labels used for augmentation (Table~\ref{table:verification-results})---noisy labels limit the capacity of the QA model to attend to the augmentations. While the gain on Unanswerability Classification is modest, an error analysis suggests that the added presuppositions modulate the prediction change in our best-performing model (structured) from the baseline ETC model. Looking at the cases where changes in model prediction (i.e., \textit{Unanswerable (U)} $\leftrightarrow$ \textit{Answerable (A)}) lead to correct answers, we observe an asymmetry in the two possible directions of change. The number of correct \textit{A} $\rightarrow$ \textit{U} cases account for 11.9\% of the total number of unanswerable questions, whereas correct \textit{U} $\rightarrow$ \textit{A} cases account for 6.7\% of answerable questions. This asymmetry aligns with the expectation that the presupposition-augmented model should achieve gains through cases where unverified presuppositions render the question unanswerable. For example, given the question \textit{who played david brent's girlfriend in the office} that contains a false presupposition \textit{David Brent has a girlfriend}, the structured model changed its prediction to \textit{Unanswerable} from the base model's incorrect answer \textit{Julia Davis} (an actress, not David Brent's girlfriend according to the document: \textit{$\dots$ arrange a meeting with the second woman (voiced by Julia Davis)}). On the other hand, such an asymmetry is not observed in cases where changes in model prediction results in incorrect answers: incorrect \textit{A} $\rightarrow$ \textit{U} and \textit{U} $\rightarrow$ \textit{A} account for 9.1\% and 9.2\%, respectively. More examples are shown in Appendix \ref{sec:error-analysis}. \section{Related Work} While presuppositions are an active topic of research in theoretical and experimental linguistics \citep[\textit{i.a.,}]{beaver1997presupposition,simons2013presupposing,schwarz2016experimental}, comparatively less attention has been given to presuppositions in NLP (but see \citet{clausen2009presupposed} and \citet{tremper2011extending}). More recently, \citet{cianflone2018lets} discuss automatically detecting presuppositions, focusing on adverbial triggers (e.g., \textit{too, also...}), which we excluded due to their infrequency in NQ. \citet{jeretic2020natural} investigate whether inferences triggered by presuppositions and implicatures are captured well by NLI models, finding mixed results. Regarding unanswerable questions, their importance in QA (and therefore their inclusion in benchmarks) has been argued by works such as \citet{clark-gardner-2018-simple} and \citet{zhu-etal-2019-learning}. The analysis portion of our work is similar in motivation to unanswerability analyses in \citet{yatskar-2019-qualitative} and \citet{asai2020challenges}---to better understand the causes of unanswerability in QA. \citet{hu2019read,zhang2020retrospective,Back2020NeurQuRI} consider answerability detection as a core motivation of their modeling approaches and propose components such as independent no-answer losses, answer verification, and answerability scores for answer spans. Our work is most similar to \citet{geva2021did} in proposing to consider implicit assumptions of questions. Furthermore, our work is complementary to QA explanation efforts like \citet{lamm2020qed} that only consider answerable questions. Finally, abstractive QA systems (e.g., \citealt{fan2019eli5}) were not considered in this work, but their application to presupposition-based explanation generation could be an avenue for future work. \section{Conclusion} Through an NQ dataset analysis and a user preference study, we demonstrated that a significant portion of unanswerable questions can be answered more effectively by calling out unverifiable presuppositions. To build models that provide such an answer, we proposed a novel framework that decomposes the task into subtasks that can be connected to existing problems in NLP: presupposition identification (parsing and text generation), presupposition verification (textual inference and fact verification), and explanation generation (text generation). We observed that presupposition verification, especially, is a challenging problem. A combination of a competitive NLI model, finer-tuning and rule-based hybrid inference gave substantial gains over the baseline, but was still short of a fully satisfactory solution. As a by-product, we showed that verified presuppositions can modestly improve the performance of an end-to-end QA model. In the future, we plan to build on this work by proposing QA systems that are more robust and cooperative. For instance, different types of presupposition failures could be addressed by more fluid answer strategies---e.g., violation of uniqueness presuppositions may be better handled by providing all possible answers, rather than stating that the uniqueness presupposition was violated. \section*{Acknowledgments} We thank Tom Kwiatkowski, Mike Collins, Tania Rojas-Esponda, Eunsol Choi, Annie Louis, Michael Tseng, Kyle Rawlins, Tania Bedrax-Weiss, and Elahe Rahimtoroghi for helpful discussions about this project. We also thank Lora Aroyo for help with user study design, and Manzil Zaheer for pointers about replicating the ETC experiments. \bibliographystyle{acl_natbib}
{'timestamp': '2021-09-06T02:20:07', 'yymm': '2101', 'arxiv_id': '2101.00391', 'language': 'en', 'url': 'https://arxiv.org/abs/2101.00391'}
arxiv
\section{Introduction} As a new and dominating service class in 6th Generation (6G) networks, massive Ultra-Reliable and Low Latency Communications (mURLLC) integrates URLLC with massive access to support massive short-packet data communications in time-sensitive wireless networks with high reliability and low access latency\cite{9186090}. This requires a reliability-latency-scalability trade-off and mandates a principled and scalable framework accounting for the delay, reliability, and decision-making under uncertainty \cite{8869705}. Concretely speaking, the Third Generation Partnership Project (3GPP) standard \cite{3gpp2018study} has defined a general URLLC requirement as: $1-10^{-5}$ reliability within 1ms user plane latency for 32 bytes. More details on the requirements of various different URLLC use cases, including smart grids, intelligent transportation systems, and process automation with reliability requirements of $1-10^{-3}$ to $1-10^{-6}$ at latency requirements between 1 ms to 100 ms, can be found in \cite{3gpp22261}. It is also anticipated that the device density may grow to hundred(s) of devices per cubic meter in the 6G white paper\cite{latva2020key}. Current cellular network can hardly fulfill the joint massive connectivity, ultra-reliability, and low latency requirements in mURLLC service. To achieve low latency, \textit{grant-free (GF) access} has been proposed\cite{11705654,ye2018uplink} as an alternative for traditional grant-based (GB) access due to its drawbacks in high latency and heavy signaling overhead\cite{6163599}. Different from GB access, GF access allows a User Equipment (UE) to transmit its data to the Base Station (BS) in an arrive-and-go manner, without sending a scheduling request (SR) and obtaining a resource grant (RG) from the network\cite{R1-1608917}. To achieve high reliability, several GF schemes, including the \textit{K-repetition} scheme and the \textit{Proactive} scheme, have been proposed, where a pre-defined number ($K$) of consecutive replicas of the same packet are transmitted \cite{3gpp38214,1705246,1612246,1903079}. To achieve massive connectivity, \textit{non-orthogonal multiple access (NOMA)} has been proposed to synergize with GF in order to deal with the multiple access (MA) physical resource collision as shown in Fig.~\ref{fig:1} in contention-based\footnote{Unless otherwise stated, the GF and GB access described in this work are both contention based.} GF access on orthogonal multi-access (OMA) physical resources, when two or more UEs transmit their data using the same MA physical resource\cite{8533378,9097306}. \begin{figure}[htbp!] \centering \includegraphics[width=5.6in,height=2.5in]{resourcecollision.pdf} \caption{Collision of MA physical resource. } \label{fig:1} \end{figure} Here, we focus on the signature-based GF-NOMA, including the sparse code multiple access (SCMA), multiuser shared access (MUSA), pattern division multiple access (PDMA), and etc, where the NOMA technique allows multiple users to transmit over the same MA physical resource by employing user-specific signature patterns (e.g, codebook, pilot sequence, interleaver/mapping pattern, demodulation reference signal, power, etc.)\cite{7972955}. However, when two or more UEs transmit their data using the same MA physical resource and the same MA signature, the MA signature collision occurs, and the BS cannot differentiate among different UEs and therefore cannot decode the data\cite{8533378,9097306}. It is important to know that the research challenges in GF-NOMA are fundamentally different from those in GB-NOMA \cite{9210822,8408843}. \begin{figure}[htbp!] \centering \includegraphics[width=5.6in,height=2.6in]{GB.pdf} \caption{Uplink transmissions for grant-based and grant-free random access. } \label{fig:2} \end{figure} In GB scheme, the four-step random access (RA) procedure as shown in Fig.~\ref{fig:2} is executed by the UE to request the BS to schedule dedicated resources for data transmission, where the data transmission is more likely to be successful once the random access succeeds. While in GF scheme, the data is transmitted along with the pilot in a randomly chosen MA resource, which is unknown at the BS, and can lead to new research problems including but not limited to: 1) identify the MA signature collisions due to UEs transmitting data over the same channel resource with the same MA signature; 2) blind detection of active UEs due to that the set of active users is unknown to the BS; 3) blind decoding of UEs’ data with no knowledge of channels and codebooks. These new research problems make the dynamic resource configuration of GF-NOMA as one important but challenging problem to solve. The main challenges of the dynamic resource configuration optimization of GF-NOMA include: 1) the set of active users and their respective channel conditions are unknown to the BS, which prohibits the pre-configuration and the pre-assignment of resources, including pilots/preambles, power, codebooks, repetition values, retransmission related parameters, and etc; 2) simultaneously satisfy the reliability and latency requirements under random traffics, the optimal parameter configurations vary over different time slots, which is hard to be described by a tractable mathematical model; 3) the MA signature collision detection and the blind UE activity detection, as well as the data decoding, need to be considered, which largely impacts the resource configuration in each time slot; 4) a general optimization framework for GF-NOMA systems have never been established for various signature-based NOMA schemes. The above mentioned challenges can hardly be solved via the traditional convex optimization method, due to the complex communication environment with the lack of tractable mathematical formulations, whereas Machine Learning (ML), can be a potential alternative approach, due to that it solely relies on the self-learning of the environment interaction, without the need to derive explicit optimization solutions based on a complex mathematical model. In the GF-NOMA system, the BS can only observe the results of both collision detection (e.g., the number of non-collision UEs and collision MA signatures) and data decoding (e.g., the number of successful decoding UEs and failure decoding UEs) in each round trip time (RTT). This historical information can be potentially used to facilitate the long-term optimization of future configurations. Even if one knew all the relevant statistics, tackling this problem in an exact manner would result in a Partially Observable Markov Decision Process (POMDP) with large state and action spaces, which is generally intractable. To deal with it, Reinforcement Learning (RL), can be a promising tool to deal with this complex POMDP problem in GF-NOMA resource configuration optimization. In this paper, we aim to develop a general learning framework for GF-NOMA systems with mURLLC services. Our contributions can be summarized as follows: \begin{itemize} \item We develop a general learning framework for dynamic resource configuration optimization in signature-based GF-NOMA systems, including the SCMA, MUSA, PDMA, and etc, for mURLLC service. In this framework, we practically simulate the random traffics, the resource selection and configuration, the transmission latency check, the collision detection, the data decoding, and the Hybrid Automatic Repeat reQuest (HARQ) retransmission procedures. We use this generated simulation environment to train the RL agents. \end{itemize} \begin{itemize} \item We first perform the repetition values dynamic optimization via developing a double Deep Q-Network (DDQN) to optimize the number of successfully served UEs under the latency constraint for the K-repetiton GF scheme and the Proactive GF scheme, respectively. We then develop a Cooperative Multi-Agent learning based on DQN (CMA-DQN) to dynamically optimize both the repetition values and contention-transmission unit (CTU) numbers, which breaks down the selection in high-dimensional parameters into multiple parallel sub-tasks with a number of DQN agents cooperatively being trained to produce each parameter. \end{itemize} \begin{itemize} \item Through dynamic optimization via CMA-DQN, we show that the Proactive scheme outperforms the K-repetition scheme in terms of the number of successfully served UEs, especially under the long latency constraint, which are opposite to the results without optimization in our previous work\cite{9174916} with only a single packet transmission, Our results also show the superior performance of CMA-DQN over the conventional load estimation-based approach (LE-URC) in the multiple configuration parameters scenario. Importantly, our general learning framework can be used to optimize theresource configuration problems in all the signature-based GF-NOMA schemes. \end{itemize} The rest of the paper is organized as follows. Section II presents related works. Section III illustrates the system model and formulates the problem. Section IV illustrates the preliminary and the conventional approach. Section V proposes Q-learning based uplink GF-NOMA resource configuration approaches. Section VI elaborates the numerical results, and finally, Section VII summarizes the conclusion and future work. \section{Related Works} The potential of GF-NOMA in diverse services is an open research area as the research challenges of GF-NOMA have not been solved yet. In \cite{7887683,8352623,8288402}, GF-NOMA is designed empirically by directly incorporating the GF mechanism into several state-of-the-art NOMA schemes, including SCMA, MUSA, and PDMA, that are categorized according to their specially designed spreading signatures. Most existing GF-NOMA works focused on the receiver design using the compressive sensing (CS) technique. The authors in \cite{7731144} proposed a message passing algorithm to solve the problem of GF-NOMA using CS-based approaches, which improves the bit error rate (BER) performance in comparison to \cite{7462187}. The authors in \cite{7996932} considered a comprehensive study such that synchronization, channel estimation, user detection and data decoding were performed in one-shot. The proposed CS-based algorithm exploited the sparsity of the system in terms of user activity and multi-path fading. To the best of our knowledge, no works have focused on the optimization of a general GF-NOMA system taking into account the MA collision detection, the UE detection, as well as data decoding procedures. The major challenge comes from the fact that random user activation and non-orthogonal transmissions make the GF-NOMA difficult to mathematically model and optimize using traditional optimization methods. Machine Learning has been introduced to improve the GF-NOMA systems in \cite{8625480,8952876,8968401}. In \cite{8625480}, deep learning was used to solve a variational optimization problem for GF-NOMA. The neural network model includes encoding, user activity, signature sequence generation, and decoding. The authors then extended their work to design a generalized/unified framework for NOMA using deep multi-task learning in \cite{8952876}. A deep learning-based active user detection scheme has been proposed for GF-NOMA in \cite{8968401} . By feeding training data into the designed deep neural network, the proposed active user detection scheme learns the nonlinear mapping between received NOMA signal and indices of active devices. Their results shown that the trained network can handle the whole active user detection process, and achieve accurate detection of the active users. These works assumed that each UE is pre-allocated with a unique sequence, and thus collisions are not an issue. However, this assumption does not hold in massive UEs settings in mURLLC, where the collision is the bottleneck of the GF-NOMA performance. Different from \cite{8625480,8952876,8968401}, we aim to develop a general learning framework to optimize GF-NOMA systems for mURLLC service taking into account the MA signature collision, the UE detection as well as the data decoding procedures. \section{System Model} We consider a single cell network consisting of a BS located at the center and a set of $N$ UEs randomly located in an area of the plane $\mathbb{R}^2$, where the UEs are in-synchronized and unaware of the status of each other. Once deployed, the UEs remain spatially static. The time is divided into short transmission time intervals (TTIs)\footnote{In this paper, the TTI refers to a mini-slot. The Fifth Generation (5G) New Radio (NR) introduces the concept of `mini-slots' and supports a scalable numerology allowing the sub-carrier spacing (SCS) to be expanded up to 240 kHz. In contrast with the LTE slot consisting of 14 OFDM symbols per TTI, the number of OFDM symbols in 5G NR mini-slots ranges from 1 to 13 symbols, and the larger SCS decreases the length of each symbol further. Collectively, mini-slots and flexible numerology allow shorter transmission slots to meet the stringent latency requirement. }, and the small packets for each UE are generated according to random inter-arrival processes over the short-TTIs, which are Markovian as defined in \cite{name2015,3gpp37868} and unknown to BS. \begin{figure}[htbp!] \centering \includegraphics[width=6.6 in,height=3in]{procedure3.pdf} \caption{Uplink GF-NOMA transmission procedure. } \label{fig:3} \end{figure} \subsection{ GF-NOMA Network Model} We consider the uplink contention-based GF-NOMA over a set of preconfigured MA resources. To capture the effects of the physical radio, we consider the standard power-law path-loss model with the path-loss attenuation $r^{-\eta}$, where $r$ is the Euclidean distance between the UE and the BS and $\eta$ is the path-loss attenuation factor. In addition, we consider a Rayleigh flat-fading environment, where the channel power gains $h$ are exponentially distributed (i.i.d.) random variables with unit mean. We presents the uplink GF-NOMA procedure in Fig.~\ref{fig:3} following the 3GPP standard \cite{Solutions,R1-1608917,MA,1612246,1903079}, which includes 1) traffic inter-arrival, 2) resources and parameters configuration, 3) latency check; 4) collision detection, 5) data decoding, and 6) HARQ retransmissions. These six stages are explained in details in the following six subsections to illustrate the system model. \subsubsection{Traffic Inter-Arrival} We consider a bursty traffic scenario, where massive UEs are triggered due to an emergency event, e.g., earthquake alarm and fire alarms\cite{3gpp37868,8985528}. Each UE would be activated at any time $\tau$, according to a time limited Beta probability density function as \cite[Section 6.1.1]{3gpp37868} \begin{align}\label{beta} p(\tau) = \frac{{{\tau ^{\alpha - 1}}{{(T - \tau )}^{\beta - 1}}}}{{{T^{\alpha + {\beta} - 1}} \rm {Beta}(\alpha ,\beta )}}, \end{align} where $T$ is the total time of the bursty traffic and Beta ($\alpha , \beta$) is the Beta function with the constant parameters $\alpha$ and $\beta$\cite{gupta2004handbook}. Due to the nature of slotted-Aloha, a UE can only transmit at the beginning of a RTT as shown in Fig. 4 and Fig. 5, which means that the newly activated UEs executing transmission come from those who received an packet within the interval between with the last RTT period ($\tau^{i-1}$,$\tau^{i}$). The traffic instantaneous rate in packets in a period is described by a function $p(\tau)$, so that the packets arrival rate in the $i$th RTT is given by \begin{align}\label{rate} {\mu ^i} = \int_{{\tau _{i - 1}}}^{{\tau _i}} {p(\tau )} d\tau. \end{align} \subsubsection{Resources and Parameters Configuration} The MA resources, repetition values, and HARQ related parameters, etc, are configured at the BS by radio resource control (RRC) signaling and L1 signaling prior to the GF access (as Type 2 GF \cite{3gpp38824}). a) Repetition values: We consider the K-repetition GF scheme and the Proactive GF scheme as shown in Fig.~\ref{fig:4} and Fig.~\ref{fig:5}, respectively. The repetition values for K-repetition scheme $K_{\rm Krep}^t$ and for Proactive scheme $K_{\rm Proa}^t$ are configured at the beginning of each RTT. \begin{figure}[htbp!] \centering \includegraphics[width=5.3 in,height=2.2in]{krep2.pdf} \caption{K-repetition GF transmission } \label{fig:4} \end{figure} \begin{itemize} \item \textbf{K-{repetition} scheme:} The K-repetition scheme is illustrated in Fig.~\ref{fig:4}, the UEs served by the BS are configured to autonomously transmit (T) the same packet for $K_{\rm Krep}^t$ repetitions in consecutive TTIs. The BS decodes (D) each repetition independently and the transmission in one RTT is successful when at least one repetition succeeds. After processing all the received $K_{\rm Krep}^T$ repetitions, the BS transmits the ACK/NACK feedback (F) to the UE. \begin{figure}[htbp!] \centering \includegraphics[width=5.6 in,height=2.6in]{proa2.pdf} \caption{Proactive GF transmission } \label{fig:5} \end{figure} \item \textbf{Proactive scheme:} The Proactive scheme is illustrated in Fig.~\ref{fig:5}. Similar to the K-repetition scheme, the UEs served by the BS are configured to repeat the transmission for a maximum number of $K_{\rm Proa}^t$ repetitions, but can receive the feedback after each repetition. This allows the UE to terminate repetitions earlier once receiving the ACK. \end{itemize} Considering the small packets of mURLLC traffic, we set the packet transmission time as one TTI. The BS feedback time and the BS (UE) processing time are also assumed to be one TTI following our previous work \cite{9174916}. Once the repetition value is configured, the duration of one RTT is known to the UEs and the BS, which is given as \begin{align}\label{RTT} T_{{\rm RTT}}^t=(K^t+3) {\rm TTIs}, \end{align} with $K^t=K_{\rm Krep}^t$ or $K^t=K_{\rm Proa}^t$ for the K-repetition scheme and the Proactive scheme, respectively. b) MA resources: A \textit{contention-transmission unit} (CTU) as shown in Fig.~\ref{fig:6} is defined as the basic MA resource, where each CTU may comprise of a MA physical resource and a MA signature\cite{ye2018uplink,9097306,7063547}. \begin{figure}[htbp!] \centering \includegraphics[width=6.2 in,height=2.4in]{CTU3.pdf} \caption{GF-NOMA resource } \label{fig:6} \end{figure} The MA physical resources represent a set of time-frequency resource blocks (RBs). The MA signatures represent a set of pilot sequences for channel estimation and/or UE activity detection, and a set of codebooks for robust data transmission and interference whitening, etc. Without loss of generality, in one TTI, we consider $F$ orthogonal RBs and each RB is overlaid with $L$ unique codebook-pilot\footnote{A one-to-one mapping or a many-to-one mapping between the pilot sequences and codebooks can be predefined. Since it has been verified in \cite{7887683} that the performance loss due to codebook collision is negligible for a real system, we focus on the pilot sequence collision and consider the one-to-one mapping as \cite{8533378,9031550}. } pairs\cite{8533378,8316582}. Thus, at the beginning of each RTT, the BS configures a resource pool of $C^t=F\times L$ unique CTUs, and each UE randomly choose one CTU from the pool to transmit in this RTT. \subsubsection{Latency Check} The HARQ index $H_{HARQ}$ is included in the pilot sequence and can be detected by the BS. At the beginning of each RTT, the HARQ index and the transmission latency $T_{\rm late}$ will be updated as shown in Fig.~\ref{fig:3}. For example, for the initial RTT with initial $K^1$, $H_{HARQ}=1$ and $T_{\rm late}=RTT_{H_{HARQ}=1}$, where $RTT_{H_{HARQ}}$ is calculated by using \eqref{RTT}. After this round time trip transmission, the BS optimizes a $K^2$ based on the observation of the reception and configures it to the UE for the next RTT. Then, the UE updates its $H_{HARQ}=2$ and calculated $RTT_{H_{HARQ}=2}$ by using \eqref{RTT} with $K^2$, and consequently, the transmission latency $T_{\rm late}$ is updated as $T_{\rm late}=RTT_{H_{HARQ}=1}+RTT_{H_{HARQ}=2}$. When $T_{\rm late}>T_{\rm cons}$, the UE fails to be served and the packets will be dropped. Note that the HARQ index, as well as the transmission latency, will be updated at the beginning of each RTT instead of at the end of each RTT due to that we consider the user plane latency\footnote{User plane latency is defined as the one-way latency from the processing of the packet at the transmitter to the successful reception of the packet, including the transmission processing time, the transmission time, and the reception processing time.} in this work. That is to say, from the UE perspective, when the UE executes this RTT, it will check transmission results after finishing the RTT. Thus, the duration of this RTT should be included when calculating the UE transmission latency. \subsubsection{Collision Detection} At each RTT, each active UE transmits its packets to the BS by randomly choosing a CTU. The BS can detect the UEs that have chosen different CTUs. \begin{figure}[htbp!] \centering \includegraphics[width=5.3in,height=3.5in]{collision1.pdf} \caption{Detection and Decoding in a network with L=2 RBs, C = 6 CTUs and N = 8 UEs. } \label{fig:7} \end{figure} However, if multiple UEs choose the same CTU, the BS cannot differentiate the these UEs and therefore cannot decode the data. We categorize the CTUs into three types: an \textit{idle} CTU is a CTU which has not been chosen by any UE; a \textit{singleton} CTU is a CTU chosen by only one UE; and a \textit{collision} CTU is a CTU chosen by two or more UEs\cite{8533378}. One example is illustrated in Fig.~\ref{fig:7}. The UE 1 and UE 5 have chosen the unique CTU 6 and CTU 5, respectively, thus, the CTU 6 and 5 are singleton CTUs. The CTU 3 is an idle CTU. The UE 4 and UE 7 have chosen the CTU 1, the UE 2 and UE 3 have chosen the CTU 2, and the UE 6 and UE 8 have chosen the CTU 4, thus, CTU 1, 2 and 4 are collision CTUs. After collision detection at the $t$th RTT, the BS observes the set of singleton CTUs ${\cal C}_{sc}^t$, the set of idle CTUs ${\cal C}_{ic}^t$, and the set of collision CTUs ${\cal C}_{cc}^t$ as shown in orange, blue and green color, respectively, in Fig.~\ref{fig:7}. \subsubsection{ Data Decoding} After detecting the UEs that have chosen the singleton CTUs (e.g., UE 1 and UE 5 shown as triangle in Fig.~\ref{fig:7}), the BS performs the successive interference cancellation (SIC) technique to decode the data of these UEs. During the decoding, the UEs that transmit in different RBs do not interfere with each other due to the orthogonality, and only UEs that transmit in the same RB cause interference, i.e., as shown in Fig.~\ref{fig:7}, the interference UE set in RB 1 is $\{2,3,4,7\}$ shown in color grey and the interference UE set in RB 2 is $\{1,5,6,8\}$ shown in color yellow. In each iterative stage of SIC decoding, the CTU with the strongest received power is decoded by treating the received powers of other CTUs over the same RB as the interference. Each iterative stage of SIC decoding is successful when the signal-to-interference-plus-noise ratio (SINR) in that stage is larger than the SINR threshold. If the received signal is decoded successfully, the decoded signal is subtracted from the received signal\footnote{We assume perfect SIC the same as \cite{8533378}, with no error propagation between iterations.}. Thus, in the $k$th repetition of the $t$th RTT, the $s$th stage of SIC decoding is successful if the SINR is higher than a threshold $\gamma_{th}$ \cite{8533378}, i.e., \begin{align}\label{SIC} {\rm SINR}^{t}_{f,s}(k) = \frac{{{P}{h_{s,k}}{r_s}^{ - \eta }}}{{\sum\limits_{m=s+1}^{ { N}_{f,sc}^t(k)} {{P_m}} {h_{m,k}}r_m^{ - \eta } + \sum\limits_{n' \in {\cal N}_{f,cc}^t(k)}^{} {{P_{n'}}} {h_{n',k}}r_{n'}^{ - \eta } + {\sigma ^2}}} \ge {\gamma _{th}}, \end{align} where $P$ is the transmission power, ${\cal N}_{f,sc}^t$ is the set of other devices that have chosen the singleton CTUs over the $f$th RB, ${\cal N}_{f,cc}^t$ is the set of devices that have chosen the collision CTUs over the $f$th RB, $\sigma^2$ is the noise power. The SIC procedure stops when one iterative stage of the SIC fails or when there are no more signals to decode. The SIC decoding procedure for each GF scheme is described in the following. $i$) K-repetition scheme: For the K-repetition scheme as shown in Fig. 4, the successful decoding event occurs at least one repetition decoding succeeds. Thus, the SIC decoding procedure follows: \begin{itemize} \item Step 1: Start the $k$th repetition with the initial $k=1$, ${\cal N}_{f,sc}^t$ and ${\cal N}_{f,cc}^t$; \item Step 2: Decode the $s$th CTU with the initial $s=1$ using \eqref{SIC}; \item Step 3: If the $s$th CTU is successfully decoded, put the decoded UE in set ${\cal N}_{f,sd}^t(k)$ and go to Step 4, otherwise go to Step 5; \item Step 4: If $s \le { N}_{f,sc}^t$, do $s=s+1$, go to Step 2, otherwise go to Step 5; \item Step 5: SIC for the $k$th repetition stops; \item Step 6: If $k \le K_{\rm Krep}$, do $k=k+1$, go to Step 1, otherwise go to the end. \end{itemize} $ii$) Proactive scheme: For the Proactive scheme as shown in Fig.~\ref{fig:5}, the successful decoding event occurs once the repetition decoding succeeds. The successfully decoded UEs will not transmit in the remaining repetitions in this RTT to reduce interference to other UEs. It should be noted that the ACK/NACK feedback can only be received after 3TTIs, which means the ACK feedback of the $k$th successful repetition can be received by the UE in the $(k+3)$th repetition and the UE stops transmission from the $(k+4)$th repetition. In addition, the BS does not send any ACK/NACK feedback to the collision UEs. The collision USs in the $k$th repetition that do not receive feedback at the pre-defined timing after the UEs sent the packet (e.g., after 3TTIs) will not transmit in the remaining repetitions to reduce interference to other UEs. \begin{itemize} \item Step 1: Initialize $k=1$, ${\cal N}_{f,sc}^t$ and ${\cal N}_{f,cc}^t$. If $k< 4$, go to Step 3, otherwise go to Step 2; \item Step 2: Update the ${\cal N}_{f,sc}^t(k)={\cal N}_{f,sc}^t(k)-{\cal N}_{f,sd}^t(k-4)$ and ${\cal N}_{f,cc}^t(k)=\varnothing$; \item Step 3: Start the $k$th repetition with $k$, ${\cal N}_{f,sc}^t(k)$ and ${\cal N}_{f,cc}^t(k)$; \item Step 4: Decode the $s$th CTU with initial $s=1$ using \eqref{SIC}; \item Step 5: If the $s$th CTU is successfully decoded, put the decoded UE in set ${\cal N}_{f,sd}^t(k)$ and go to Step 6, otherwise go to Step 7; \item Step 6: If $s \le { N}_{f,sc}^t$, do $s=s+1$, go to Step 4, otherwise go to Step 7; \item Step 7: SIC for the $k$th repetition stops; \item Step 8: If $k \le K_{\rm Pro}$, do $k=k+1$, go to Step 1, otherwise go to the end. \end{itemize} Finally, the set ${\cal N}_{f,sd}^t = \bigcup\limits_{k = 1}^{{K_{Krep}}} {( {{\cal N}_{f,sd}^t(k)} )} $ is the successfully decoded UEs over the $f$th RB and ${\cal N}_{sd}^t = \bigcup\limits_{f = 1}^{{F^t}} {( {{\cal N}_{f,sd}^t} )} $ is the successfully decoded UEs in the $t$th RTT. \subsubsection{HARQ Retransmissions} We We take into account the GF-NOMA HARQ retransmissions to achieve high reliability performance. However, due to the latency constraint $T_{\rm cons}$, the HARQ retransmission times are limited as shown in Fig.~\ref{fig:3}. The UE determines a re-transmission or not based on the following two different scenarios. $i$) when the UE receives an ACK from the BS, it means that the BS successfully detected the UE (i.e., the UE choosing the singleton CTUs) and decoded the UE's data (i.e., SIC succeeds), no further re-transmission is needed; $ii$) when the UE receives a NACK from the BS, it means that the BS successfully detected the UE but failed to decode the UE's data (i.e., SIC fails). Otherwise, when the UE does not receive any feedback at the pre-defined timing after the UE sent the packet (e.g., at the end of one RTT), it means the BS failed to identify the UE, the UE determines whether to retransmit or not in the next RTT based on the transmission latency check as shown in Fig.~\ref{fig:3}. \subsection{Problem Formulation} Once actived in a given RTT $t$, a UE executes the GF-NOMA procedure, where the UE randomly chooses one of the preconfigured $C^t$ CTUs to transmit its packets for $K_{\rm{Krep}}^t$ times or $k_{\rm{Proa}}^t\le K_{\rm{Proa}}^t$ times under the K-repetition scheme and the Proactive scheme, respectively. During this RTT, the GF-NOMA fails if: ($i$) a CTU collision occurs when two or more UEs choose the same CTU (i.e., UE detection fails); or ($ii$) the SIC decoding fails (i.e., data decoding fails). Once failed, UEs decides whether to retransmit in the following RTT or not based on the transmission latency check. When $T_{\rm late}>T_{\rm cons}$, the UE fails to be served and its packets will be dropped. It is obvious that 1) increasing the repetition values $K^t$ could improve the GF-NOMA success probability, but results in an increasing latency; 2) increasing CTU numbers $C^t$ could improve the UE detection success probability, but it results in low resource utilization efficiency. Thus, it is necessary to tackle the problem of optimizing the GF-NOMA configuration defined by parameters\footnote{According to the UE detection and data decoding procedure described in Section II.A, for the same CTU number $C^t$, a large RB number $F^t$ leads to fewer UEs in each RB, which increases the data decoding success probability. That is to say, the larger RB number, the better. Thus, we fix the RB number $F=4$ in this work to optimize the CTU number.} $A^t$ = $\{K^t,C^t\}$ for each RTT $t$ under both the K-repetition scheme and the Proactive scheme, where $K^t$ is the repetition value and $C^t$ is the number of CTUs. At the beginning of each RTT $t$, the decision is made by the BS according to the transmission receptions ${U^{t'}}$ for all prior RTTs (${t'=1,...,t-1}$), consisting of the following variables: the number of the collision CTUs ${V_{cc}^{t'}}$, the number of the idle CTUs ${V_{ic}^{t'}}$, the number of the singleton CTUs ${V_{sc}^{t'}}$, the number of UEs that have been successfully detected and decoded under the latency constraint ${V_{sd}^{t'}}$, and the number of UEs that have been successfully detected but not successfully decoded ${V_{ud}^{t'}}$. We denote ${{H^t}=\{O^1, O^2,..., O^{t-1}\}}$ with ${{O^{t-1}}=\{U^{t-1}, A^{t-1}\}}$ as the observation in each RTT $t$ including histories of all such measurements and past actions. At each RRT $t$, the BS aims at maximizing a long-term objective $R_t$ related to the average number of UEs that have successfully send data under the latency constraint ${V_{sd}^{t'}}$ with respect to the stochastic policy $\pi$ that maps the current observation history $O^t$ to the probabilities of selecting each possible parameters in $A^t$. This optimization problem (P1) can be formulated as: \begin{align}\label{P1} ({\rm P1}:)&\max\limits_{\pi ({A^t}| {{O^t}} )}\quad \sum\limits_{k = t}^\infty {{\gamma ^{k - t}}}{{\mathbb E}_\pi }[V_{sd}^k]\\ & \begin{array}{r@{\quad}r@{}l@{\quad}l} s.t.&T_{\rm late} \le T_{\rm cons}\\ \end{array}, \end{align} where $\gamma \in [0,1)$ is the discount factor for the performance accrued in the future RTTs, and $\gamma=0$ means that the agent just concerns the immediate reward. Since the dynamics of the GF-NOMA system is Markovian over the continuous RRTs, this is a Partially Observable Markov Decision Process (POMDP) problem which is generally intractable. Here, the partial observation refers to that a BS can not fully know all the information of the communication environment, including, but not limited to, the channel conditions, the UE transmission latency, the random collision process, and the traffic statistics. Approximate solutions will be discussed in Section IV and V. \section{Preliminaries and Conventional Solutions} The optimization problem (P1) is really complicated, which cannot be easily solved via the conventional uplink resource optimization solutions, especially the dynamic optimization taking into account the latency constraint. In addition, most prior works simplified the optimization without consideration of future performance\cite{7404058}. We modify the load estimation (LE) approach given in \cite{7404058} via estimating based on the last number of the collision CTUs ${V_{cc}^{t-1}}$ and the previous numbers of idle CTUs ${V_{ic}^{t-1}}$, ${V_{ic}^{t-2}}$, $\cdots$, ${V_{ic}^{1}}$. To simplify, we propose a load estimation-based uplink resource configuration (LE-URC) approach to dynamically configure the CTUs number $C^t$ with the fixed repetition value $K^t$ in each RTT to maximize the successfully served UEs without latency check and SIC procedure\footnote{In the conventional solution, we ignore the SIC detection failure. That is to say, the UE is successfully transmitted if there is no CTU collision occurs. Thus, the optimization objective is $V_{sc}^t$.} described in Section III, which is expressed as \begin{align}\label{P2} ({\rm P2}:)&\max\limits_{\pi ({C^t}| {{O^t}} )}{{\mathbb E}_\pi }[V_{sc}^t], \end{align} At the RTT $t-1$ we consider that $D_{UE}^{t - 1}=n$ UEs randomly choose one of the available $C^{t-1}$ CTUs with an equal probability $1/C^{t-1}$. The probability that no UE chooses a CTU $c$ is \begin{align}\label{user probability} {\mathbb{P}}({D_c} = 0 | {D_{UE}^{t - 1} = n}) = {( {1 - 1/{C^{t - 1}}} )^n}. \end{align} The expected number of idle CTUs is given by \begin{align}\label{idle pro} \mathbb{E}[ {V_{ic}^{t - 1}| {D_{UE}^{t - 1} = n} } ] = \sum\limits_{c = 1}^{{C^{t - 1}}} {\mathbb{P}({D_c} = 0 | {D_{UE}^{t - 1} = n} ) = } {C^{t - 1}}{(1 - 1/{C^{t - 1}})^n}. \end{align} Due to that the actual number of idle CTUs $V_{ic}^{t - 1}$ can be observed at the BS, the number of active UEs in the $(t-1)$th RTT is estimated as \begin{align}\label{estimate} {\tilde D_{UE}^{t - 1}} = {f^{ - 1}}(\mathbb{E}[ {V_{ic}^{t - 1}| {D_{UE}^{t - 1} = n} } ]) = {\log _{(1 - 1/{C^{t - 1}})}}(V_{ic}^{t - 1}/{C^{t - 1}}). \end{align} Next, we need to estimate the number of active UEs in the $t$th RTT $\tilde D_{UE}^t$. We use $\delta^t$ to represent the difference between the estimated numbers of UEs in the $(t-1)$th and the $t$th RTTs. That is ${\delta ^t} = \tilde D_{UE}^t - \tilde D_{UE}^{t - 1}$ for $t=1,2,\cdots$, where $\tilde D_{UE}^{0}=0$. According to \cite{7404058}, we have ${\delta ^t}\approx {\delta ^{t-1}}$. Therefore, the number of UEs in RTT $t$ is estimated as \begin{align}\label{estimate_t} \tilde D_{UE}^t = \max \{ {2V_{cc}^{t - 1},\tilde D_{UE}^{t - 1} + {\delta ^{t-1}}} \}, \end{align} where $2V_{cc}^{t - 1}$ represents that there are at least $2V_{cc}^{t - 1}$ number of UEs colliding in the last RTT. Based on the estimated number of active UEs in the $t$th RTT $\tilde D_{UE}^t$, the probability that only one UE chooses CTU $c$ (i.e., no collision occurs) is given by \begin{align}\label{success_up} {\mathbb{P}}({D_c} = 1| {\tilde D_{UE}^t = n} ) = \Big( \begin{array}{l} n\\ 1 \end{array} \Big)1/{C^t}{( {1 - 1/{C^t}} )^{n - 1}}. \end{align} The the expected number of the successfully served UEs in the $t$th RTT is given as \begin{align}\label{UE_number} V_{suss}^t(C^t)=\mathbb{E}[ {V_{sc}^{t }| {\tilde D_{UE}^{t} = n} } ] = \sum\limits_{c = 1}^{{C^{t}}} {\mathbb{P}({D_c} = 1 | {D_{UE}^{t } = n} ) = } n{(1 - 1/{C^{t }})^{n-1}}. \end{align} The maximal expected number of the successfully served UEs is obtained by choosing the number of CTUs as \begin{align}\label{max} {C^{t * }} = \mathop {\arg \max }\limits_{C^t \in {{\cal N}_{CTU}}} V_{suss}^t(C^t). \end{align} \section{Deep reinforcement learning-based GF-NOMA resource configuration} The deep reinforcement learning (DRL) is regarded as a powerful tool to address complex dynamic control problems in POMDP. In this section, we propose a Deep Q-network (DQN) based algorithm to tackle the problem (P1). The reasons in choosing DQN are that: 1) the Deep Neural Network (DNN) function approximation is able to deal with several kinds of partially observable problems \cite{sutton2018reinforcement,mnih2015human}; 2) DQN has the potential to accurately approximate the desired value function while addressing a problem with very large state spaces; 3) DQN is with high scalability, where the scale of its value function can be easily fit to a more complicated problem; 4) a variety of libraries have been established to facilitate building DNN architectures and accelerate experiments, such as TensorFlow, Pytorch, Theano, Keras, and etc.. To evaluate the capability of DQN in GF-NOMA, we first consider the dynamic configuration of repetition value $K^t$ with fixed CTU numbers $C^t$, where the DQN agent dynamically configures the $K^t$ at the beginning of each RTT for K-repetition and Proactive GF schemes. We then propose a cooperative multi-agent learning technique based on the DQN to optimize the configuration of both repetition value $K^t$ and CTU numbers $C^t$ simultaneously, which breaks down the selection in high-dimensional action space into multiple parallel sub-tasks. \subsection{Deep reinforcement learning-based single-parameter configuration} \subsubsection{Reinforcement learning framework} \label{RL_framework} To optimize the number of successfully served UEs under the latency constraint in GF-NOMA schemes, we consider a RL-agent deployed at the BS to interact with the environment in order to choose appropriate actions progressively leading to the optimization goal. We define $s \in \cal S$, $a \in \cal A$, and $r \in \cal R$ as any state, action, and reward from their corresponding sets, respectively. The RL-agent first observes the current state $S^t$ corresponding to a set of previous observations $(O^t=\{U^{t-1},U^{t-2},...,U^{1} \})$ in order to select an specific action $A^t\in {\cal A}(S^t)$. Here, the action $A^t$ represents the repetition values $K^t$ in the $t$th RTT $A^t=K^t$ in this single-parameter configuration scenario and the $S^t$ is a set of indices mapping to the current observed information $U^{t-1}=[V_{cc}^{t-1},V_{ic}^{t-1},V_{sc}^{t-1},V_{sd}^{t-1},V_{ud}^{t-1}]$. With the knowledge of the state $S^T$, the RL-agent chooses an action $A^t$ from the set $\cal A$. Once an action $A^t$ is performed, the RL-agent transits to a new observed state $S^{t+1}$ and receives a corresponding reward $R^{t+1}$ as the feedback from the environment, which is designed based on the new observed state $S^{t+1}$ and guides the agent to achieve the optimization goal. As the optimization goal is to maximize the number of the successfully served UEs under the latency constraint, we define the reward $R^{t+1}$ as \begin{align}\label{reward} R^{t+1}=V_{sd}^t, \end{align} where $V_{sd}^t$ is the observed number of successfully served UEs under the latency constraint $T_{\rm cons}$. To select an action $A^t$ based on the current state $S^t$, a mapping policy $\pi(a|s)$ learned from a state-action value function $Q(s, a)$ is needed to facilitate the action selection process, which indicates probability distribution of actions with given states. Accordingly, our objective is to find an optimal value function $Q^*(s, a)$ with optimal policy $\pi^*(a|s)$. At each RTT, $Q(s, a)$ is updated based on the received reward by following \begin{align}\label{Qtable1} Q(S^t,A^t)= Q(S^t,A^t)+\lambda[R^{t+1}+\gamma \mathop {\max }\limits_{a \in {\cal A}} Q(S^{t+1},a)-Q(S^{t},A^t) ], \end{align} where $\lambda$ is a constant learning rate reflecting how fast the model adapting to the problem, $\gamma \in [0, 1)$ is the discount rate that determines how current rewards affect the value function updating. After enough iterations, the BS can learn the optimal policy that maximizes the long-term rewards. \subsubsection{Deep Q-network} When the state and action spaces are large, the RL algorithm becomes expensive in terms of memory and computation complexity, which is difficult to converge to the optimal solution. To overcome this problem, DQN is proposed in \cite{mnih2015human}, where the Q-learning is combined with DNN to train a sufficiently accurate state-action value function for the problems with high dimensional state space. Furthermore, the DQN algorithm utilizes the experience replay technique to enhance the convergence performance of RL. When updating the DQN algorithm, mini-batch samples are selected randomly from the experience memory as the input of the neural network, which breaks down the correlation among the training samples. In addition, through averaging the selected samples, the distribution of training samples can be smoothed, which avoids the training divergence. In DQN algorithm, the action-state value function $Q(s.a)$ is parameterized via a function $Q(s,a,\bm{\theta})$, where \bm{$\theta$} represents the weights matrix of a multiple layers DNN. We consider the conventional fully-connected DNN, where the neurons between two adjacent layers are fully pairwise connected. The variables in the state $S^t$ is fed in to the DNN as the input; the Rectifier Linear Units (ReLUs) are adopted as intermediate hidden layers by utilizing the function $f(x)=\max\ (0,x)$; while the output layer is consisted of linear units, which are in one-to-one correspondence with all available actions in $\cal A$. To achieve exploitation, the forward propagation of Q-function $Q(s,a,\bm{\theta})$ is performed according to the observed state $S^t$. The online update of weights matrix \bm{$\theta$} is carried out along each training episode to avoid the complexities of eligibility traces, where a double deep Q-learning (DDQN) training principle\cite{van2015deep} is applied to reduce the overestimations of value function (i.e., sub-optimal actions obtain higher values than the optimal action). Accordingly, learning takes place over multiple training episodes, where each episode consists of several RTT periods. In each RTT, the parameter $\bm{\theta}$ of the Q-function approximator $Q(s,a,\bm{\theta})$ is updated using RMSProp optimizer\cite{tieleman2012lecture} as \begin{align}\label{RMS} {\bm{\theta} ^{t + 1}} = {\bm{\theta} ^{t}} - {\lambda _{\mathrm{RMS}}}\nabla {L^{\mathrm{DDQN}}}({\bm{\theta} ^t}) \end{align} where $\lambda _{\mathrm{RMS}} \in (0,1]$ is RMSProp learning rate, $\nabla {L^{\mathrm{DDQN}}}({\bm{\theta}^t})$ is the gradient of the loss function ${L^{\mathrm{DDQN}}}({\bm{\theta} ^t})$ used to train the state-action value function. The gradient of the loss function is defined as \begin{align}\label{approximator} \nabla {L^{\mathrm{DDQN}}}({\bm{\theta}^t}) = {{\rm E}_{{S^i},{A^i},{R^{i + 1}},{S^{i + 1}}}}[({R^{i + 1}} + \gamma \mathop {\mathop {\max }\limits_{a \in {\cal A}} \ Q({S^{i + 1}},a,{{\bar {\bm{\theta}} }^t})} - Q({S^i},{A^i},{\bm{\theta} ^t})){\nabla _{\bm{\theta}} }Q({S^i},{A^i},{{\bm{\theta}} ^t})]. \end{align} We consider the application of minibatch training, instead of a single sample, to update the value function $Q(s,a,\bm{\theta})$, which improves the convergent reliability of value function $Q(s,a,\bm{\theta})$. Therefore, the expectation is taken over the minibatch, which are randomly selected from previous samples $(S_i, A_i, S_{i+1}, R_{i+1})$ for $i \in \{t-M_r,...,t\}$ with $M_r$ being the replay memory size\cite{sutton2018reinforcement}. When $t-M_r$ is negative, it represents to include samples from the previous episode. Furthermore, $\bar {\bm{\theta}}^t$ is the target Q-network in DDQN that is used to estimate the future value of the Q-function in the update rule, and $\bar {\bm{\theta}}^t$ is periodically copied from the current value $ {\bm{\theta}}^t$ and kept unchanged for several episodes. Through calculating the expectation of the selected previous samples in minibatch and updating the ${\bm{\theta} ^{t}}$ by \eqref{RMS}, the DQN value function $Q(s,a,\bm{\theta})$ can be obtained. The detailed DQN algorithm is presented in \textbf{Algorithm 1.} \begin{figure}[htbp!] \label{DQN} \renewcommand{\algorithmicrequire}{\textbf{Input:}} \renewcommand{\algorithmicensure}{\textbf{Output:}} \begin{algorithm}[H] \caption{DQN Based GF-NOMA Uplink Resource Configuration \LinesNumbered \KwIn{The set of repetition values in each RTT $K$ and Operation Iteration I. Algorithm hyperparameters: learning rate $\lambda_{RMS} \in (0, 1])$, discount rate $\gamma \in [0, 1) $, $\epsilon$-greedy rate $\epsilon \in (0, 1]$, target network update frequency $K$; Initialization of replay memory $M$ to capacity $D$, the state-action value function $Q(S,A,{\bm\theta})$, the parameters of primary Q-network $\bm\theta$, and the target Q-network $\bm{\bar \theta}$; \For{Iteration $\leftarrow$ 1 to I}{ Initialization of $S^1$ by executing a random action $A^0$ and bursty traffic arrival rate $\mu^0=0$; \For {t $\leftarrow$ 1 to T}{ Update $\mu^0$ using Eq. (2); \textbf{if} {$p_\epsilon <\epsilon$} \textbf{Then} select a random action $A^t$ from $\cal A$; \textbf{else} select ${A^t} = \mathop {\arg \max }\limits_{a \in A} Q({S^t},a,\bm\theta )$. The BS broadcasts $K(A^t)$ and backlogged UEs attempt communication in the $t$th RTT; The BS observes state $S^{t+1}$, and calculate the related reward $R^{t+1}$ using Eq. (15); Store transition $(S^t, A^t, R^{t+1}, S^{t+1})$ in replay memory $M$; Sample random minibatch of transitions $(S^t, A^t, R^{t+1}, S^{t+1})$ from replay memory $M$ Perform a gradient descent step and update parameters $\bm\theta$ for $Q(s,a,{\bm\theta})$ using Eq. (18); Update the parameter $\bm{\bar\theta}=\bm{\theta}$ of the target Q-network every $J$ steps. } } \end{algorithm} \end{figure} \begin{figure}[htbp!] \subfigure {\includegraphics[width=5.9in,height=3.4in]{DQN.pdf}} \caption{The CMA-DQN agents and environment interaction in the POMDP.} \label{fig:9} \end{figure} \subsection{Cooperative Multi-Agent Learning-based multi-parameter optimization} In practice, not only the repetition values but also the CTU numbers, influence reliability-latency performance in GF-NOMA. Fixed CTU numbers cannot adapt to the dynamics of the random traffic, which may violate the stringent latency requirement or lead to low resource efficiency. Thus, we study the problem (P1) of jointly optimizing the resource configuration with parameters $A^t=\{K^t, C^t\}$ to improve the network performance. The learning algorithm provided in Sec. V.A is model-free, and thus the learning structure can be extended in this multi-parameter scenario. Due to the high capability of DQN to handle problems with massive state spaces, we consider to improve the state spaces with more observed information to support the optimization of RL-agent. Therefore, we define the current state $S^t$, to include information about the last $M_o$ RTTs $(U^{t-1}, U^{t-2}, U^{t-3}, ... , U^{t-M_o} )$, which enables the RL-agent to estimate the trend of traffic. Similar to the state spaces, the available action spaces also exponentially increases with the increment of the adjustable parameter configurations in GF-NOMA. The total number of available actions corresponds to the possible combinations of all parameter configurations. Although the GF-NOMA configuration is managed by a central BS, breaking down the control of multiple parameters as multiple sub-tasks is sufficient to deal with the problems with unsolvable action space, which are cooperatively handled by independent Q-agents. As shown in Fig.~\ref{fig:9}, we consider multiple DQN agents that are centralized at the BS following the same structure of value function approximator as Sec. V.A. Each DQN agent controls their own action variable, namely $K^t$ or $C^t$, and receives a common reward to guarantee the objective in P1 cooperatively. However, the common reward design also poses challenge on the evaluation of each action, because the individual effect of specific action is deeply hidden in the effects of the actions taken by all other DQN agents. For instance, a positive action taken by a agent can receive a misleading low reward due to other DQN agents’ negative actions. Fortunately, in GF-NOMA scenario, all DQN agents are centralized at the BS and share full information among each other. Accordingly, we include the action selection histories of each DQN agent as part of state function, and hence, the agents are able to learn the relationship between the common reward and different combinations of actions. To do so, we define state variable $S^t$ as \begin{align}\label{Statevariable} {{S ^{t}}} = [A^{t-1}, U^{t-1}, A^{t-2}, U^{t-2}, ..., A^{t-M_{o}}, U^{t-M_{o}}], \end{align} where $M_{o}$ is the number of stored observations, $A^{t-1}$ is the set of selected action of each DQN agent in the $(t-1)$th TTI corresponding to $K^{t-1}$, and $C^{t-1}$, and $U^{t-1}$ is the set of observed transmission receptions. In each RTT, the $k$th agent update the parameters ${\bm\theta}_k$ of the value function $Q(s,a_{k},\bm{\theta}_{k})$ using RMSProp optimizer following Eq. \eqref{RMS}. The learning algorithm can be implemented following \textbf{Algorithm 1}. Different from the GF NOMA single-parameter configuration scenario in Section III.A, it is required to initialize two primary networks ${\bm\theta}_k$, target networks ${\bar{{\bm\theta}}_k}$ and the replay memories $M_k$ for each DQN agent. In step 10 of \textbf{Algorithm 1}, each agent stores their own current transactions in memory separately. In step 11 and 12 of \textbf{Algorithm 1}, the minibatch of transaction should separately be sampled from individual memory to train the corresponding DQN agent. \section{Simulation Results} In this section, we examine the effectiveness of our proposed GF-NOMA schemes with DQN algorithm via simulation and compare the results with LE-URC. We adopt the standard network parameters listed in Table I following\cite{2Tel2018}, and hyperparameters for the DQN learning algorithm are listed in Table II. \begin{table}[htbp!] \centering \caption{Simulation Parameters} {\renewcommand{\arraystretch}{1.1} { \begin{tabular}{|p{5cm}|p{2cm}|p{5cm}|p{2cm}|} \hline Parameters & Value & Parameters & Value \\ \hline Path-loss exponent $\eta$ & 4 & Noise power $\sigma^2$ & -132 dBm \\ \hline Transmission power $P$ & 23 dBm & The received SINR threshold $\gamma_{th}$ & -10 dB \\ \hline Duration of traffic $T$ & 2 s & The set of the repetition value & $\{1, 2, 4, 6, 8\}$\\ \hline The set of the CTU number & $\{12, 24, 36, 48\}$ & Latency constraint & 2 ms and 8 ms \\ \hline Bursty traffic parameter Beta($\alpha$,$\beta$)& (2, 4) & The number of bursty UEs $N$ & 20000 \\ \hline Cell radius & 10 km & Duration of one TTI & 0.125 ms \\ \hline \end{tabular} } } \label{table_accord} \end{table} \begin{table}[htbp!] \centering \caption{Learning Hyperparameters} {\renewcommand{\arraystretch}{1.1} { \begin{tabular}{|p{5cm}|p{2cm}|p{5cm}|p{2cm}|} \hline Hyperparameters & Value & Hyperparameters & Value \\ \hline Learning rate $\lambda_{RMS}$ &0.0001 & Minimum exploration rate $\epsilon$ & 0.1 \\ \hline Discount rate $\gamma$ & 0.5 & Minibatch size & 32 \\ \hline Replay Memory & 10000 & Target Q-network update frequency & 1000\\ \hline \end{tabular} } } \label{table_accord} \end{table} All testing performance results are obtained by averaging over 1000 episodes. The BS is located at the center of a circular area with a 10 km radius, and the UEs are randomly located within the cell. Unless otherwise stated, we consider the number of bursty UEs to be $N=20000$. The DQN is set with two hidden layers, each with 128 ReLU units. In the following, we present our simulation results of the single-repetition configuration and the multi-parameter configuration in Section V-A and Section V-B, respectively. The single-repetition configuration is optimized under the latency constraint ${T_{\rm cons}}=2$ ms and the multi-parameter configuration is optimized under the latency constraint ${T_{\rm cons}}=8$ ms, respectively. \subsection{Single-repetition configuration} In the single-repetition configuration scenario, we set the number of CTU as $C$ = 48. Throughout epoch, each UE has a periodical a bursty traffic profile (i.e., the time limited Beta profile defined in \eqref{beta} with parameters (2, 4) that has a peak around the 4000th TTI. \begin{figure}[htbp!] \centering \includegraphics[width=2.8in,height=2.1in]{traffic.pdf} \caption{Backlog traffic in each TTI under latency constraint $T_{\rm cons}=2$ ms and $T_{\rm cons}=8$ ms. } \label{fig:10} \end{figure} Fig.~\ref{fig:10} plots the backlog traffic in each TTI under latency constraint $T_{\rm cons}=2$ ms and $T_{\rm cons}=8$ ms, respectively. It should be noted that the the backlog traffic in each TTI does not only include the newly generated traffic, but also the retransmission traffic, due to the fact that the UEs are allowed to retransmit in the next RTT under the latency constraint. The results have shown that when the latency constraint increases, the backlog traffic in each TTI increase as the retransmission traffic increases. The backlog traffic in each TTI for the Proactive scheme is smaller than that of the K-repetition scheme due to the efficiency of the Proactive scheme, which has been analyzed in details in the following. \begin{figure}[htbp!] \centering \subfigure[K-repetition scheme] {\includegraphics[width=2.7in,height=2.1in]{krepe_reward.pdf}} \subfigure[Proactive scheme] {\includegraphics[width=2.7in,height=2.1in]{reward.pdf}} \caption{Average received reward for each GF scheme.} \label{fig:12} \end{figure} Fig.~\ref{fig:12} plots the average received reward for the K-repetition scheme and the Proactive scheme, respectively. It can be seen that the average rewards of both K-repetition and proactive schemes converge to the optimal value after training. We can also observe that the average received reward of proactive scheme in Fig.~\ref{fig:12} (b) is higher than that of the K-repetition scheme in Fig.~\ref{fig:12} (a). This is because the proactive scheme can terminate the repetition earlier and start new packet transmission with timely ACK feedback, which is able to deal with the traffic more effectively. \begin{figure}[htbp!] \centering {\subfigure[K-repetition scheme] {\includegraphics[width=3.0in,height=2.1in]{KREPE_TTI1.pdf}} \subfigure[Proactive scheme] {\includegraphics[width=3.0in,height=2.1in]{roa_TTIP.pdf}}} \caption{The transmission results for each GF scheme.} \label{fig:11} \end{figure} Fig.~\ref{fig:11} plots the number of the successfully served UEs, the non-collision UEs, the collision UEs, and the decoding failure UEs for the K-repetition scheme and the Proactive scheme respectively, under latency constraint $T_{\rm cons}=2$ ms. It is shown that the number of successfully served UEs achieved under latency constraint for the Proactive scheme is almost up to 1.5 times more than that for the K-repetition scheme. This is due to that the UEs in the Proactive scheme can terminate their repetitions earlier to reduce the interference to other UEs, which leads to an increase in the number of successfully decoding UEs. In both Fig.~\ref{fig:11} (a) and Fig.~\ref{fig:11} (b), the number of collision UEs has a peak at around the 4000th TTI with the peak traffic at this time as shown in Fig.~\ref{fig:10}. Due to the fact that only the non-collision UEs can be detected by the UE to decoding their data, the number of successful UEs depends on the number of the non-collision UEs. In addition, the number of failure decoding UEs reaches a peak due to the peak traffic at the 4000th TTI, which leads to the decrease in the number of successful UEs at that time. \subsection{Multi-parameter configuration including the repetition values and the CTU number} \begin{figure}[htbp!] \centering \subfigure[K-repetition scheme] {\includegraphics[width=2.8in,height=2.1in]{k_reward.pdf}} \subfigure[Proactive scheme] {\includegraphics[width=2.8in,height=2.1in]{reward_p.pdf}} \caption{Average received reward for each GF scheme with multi-parameter configuration.} \label{fig:14} \end{figure} Fig.~\ref{fig:14} plots the average received reward for the K-repetition scheme and the Proactive scheme with multi-parameter configuration, including the repetition values and the CTU number, respectively. It can be seen that both the average received rewards of the K-repetition and the Proactive scheme converge to a optimal value after training. Compared to Fig.~\ref{fig:12} under latency constraint $T_{\rm cons}=$2 ms, we observe that the average received reward of two schemes decrease significantly. This is because the larger latency constraint $T_{\rm cons}=8$ ms leads to larger retransmission packets, which results in serious traffic congestion. It is noted that the performance degradation of K-repetition scheme is much larger than that of Proactive scheme, which shows the potential of the Proactive scheme in heavy traffic and long latency constraint situation due to timely termination. \begin{figure}[htbp!] \centering \subfigure[K-repetition scheme] {\includegraphics[width=2.8in,height=2.1in]{multi_kre_success.pdf}} \subfigure[Proactive scheme] {\includegraphics[width=2.8in,height=2.1in]{multi_pro_success.pdf}} \caption{The transmission results for each GF scheme.} \label{fig:13} \end{figure} Fig.~\ref{fig:13} plots the number of successful UEs, non-collision UEs, and decoding failure UEs for K-repetition scheme and Proactive scheme with multi-parameter configuration including the repetition values and the CTU number under latency constraint $T_{\rm cons}=8$ ms, respectively. We have observed that the number of non-collision transmission UEs of both scheme is similar. However, the number of decoding failure UEs of the K-repetition scheme is almost up to five times more than that of the Proactive scheme at the peak traffic, due to the interference caused by multiple repetitions from collision UEs as Fig.~\ref{fig:15}. It is also noted that in both schemes, there is lower number of success UEs in high traffic, especially in peak traffic at round 4000th TTI. \begin{figure}[htbp!] \centering \subfigure[K-repetition scheme] {\includegraphics[width=2.8in,height=2.1in]{compaer_krepe.pdf}} \subfigure[Proactive scheme] {\includegraphics[width=2.8in,height=2.1in]{compaer_PROA.pdf}} \caption{Average number of successfully served UEs for each GF scheme} \label{fig:16} \end{figure} Fig.~\ref{fig:16} plots the average number of successful UEs for the K-repetition scheme and the Proactive scheme by comparing the learning framework with fixed parameters, and with the LE-URC approach, respectively. Here, we set the fixed repetition value $K=8$ and the CTU number $C=48$. Our results shown that the number of successfully served UEs under the same latency constraint in our proposed learning framework is up to ten times for the K-repetition scheme, and two times for the Proactive scheme, more than that with fixed repetition values and CTU numbers, respectively. In addition, since the LE-URC approach does not aware of the latency constraint and SIC procedure, the results are large at first, but still smaller than the number of non-collision UEs of CMA-DQN. However, with increasing TTIs (above 6000), the cumulated traffic increases due to unsuccessful transmissions and retransmissions, the LE-URC method becomes worse and achieve lower number of successful UEs than that of CMA-DQN due to its ignorance in latency constraint during its optimization for one time instance. The superior performance of CMA-DQN in heavy traffic scenario also demonstrate its capability in dynamically configure lower lower repetition values and CTU numbers to alleviate the traffic congestion to obtain a long-term reward. \begin{figure}[htbp!] \centering \subfigure[K-repetition scheme] {\includegraphics[width=2.6in,height=2.3in]{repe_k.pdf}} \subfigure[Proactive scheme] {\includegraphics[width=2.6in,height=2.3in]{proc_k.pdf}} \caption{Actions for each GF scheme.} \label{fig:15} \end{figure} Fig.~\ref{fig:15} plots the average number $K$ of repetition values and the average number $C$ of CTUs for each scheme that are selected by CMA-DQN and LE-URC, respectively. In Fig.~\ref{fig:15} (a), we can see that the repetition value of K-repetition scheme decreases first and then increases back to a higher value. This is because the agent in K-repetition scheme learns to sacrifice the current successful transmission to alleviate the traffic congestion in heavy traffic region to obtain a long-term reward, while LE-URC approach just adopts the maximum repetition value to optimize for one time instance. In Fig.~\ref{fig:15} (b), we can see that the Proactive scheme adopts a higher and more stable repetition value due to its capability to deal with the traffic congestion. In Fig.~\ref{fig:15} (a)(b), it can be seen that the number of CTUs has a similar trend as the repetition value, which may be caused by the sharing of actions as observations among agents. \section{Conclusion} In this paper, we developed a general learning framework for dynamic resource configuration optimization in signature-based GF-NOMA systems, including the sparse code multiple access (SCMA), multiuser shared access (MUSA), pattern division multiple access (PDMA), and etc, for mURLLC service under the K-repetition GF scheme and the Proactive GF scheme. This general learning framework was designed to optimize the number of successfully served UEs under the latency constraint via adaptively configuring the uplink resources, including the repetition values and the contention-transmission unit (CTU) numbers. We first performed a real-time repetition value configuration for the two schemes, where a double Deep Q-Network (DDQN) was developed. We then designed a Cooperative Multi-Agent learning technique based on the DQN (CMA-DQN) to optimize the configuration of both the repetition values and the CTU numbers for these two schemes, by dividing high-dimensional configurations into multiple parallel sub-tasks. Our results have shown that: 1) the number of successfully served UEs under the same latency constraint in our proposed learning framework is up to ten times for the K-repetition scheme, and two times for the Proactive scheme, more than that with fixed repetition values and CTU numbers; 2) with learning optimization, the Proactive scheme always outperforms the K-repetition scheme in terms of the number of successfully served UEs, especially under the long latency constraint; 3) the proposed CMA-DQN is superior to the conventional load estimation-based approach (LE-URC) that demonstrating its capability in dynamically configuring in long term; 4) the proposed learning framework is general and can be used to optimize the resource configuration problems in all the signature-based GF-NOMA schemes; and 5) determining the retransmission or not can be optimized in the future by considering not only the long latency constraint but also the future traffic congestion, due to the fact that the long latency constraint will lead to high future traffic congestion. \ifCLASSOPTIONcaptionsoff \newpage \fi \bibliographystyle{IEEEtran}
{'timestamp': '2021-03-29T02:05:01', 'yymm': '2101', 'arxiv_id': '2101.00515', 'language': 'en', 'url': 'https://arxiv.org/abs/2101.00515'}
arxiv
\section{Introduction}\label{sec:intro} Among the draft \textit{Ethics Guidelines for Trustworthy AI} released by the European Union in 2019 were calls for greater transparency around deployed systems using artificial intelligence, advising that an ``AI system’s capabilities and limitations should be communicated to practitioners or end-users in a manner appropriate to the use case at hand.'' \cite{ec2019ethics} This is a high-profile example of the vagueness endemic to guidance on ethical disclosure and AI---\textit{what constitutes an appropriate manner of communication}? There is a growing awareness of the importance of communicating AI system function and performance clearly and understandably. This is both a matter of public interest, for mitigating harms caused by, for example, racial biases in the performance of human classifiers \cite{raji2019actionable}, but also in the interest of system providers, as users who feel like they do not understand how machine learning models work and what kind of information they rely on tend to be more resistant to using them \cite{poursabzi2018manipulating}. However, while fairness \cite{pmlr-v81-dwork18a, harrison_empirical_2020} and privacy as general principles \cite{ji2014differential, papernot2016towards} have been well-studied in the context of AI, transparency does not receive as much attention. The term \textit{transparency} is overloaded \cite{lipton2019research}, with many different definitions in the literature \cite{felzmann_robots_2019}. It has a broad meaning in the public consciousness, from which some studies adopt a ``you'll know it when you see it'' definition \cite{doshi2017towards}. As opposed to the notions of \textit{transparency as explainability} \cite{veale_2018_fairness} and \textit{as invisibility} \cite{hamilton_path_2014}, \textit{transparency as disclosure} \cite{suzor_what_2019}, the extent to which the producers of an AI system or service provide detailed messaging about a system to stakeholders such as buyers, users, or the general public. This third sense, \textit{\textbf{disclosive transparency}}, is particularly subjective. \citet{pieters2011explanation} identifies a confusion dynamic where providing ``too much information'' about a decision system worsens user understanding and trust. This dynamic could have serious ramifications---if disclosive transparency really decreases user trust, stakeholders are further incentivized to not disclose. Unfortunately, studies on this relationship are small-scale and subjective. This is why measurable, repeatable, and objective measures of disclosive transparency are sorely needed. In this work, we \textbf{decompose disclosive transparency} into two components: \textit{replicability} and \textit{style-appropriateness}, \textbf{develop three objective neural language model measures} of them, and apply them in a \textbf{pilot study of real systems}\footnote{All code, data, and annotations are available online at \texttt{ \href{https://github.com/michaelsaxon/disclosive-transparency}{github.com/michaelsaxon/disclosive-transparency}}.}. \section{Decomposing Disclosive Transparency} Our goal is to develop an objective measure of disclosive transparency that is repeatable, explainable, intuitive, and well-correlated with subjective opinions. However, at face value there is not an obvious way to assign a numerical value to the ``level of transparency'' in a description. To resolve some vagueness, we decompose disclosive transparency into two components: the \textbf{replicability}, or degree to which the requisite content to reproduce the system being described is present in a description, and the \textbf{style-appropriateness}, or the degree to which it is written in a manner understandable to a member of the general public. These components are more specific than ``transparency'' alone, but still quite subjective. \begin{comment} \begin{enumerate} \item The \textit{Replication Room}, a thought experiment for developing a principled theory of disclosive transparency. \item Replication Room-inspired objective disclosive transparency metrics derived from neural language models. \item A precise set of questions that capture dimensions of Replication Room-style disclosive transparency, enabling the assessment of user attitudes. \item A user study analyzing the relationship between disclosive transparency in and user opinions toward real NLP system demonstration descriptions. \end{enumerate} \end{comment} A key insight underpins the possibility of developing objective measures of replicability and style-appropriateness: \textbf{disclosure is a communication task}. In describing a system, an explainer, typically an authority providing an AI service to the public, attempts to encode information about the design and function of their system in a \textit{summary}. We find the communication-based definition of meaning provided in \citet{bender-koller-2020-climbing} useful for motivation. In their framework, the \textit{meaning}, $m$ of an utterance is a pair $(e, i)$ of the surface form $e$ (such as text or speech audio) and \textit{communicative intent}, $i$ which is external to language. In the case of disclosive transparency, this $i$ is the particulars of the system being described. Any assessment of the disclosive transparency of a description $e$ is fundamentally an assessment of its underlying $i$---the degree to which $i$ contains the information necessary to reconstruct the system being described. Furthermore, \textbf{some short descriptions come paired with longer ones}. Anyone who has clicked ``I Agree'' without reading a terms of service, but has taken the time to look over a short, to-the-point statement on how data is used, knows that the lengthy legalese-laden descriptions that truly define systems we interact with can be sufficiently summarized succinctly. However, the succinct summarization is intended to carry the detailed meaning of the actual contract a user is agreeing to. In other words, for the short description $e'$ of an agreement, there exists a `source' document $e$ that is much more detailed, which share a common $i$. An analogue in system descriptions is what enables our metrics. \section{Objective Transparency Metrics} \begin{figure}[t] \centering \includegraphics[width=\linewidth]{Fig/Method_final.pdf} \caption{A diagram of our proposed method for extracting the \textit{style-appropriateness} and \textit{replicability} objective features to characterize disclosive transparency. } \label{fig:method} \end{figure} We now move to developing usable metrics that quantify both the replicability and style-appropriateness of real system descriptions. The system demonstration tracks at academic AI conferences represent a good source of real-world system descriptions. Ideally, the purpose of a system demonstration paper at an academic AI venue is to provide a sufficiently detailed system description such that a peer could (given sufficient resources and data) replicate it. Each of these lengthy documents, $e_i$, is accompanied by an abstract, $e'_i$ which briefly describes the system. Although these abstracts are not intended for consumption by the general public, they do succinctly describe implemented systems, some of which are intended to (at least hypothetically) be used by the public. Combined with the fact that these paper/abstract pairs are freely available online, these are an appealing subject of study for modeling disclosive transparency. Details on our pilot study using demo track NLP papers is provided in \autoref{sec:study}. \autoref{fig:method} provides a high-level depiction of our objective disclosive transparency metrics, the \textit{style-appropriateness} `clarity' metric $C(e)$, and the \textit{replicability metrics} of `sentence affinity' $R_A(e', e)$ and simulated `information recovery ratio' $R_R(e',e)$. We assess these features using language model scores derived from GPT-2 \cite{radford2019language} and BERT \cite{devlin2018bert}. For fine-tuning data on academic language in AI and CS, we produce a training dataset by crawling a random sample of 100k \LaTeX\space files from the arXiv preprint repository with topic label cs.* from 2007-2020. Additionally, we further collect all 30k crawlable \LaTeX\space files from the cs.CL label from 2017-2020, to adequately sample recent research in natural language processing and computational linguistics. From these raw \texttt{.tex} files we produce task-specific plaintext training corpora as described in Appendix C. We then fine-tune the GPT-2 regular pretrained model from Huggingface \cite{wolf2020transformers} on the corpora as explained below. We manually exclude all papers used in our downstream case study from pretraining. \begin{figure*}[t!] \centering \includegraphics[width=\linewidth]{Fig/tabuoid_ex-2.pdf} \caption{A demonstration of how our \textit{sentence affinity} curve simulates the replicability of the abstract based on the degree to which it ``covers'' the content of the full article. For each line in the source document, the maximum pairwise BERTscore between it and the sentences in the short system description is measured. The affinity-replicability score of the article is the paper length-normalized area under this curve.} \label{fig:abs} \end{figure*} \subsection{Modeling Replicability} When discussing system descriptions, replicability typically refers to the ability of a third party to implement a functionally equivalent replacement system from a description. Rather than automate replication itself, we use the process of \textit{recovering the full text of the system description from the abstract} as a proxy for replicability. As we established previously, a reasonable assumption for the communicative goal $i$ of an author of an academic paper $e$ describing a system is to transmit the information necessary to reconstruct it. Obviously, it is not generally possible to perfectly recover $i$ from $e'$ or academic papers beyond the abstract would be generally superfluous. The problem of generalized inversion of communicative intent $i$ from form $e$ is yet unsolved \cite{yogatama2019learning}. So, we treat recovery of $e$ from a short summary $e'$ as a proxy for recovering $i$, reconstructing the system. In other words, \textbf{the replicability of an abstract $e'$ can be modeled as the amount of information contained in the full article text $e$ than can be recovered from $e'$}. We propose two metrics to simulate this process using the document $e$ and abstract $e'$; \textit{trigram information recovery} and \textit{sentence affinity}. \subsubsection{Trigram recovery} We directly attempt the recovery of $e$ from $e'$ using a generative language model (in this case, GPT-2 \cite{radford2019language}) fine-tuned on a \textit{full-text recovery task}, where for each abstract the replicability score is the rate of trigram information in $e$ recovered by the model-generated text. The model generates predicted sentences $e_g$ from the full paper conditioned on an abstract. Given promising results on quantifying semantic complexity using simple measures such as n-gram entropy \cite{mckenna2020semantic}, we use a trigram self-information content metric to measure the amount of information content in $e'$ that is recovered in $e_g$. Using the training dataset global trigram distribution, we take the ratio of the trigram self-information of all trigrams present in $e_g$ that were recovered from $e$ against the total trigram self-information of $e$. This gives us a ratio of recovered form information $R$ as defined in \autoref{eqn:R}: \begin{equation}\label{eqn:R} R_R(e, e_g) = \frac{\sum_{t\in e_{g} \cap e} \log(p(t))}{\sum_{t\in e} \log(p(t))} \end{equation} \subsubsection{Sentence affinity} Using the aforementioned trigram recovery metric to model replicability has risks. The distribution of source papers could be too specific, and not contain requisite information, or the generated output might be too noisy to meaningfully simulate the process of inverting system from abstract. Thus, we present an alternative approach here. \citet{zhang2019bertscore} presented a method for evaluating the similarity of sentence pairs called BERTscore, which is computed by averaging a greedy match of the cosine similarities of the BERT \cite{devlin2018bert} token embeddings $\textbf{b}(t)$ for each token in a pair of sentences: \begin{equation} P_\text{BERT}(s_1,s_2) = \frac{1}{|s_1|}\sum_{t_i\in s_1}(\max_{t_j \in s_2}(\textbf{b}(t_i)^T\textbf{b}(t_j)) \end{equation} We propose extending this to match a sentence over a set of sentences in a document to produce a document-level \textit{affinity score}, \begin{equation} R_A(e_1, e_2) = \frac{1}{|e_1|}\sum_{s_1\in e_1}\max_{s_2 \in e_2}(P_\text{BERT}(s_1, s_2)) \end{equation} This metric has advantages over trigram recovery in that it doesn't rely on training a generative language model, and is more readily interpretable, as \autoref{fig:abs} demonstrates. \subsection{Modeling Style-appropriateness} Orthogonal to the question of whether an abstract contains the necessary information to perform a replication is the question of \textbf{who would be capable of performing the replication}. This question is important for assessing the appropriateness of a description to layperson audiences. We simulate this with a pair of language models tuned to two styles of writing---one general interest, one scientific---to make a perceptual model of ``academic style,'' as a layperson would probably require many more textbook lookups to understand an academic paper or detailed terms of service than they would reading a Wikipedia article. This approach is analogous to a popular the use of perceptual likelihood ratios in speech processing, which have been shown to correlate well with subjective perceptual opinions \cite{saxon2020robust}. For each passage we extract a likelihood ratio between two language models, one a GPT-2 model fine-tuned on the 100k file arXiv corpus, the other the vanilla GPT-2 model that is pretrained on a large, diverse corpus of online English text. Given the system demo abstract $e$, we compute the style-appropriateness $C$ as a log-likelihood ratio that it belongs to this academia-specific distribution $A$ or a general public distribution $V$ as follows: \begin{equation}\label{eqn:C} C(e) = - \sum_{j=1}^{|\{t|t\in e\}|} \log\left(\frac{p(t_j|A, t_{j-1}...t_1)}{p(t_j|V, t_{j-1}...t_1)}\right) \\ \end{equation} \section{Pilot Studies} \label{sec:study} To analyze how well our objective measures track with subjective notions of transparency, and to demonstrate how they might be used to investigate how transparency affects prospective user opinions in the real world, we perform two pilot studies utilizing our metrics and a corpus of real-world AI system descriptions. \subsection{*ACL System Demo Corpus} We extract system demonstration abstracts from EMNLP 2017--2020, ACL 2018--2020, and NAACL 2018 and 2019, retrieving a corpus of 268 abstracts describing a variety of demonstrations, including systems intended for use by the general public (e.g., translation systems, newsreaders) as well as demonstrations that are of interest more narrowly to the NLP community, software developers, or academics at large (e.g., toolkits, packages, or benchmarks). As we are interested in system descriptions for non-experts, \textbf{we restrict our analysis to abstracts which describe systems intended for use by laypeople}. This set contains 55 abstracts, describing diverse systems from automated language learning games, to news aggregators, to specialized search engines for medical topics. \begin{comment} \begin{figure}[t] \centering \begin{mdframed} \small This paper proposes the building of Xiaomingbot, an intelligent, multilingual and multimodal software robot equipped with four integral capabilities: news generation, news translation, news reading and avatar animation. Its system summarizes Chinese news that it automatically generates from data tables. Next, it translates the summary or the full article into multiple languages, and reads the multilingual rendition through synthesized speech. Notably, Xiaomingbot utilizes a voice cloning technology to synthesize the speech trained from a real person's voice data in one input language. The proposed system enjoys several merits: it has an animated avatar, and is able to generate and read multilingual news. Since it was put into practice, Xiaomingbot has written over 600,000 articles, and gained over 150,000 followers on social media platforms. \end{mdframed} \caption{One \cite{xu2020xiaomingbot} of the 55 EMNLP, ACL, and NAACL demonstration abstracts used in our study.} \label{fig:abs} \end{figure} \end{comment} We first collect expert opinions on how the abstracts conform to the aforementioned dimensions of transparency to analyze the quality of our automated metrics. Then, we collect salient layperson opinions of trust, understanding, and fairness to demonstrate a pilot study of how transparency drives user attitudes. \subsection{Connecting Objective with Subjective}\label{sec:dims} Our first pilot study seeks to determine the extent to which our objective measures faithfully model experts' subjective notions of transparency. To do this we must first pose a set of precise questions for subjectively assessing disclosive transparency. We identify three largely disjoint \textit{dimensions of disclosive transparency} that each follow directly from a key question an implementer might ask when initially trying to understand a description: \paragraph{Task Transp.:} What task does this system solve? \paragraph{Function Transp.:} What components does this system contain, and how do they work? \paragraph{Data Transp.:} What are the inputs and outputs of this system? What kind of data collection and storage is required to train and operate it? \paragraph{} Each of these questions concerns some kind of information contained in $i$. They can be posed as survey questions by appending ``to what extent does the description explain...'' to the start. We consider \textbf{task} transparency interesting because members of the general public are often learning of new system application areas in which emerging technologies such as NLP can be applied, and without communicating the parameters of the task a system is solving clearly, users cannot understand it. \textbf{Function} transparency is perhaps the most natural dimension, as discussing the ``how'' of a system is fundamental to explaining how it works. Finally, we consider \textbf{data} transparency because many public discussions of AI ethics center on the use and misuse of data, and it is a central focus of regulatory discussions of AI. \subsubsection{Collecting the Subjective Ratings} Four NLP Ph.D. students provided five-point Likert opinion scores of the task, function, and data transparency levels for each abstract in the *ACL Corpus. To ensure consistency across the raters we analyzed average abstract-wise variance, as well as the average pairwise inter-rater Pearson correlation coefficient (PCC) and \textit{p}-value for each of the three transparency categories. \autoref{tab:irr} demonstrates the high inter-rater reliability of the scores, with each average variance $<0.55$ on the 5-point scale. \begin{table}[t] \centering \small \begin{tabular}{lccc} \hline \textbf{Transparency} & \textbf{Variance} & \textbf{PCC} & \textbf{\textit{p}}\\ \hline Task & 0.428 & 0.508 & 0.001 \\ Function & 0.506 & 0.319 & 0.085\\ Data & 0.488 & 0.368 & 0.016\\\hline \end{tabular} \caption{Inter-rater reliability assessed using variance, average pairwise Pearson's correlation coefficient (PCC) and \textit{p}-value for subjective transparency scores.}\label{tab:irr} \end{table} Each abstract in the dataset is assigned subjective task, function, and data transparency scores by averaging the four opinion ratings. \subsection{Pilot Study of User Attitudes} In this section we briefly outline how we assess user opinions regarding the system descriptions. Starting from the aforementioned dimensions of transparency---task, function, and data---we find three sets of user concerns orthogonal to these dimensions. These are ``understanding,'' ``fairness,'' and ``trust.'' Together these form ``user response variables'' such as task understanding, function fairness, or data trust, which can be posed as questions about what the user believes or understands. To measure how user attitudes and confusion correlate with description transparency, we simulate a user survey study using Amazon Mechanical Turk (AMT). Each abstract was shown to 10 crowd workers selected from a set of majority English-speaking locales (US, CA, AU, NZ, IE, UK), who were instructed to read the abstract and answer two sets of multiple-choice questions. The first set, \textit{opinion prompts}, consists of five-point Likert scale subjective attitude questions; the second set, of \textit{retention questions}, reveals how well the users can recall phrases from the abstract they just read. See Appendix B for survey methodology details \begin{comment} \begin{figure}[t] \centering \label{fig:bpb} \includegraphics[width=\linewidth]{Fig/boxplots_avg.pdf} \caption{Distributions of the six response variables as box and whisker plots with means (\textcolor{brickred}{$\times$}), minima (\textcolor{darkgreen}{$\blacktriangle$}) and maxima (\textcolor{darkgreen}{$\blacktriangledown$})} \label{fig:retentdist} \end{figure} \end{comment} \section{Results} \begin{figure*}[t] \begin{minipage}{.33\linewidth} \centering \label{subfig:d_f} \subfloat[$\textrm{PCC}=0.309$]{\includegraphics[width=1\linewidth]{Fig/XY/dkl_TFAvg.pdf}} \end{minipage}% \begin{minipage}{.33\linewidth} \centering \label{subfig:d_d} \subfloat[$\textrm{PCC}=0.276$]{\includegraphics[width=1\linewidth]{Fig/XY/dkl_TFAvg-a.pdf}} \end{minipage}% \begin{minipage}{.33\linewidth} \centering \label{subfig:d_g} \subfloat[$\textrm{PCC}=0.279$]{\includegraphics[width=1\linewidth]{Fig/XY/dkl_TDAvg.pdf}} \end{minipage}% \caption{The trigram recovery and sentence-affinity rate \textit{replicability} metrics behave very similarly on modeling expert function transparency opinions. Data transparency opinions are also captured by both metrics with statistically significant correlations.} \label{fig:trigramrec} \end{figure*} To study the correlations both between pairs of subjective variables and between our objective metrics and the subjective responses, we use Pearson's correlation coefficient (PCC). In \autoref{sec:obsub} we study how the objective transparency metrics connect to expert opinion ratings along the three dimensions of transparency identified in \autoref{sec:dims}. These are the results from the first pilot study, testing if our objective metrics capture the subjective notions of disclosive transparency as understood by experts. In \autoref{sec:response} we present the results from the second pilot study, and analyze relationships that appear between our objective transparency metrics, the subjective transparency ratings, and user opinion responses. In particular, we seek to determine if our objective measures can be used as suitable proxy for the subjective expert opinions in modeling user responses to transparency. In this section we have scatter plots containing several overlapping $(x,y)$ coordinates. We opt to represent these points where multiple identical samples are present by varying both marker color and size to convey the relative quantities of repeats. \subsection{Objective vs Subjective Transparency}\label{sec:obsub} \autoref{tab:objsubj} shows the Pearson's correlations and $p$-values for the objective \textit{style-appropriateness} and \textit{replicability} transparency metrics and the subjective expert transparency ratings, and between the objective metrics themselves. \begin{table}[t] \small \centering \begin{tabularx}{0.49\textwidth}{lcccc} \hline \textbf{Objective Metric} & \textbf{Subj. Variable} & \textbf{PCC} & \textbf{\textit{p}} \\ \hline S-A & Task Transp. & 0.366 & 0.006 \\ S-A & Function Transp. & -0.061 & 0.656 \\ S-A & Data Transp. & -0.030 & 0.827 \\ Replicability (TR) & Task Transp. & 0.150 & 0.275 \\ Replicability (TR) & Function Transp. & 0.309 & 0.022 \\ Replicability (TR) & Data Transp. & 0.279 & 0.039 \\ Replicability (AR) & Task Transp. & 0.245 & 0.071 \\ Replicability (AR) & Function Transp. & 0.276 & 0.042 \\ Replicability (AR) & Data Transp. & -0.200 & 0.143 \\ \hline Replicability (TR) & S-A & 0.200 & 0.142 \\ Replicability (AR) & S-A & -0.331 & 0.014 \\ \hline\end{tabularx} \caption{Pairwise analysis of objective style-appropriateness and replicability and expert subjective transparency scores. }\label{tab:objsubj} \end{table} The style-appropriateness (S-A) metric clearly captures information about task transparency, exhibiting a positive statistically significant correlation. However, the S-A metric exhibits no significant trends with data or function transparency. On the other hand, the replicability metric does exhibit statistically significant relationships with clear positive correlations to both function and data transparency, for trigram recovery, and with Function transparency alone for sentence affinity rate; neither exhibit statistically significant relationships with task transparency. Finally, the replicability and S-A metrics do not exhibit a significant correlation with each other. Taken together, these results suggest that \textbf{the replicability and S-A metrics capture subjective notions of transparency}. Furthermore, they capture \textbf{complementary elements} of transparency, exhibiting no significant correlation to each other, while significantly explaining variance in different dimensions of subjective transparency. \autoref{fig:trigramrec} shows how our replicability trigram information recovery score is positively correlated with both expert function and data transparency ratings, however, this relationship is less strong with task transparency. Meanwhile, the S-A log-likelihood ratio score captures user opinions of both function and task understanding, but is not predictive of retention score (\autoref{fig:loglikelihood}). While the relationship between replicability and function transparency was expected, the connection between S-A and task transparency was surprising at first. We think this is driven by a tendency for more detailed, transparent descriptions of a given task to more heavily utilize common language and analogies---after all, tasks such as translation, newsreading, and language learning all exist in the real world as topics of everyday discussion. \begin{figure}[t] \centering \includegraphics[width=\linewidth]{Fig/aff_high_low.pdf} \caption{Demonstrating interpretability of the BERTscore affinity replicability metric. } \label{fig:affhilo} \end{figure} Figure \ref{fig:affhilo} shows the \textit{sentence affinity rate curves} for two abstracts in the *ACL Demo Corpus. This demonstrates the interpretability of the affinity rate replicability score---the top curve has several peaks of particularly high BERTscore, which match to specific, technical sentences in the abstract providing concrete detail on how the system works. Meanwhile, the bottom curve has few high-scoring peaks, the highest of which match to one of the vague sentences in the source abstract. In other words, \textbf{descriptions with more specific technical detail in the abstract score higher on our objective transparency measures}, as desired. \subsection{Transparency and Response Variables}\label{sec:response} To relate the abstract-level objective and subjective transparency ratings to the response variables, we assess pairwise PCC between pairs of (transparency label, response variable) across the 55 abstracts. \autoref{tab:xy} contains a sample of pairwise correlation analyses of expert subjective transparency opinions and the user response variables. \begin{figure*}[t] \begin{minipage}{.33\linewidth} \centering \label{subfig:r_cf} \subfloat[$\textrm{PCC}=0.347$]{\includegraphics[width=1\linewidth]{Fig/YY/ratio_conf_func.pdf}} \end{minipage}% \begin{minipage}{.33\linewidth} \centering \label{subfig:r_cg} \subfloat[$\textrm{PCC}=0.383$]{\includegraphics[width=1\linewidth]{Fig/YY/ratio_conf_goal.pdf}} \end{minipage}% \begin{minipage}{.33\linewidth} \centering \label{subfig:r_u} \subfloat[$\textrm{PCC}=-0.007$]{\includegraphics[width=1\linewidth]{Fig/YY/ratio_understanding.pdf}} \end{minipage}% \caption{The style-appropriateness log-likelihood ratio clearly captures user opinions of function and task understanding, while not capturing their real trends in retention.} \label{fig:loglikelihood} \end{figure*} \begin{figure*}[t] \centering \begin{minipage}{.33\linewidth} \centering \label{subfig:g_cf} \centering \subfloat[$\textrm{PCC} =0.400$]{\includegraphics[width=1\textwidth]{Fig/XY/TGAvg_conf_func.pdf}} \end{minipage}% \begin{minipage}{.33\linewidth} \centering \label{subfig:g_cg} \subfloat[$\textrm{PCC} =0.487$]{\includegraphics[width=1\textwidth]{Fig/XY/TGAvg_conf_goal.pdf}} \end{minipage}% \begin{minipage}{.33\linewidth} \centering \label{subfig:f_cf} \subfloat[$\textrm{PCC} =-0.157$]{\includegraphics[width=1\textwidth]{Fig/XY/TFAvg_conf_func.pdf}} \end{minipage}% \caption{Task transparency drives a statistically significant positive trend in (a) average user function understanding and (b) average user goal understanding, but neither (c) function nor goal understanding has a trend against function transparency.} \label{fig:TGU} \end{figure*} \begin{table}[t] \small \centering \begin{tabularx}{0.49\textwidth}{lcccc} \hline \textbf{Abstract Rating} & \textbf{Response Variable} & \textbf{PCC} & \textbf{\textit{p}} \\ \hline Task Transp. & Function Underst. & 0.400 & 0.003 \\ Task Transp. & Task Underst. & 0.487 & 0.000 \\ Task Transp. & Task Trust & 0.327 & 0.015 \\ Func. Transp. & Function Fairness & 0.176 & 0.199 \\ Funct. Transp. & Task Fairness & -0.236 & 0.083 \\ Data Transp. & Function Underst. & 0.292 & 0.030 \\ \hline\end{tabularx} \caption{Pairwise correlations between abstract-averaged subjective transparency scores and user response variables.}\label{tab:xy} \end{table} Of the statistically significant correlations between subjective scores we observe, the positive relationship between expert-rated average \textbf{task transparency} and average user self-reported \textbf{task understanding} is the strongest. Similarly, there is a strong, statistically significant positive correlation between \textbf{task transparency} and self-reported \textbf{function understanding}. However, we were surprised to find that our expert-rated average \textbf{function transparency} does not exhibit a statistically significant correlation with either of the aforementioned understanding variables. \autoref{fig:TGU} depicts the positive correlations of these two response variables with task transparency In other words, users believe they understand not only the task, but the function of the system being described better, the more well-motivated and transparent the discussion of the \textit{task} is. However, transparency in describing the function of the system will not lead to users to think they understand either aspect better. This result was surprising. As function transparency captures ``how the system works,'' while task transparency is concerned with ``what the system does,'' it is probably the case that understanding the task is a necessary prerequisite for understanding the system function. This could explain the connection between task transparency and user function understanding. However, this connection is illusory: for example, a detailed description of the problem of translating French to Arabic contains no information about the attention mechanisms used by the underlying transformer. \begin{table}[t] \small \centering \begin{tabularx}{0.49\textwidth}{lcccc} \hline \textbf{Objective Metric} & \textbf{Response Var.} & \textbf{PCC} & \textbf{\textit{p}} \\ \hline S-A & Func. Underst. & 0.347 & 0.009 \\ S-A & Task Underst. & 0.383 & 0.004 \\ Replicability (TR) & Func. Fairness & 0.285 & 0.035 \\ Replicability (TR) & Task Fairness & -0.351 & 0.009 \\ Replicability (AR) & Task Fairness & -0.258 & 0.0573 \\ Replicability (TR) & Data Trust & 0.242 & 0.075 \\ Replicability (TR) & Task Trust & 0.286 & 0.034 \\ \hline\end{tabularx} \caption{Pairwise correlations objective transparency metrics and user response variables.}\label{tab:autoxy} \end{table} \section{Related Work} Most previous work on explainability and intelligibility in transparency focuses on ``explanations that are contrastive and sequential rather than purely subjective'' \cite{miller2019explanation}. Furthermore, prior studies regarding transparency have tended to focus on transparency in post-facto user judgments of automated systems following their use. For example, \citet{kizilcec_how_2016} and \citet{wang_factors_2020} both studied how \textit{system users} viewed the fairness of a system that judged them. In both studies, the authors found that while transparency affects perceived fairness, the strongest predictor of perceived fairness was final outcome favorability. Work in explainable AI (XAI) intersects with disclosive transparency when asking what kinds of explanations are preferred by users. Several studies have directly asked users of experimental XAI systems to respond to \cite{bhatt2019explainable, kaur2020interpreting, hong2020human} the quality and effects of the explanations. Judging how well system function descriptions are motivated by explainable outputs is thus a promising direction. Many solutions intended to remedy ethical concerns of machine learning include a disclosive component. \citet{lim2009and} studied how novice end-users can understand the function in context of intelligible systems. Similarly to us, they derive explanations from fundamental questions of ``what,'' ``why,'' and ``how'' that resolve the gulf of evaluation and gulf of execution in the user, as put forward by \cite{norman1988psychology}. While we are primarily concerned with disclosure to laypeople, disclosure between practitioners has been a key thrust of work in recent years. Disclosing potential deficiencies, biases, failure points, and intended use cases for datasets \cite{holland2018dataset, bender2018data, gebru2018datasheets}, pretrained models \cite{mitchell2019model}, and full systems \cite{arnold2019factsheets} is crucial in ensuring the ethical construction and deployment of systems that utilize machine learning while minimizing the risk of potential harms. All of these proposals focus heavily on outlining best practices to ensure that various sources of bias are accounted for and made available to system builders and decision makers before harms are perpetuated. \citet{lipton2018mythos} introduced \textit{simulatability}, the capacity for a user to comprehend all constituent operations of a model by manually performing them, as fundamental to transparency. This relies on a notion of \textit{decomposability} \cite{lou2012intelligible}. Intelligibility is both an end in itself and a useful tool for ensuring buy-in from stakeholders such as users \cite{muir1994trust} and management \cite{veale_2018_fairness}. \citet{knowles2017intelligibility} deal with designing systems that use intelligibility to convey evidence of trustworthiness under uncertain scenario, and frame intelligibility as the degree to which the system's underlying logic can be conveyed to users. \section{Conclusions} Our replication-based framework allows us to tackle the problem of characterizing disclosive transparency in NLP system descriptions. We developed \textit{style-appropriateness} and \textit{replicability} metrics using neural language models, which capture multiple subjective dimensions of transparency. We ran a pilot study characterizing layperson responses to varying levels of transparency in system descriptions, demonstrating the value of the conceptual framework and the concrete tools proposed. We release all code, data, and annotations online at \texttt{ \href{https://github.com/michaelsaxon/disclosive-transparency}{https://github.com/michaelsaxon/}} \texttt{\href{https://github.com/michaelsaxon/disclosive-transparency}{disclosive-transparency/}}. Three natural directions for future work follow these results. The automated transparency metrics can remove the costly expert annotator constraint, enabling scaled up transparency-user opinion relationship studies. More sophisticated conditional abstract-to-full text inversion models can be directly swapped in with the replicability metric to produce better automated transparency scores. Finally, the metrics can be used to guide NLG processes, perhaps to enable transparency-constrained abstractive summarization or style transfer. \section{Acknowledgements} This work was supported in part by the National Science Foundation Graduate Research Fellowship under Grant No. 1650114. We would also like to thank the Robert N. Noyce Trust for their generous gift to University of California via the Noyce Initiative. The views and conclusions contained in this document are those of the authors and should not be interpreted as representing the sponsors. \section{Ethical Considerations} \autoref{tab:autoxy} demonstrates that increased \textbf{replicability} scores are associated with decreasing opinions of the ethics of the underlying task (increasing disagreement with the statement ``I believe this system is made to solve an ethical task'') but increasing opinions of function fairness (increasing disagreement with ``I am concerned about the fairness of this system''). This was a surprising result that we are interested in attempting to replicate on larger corpora. With this relatively small sample size, it is hard to interpret why these conflicting trends in ethical opinions might arise. This negative relationship between replicability and task ethics could be an artifact of the data used to train the abstract-to-full text inversion model underpinning the replicability metric. It might be the case that there is higher public awareness and controversy toward ML tasks that are more well-represented in the arXiv inversion dataset. However, this result might also represent a genuine ethical quandary for further research in transparency. Much of Section 1 focused on making the case for \textit{why measuring transparency is important}. However, if it really is the case that increased measurable disclosive transparency drives decreasing trust in system ethics, it's conceivable that system providers or governments could become less inclined to disclose. We would consider this a negative outcome. However our results so far do not overwhelmingly suggest this relationship exists. Another potential limitation of this study is that layperson end-users are not the target audience of these NLP conference abstracts. The decision to use academic writings as stimuli was driven by the availability of (short description, long description) pairs consisting of the abstracts and their corresponding full texts. However, we believe the short description/long document pairing is applicable to a number of fields, including terms of service as discussed in Section 2, and to other types of systems described in non-academic, but still technical text, such as patent disclosures and instruction manuals. Finally, as attitudes toward privacy, fairness, and ethics can be culturally variable, we note that our survey results were sourced from crowd workers in majority-English speaking countries and may not be broadly representative. \bibliographystyle{acl_natbib}
{'timestamp': '2021-09-13T02:26:46', 'yymm': '2101', 'arxiv_id': '2101.00433', 'language': 'en', 'url': 'https://arxiv.org/abs/2101.00433'}
arxiv
\section{Introduction} Transformer is an attention-based encoder-decoder model \cite{DBLP:conf/nips/VaswaniSPUJGKP17}. It has shown promising results in machine translation tasks recently \cite{DBLP:conf/acl/WangLXZLWC19,DBLP:conf/emnlp/LiWLJDXWZ20,DBLP:conf/wmt/ZhangWCWSZRZZWM20,DBLP:conf/aaai/LiWXLZ20}. Nonetheless, Transformer suffers from the inefficiency issue at inference. This problem is attributed to the Transformer decoder for two reasons: 1) the decoder is deep \cite{DBLP:journals/corr/abs-2006-10369}. It consists of multiple layers and each layer contains three sub-layers, including two attentions and a feed-forward network; 2) the attention has a high (quadratic time) complexity \cite{DBLP:conf/acl/XiongZS18}, as it needs to compute the correlation between any two input words. Previous work has focused on improving the complexity of the attention in the decoder to accelerate the inference. For example, \aan{} uses the averaging operation to avoid computing the correlation between input words \cite{DBLP:conf/acl/XiongZS18}. \SAN{} share the attention results among layers \cite{DBLP:conf/ijcai/XiaoLZ0L19}. On the other hand, we learn that vanilla attention runs faster in training than in inference thanks to its parallelism. This offers a new direction: a higher degree of parallelism could speed up the inference. The most representative work of this type is the non-autoregressive approach \cite{DBLP:conf/iclr/Gu0XLS18}. Its decoder predicts all words in parallel, but fails to model the word dependencies. Despite of their successes, all these systems still have a deep decoder. In this work, we propose to parallelize the sub-layers to obtain a shallow autoregressive decoder. This way does not suffer from the poor result of directly reducing depths and avoids the limitation of non-autoregressive approaches. We prove that the two attention sub-layers in a decoder layer could be parallelized if we assume their inputs are close to each other. This assumption holds and thereby we compress these two attentions into one. Furthermore, we show that the remaining feed-forward network could also be merged into the attention due to their linearity. To the end, we propose \emph{Compressed Attention Network} (\my{} for short). The decoder layer of \my{} possesses a single attention sub-layer that does the previous three sub-layers' jobs in parallel. As another ``bonus'', \my{} is simple and easy to be implemented. In addition, \citet{DBLP:journals/corr/abs-2006-10369} empirically discover that existing systems are not well balancing the encoder and decoder depths. Based on their work, we build a system with a deep encoder and a shallow decoder, which is 2$\times$ faster than the widely used standard baseline without loss in performance. It requires neither the architecture modification nor adding extra parameters. This system serves as a stronger baseline for a more convincing comparison. We evaluate \my{} and the stronger baseline in 14 machine translation tasks, including WMT14 English$\leftrightarrow$\{German, French\} (En$\leftrightarrow$\{De, Fr\}) and WMT17 English$\leftrightarrow$\{German, Finnish, Latvian, Russian, Czech\} (En$\leftrightarrow$\{De, Fi, Lv, Ru, Cs\}). The experiments show that \my{} is up to 2.82$\times$ faster than the standard baseline with almost no loss in performance. Even comparing to our stronger baseline, \my{} still has a 1.42$\times$ speed-up, while other acceleration techniques such as \SAN{} and \aan{} are 1.12$\sim$1.16$\times$ in the same case. \begin{figure*}[t!] \centering \hspace*{\fill} \subfigure[Transformer] { \centering \begin{tikzpicture}[scale=1.5] \tikzstyle{reprnode} = [rectangle,draw,rounded corners=2pt,minimum height=0.2cm,minimum width=0.6cm,inner sep=3pt] \tikzstyle{wordnode} = [minimum width=0.6cm,font=\small,align=center,inner sep=1pt] \begin{scope}[local bounding box=ENCODER] \node[reprnode,fill=ugreen!50!white,anchor=west] (enc1) at (0,0) {}; \node[reprnode,fill=ugreen!50!white,anchor=west] (enc2) at ([xshift=3pt]enc1.east) {}; \node[reprnode,fill=ugreen!50!white,anchor=west] (enc3) at ([xshift=3pt]enc2.east) {}; \node[reprnode,fill=ugreen!50!white,anchor=west] (enc4) at ([xshift=3pt]enc3.east) {}; \node[wordnode,anchor=north] (sw1) at ([yshift=-1.1cm]enc1.south) {w\o3}; \node[wordnode,anchor=base west] (sw2) at ([xshift=3pt]sw1.base east) {h\en3}; \node[wordnode,anchor=base west] (sw3) at ([xshift=3pt]sw2.base east) {h\ao3}; \node[wordnode,anchor=base west] (sw4) at ([xshift=3pt]sw3.base east) {.}; \node[reprnode,minimum height=0.6cm,opacity=0,anchor=north] (es1) at ([yshift=-0.3cm]enc1.south) {}; \node[reprnode,minimum height=0.6cm,opacity=0,anchor=north] (es2) at ([yshift=-0.3cm]enc2.south) {}; \node[reprnode,minimum height=0.6cm,opacity=0,anchor=north] (es3) at ([yshift=-0.3cm]enc3.south) {}; \node[reprnode,minimum height=0.6cm,opacity=0,anchor=north] (es4) at ([yshift=-0.3cm]enc4.south) {}; \node[rectangle,draw,rounded corners=2pt,fill=gray!10!white,inner sep=0pt,fit=(es1) (es4)] (encoder) {}; \node[font=\small] () at (encoder) {Encoder}; \foreach \i in {1,...,4} { \draw[-latex,thick,black] (es\i.north) to (enc\i.south); \draw[-latex,thick,black] ([yshift=-0.3cm]es\i.south) to (es\i.south); } \end{scope} \begin{scope}[local bounding box=DECODER] \node[reprnode,fill=dblue!50!white,anchor=west] (cross1) at ([xshift=0.6cm]enc4.east) {}; \node[reprnode,fill=dblue!50!white,anchor=west] (cross2) at ([xshift=3pt]cross1.east) {}; \node[reprnode,fill=dblue!50!white,anchor=west] (cross3) at ([xshift=3pt]cross2.east) {}; \node[reprnode,fill=dblue!50!white,anchor=west] (cross4) at ([xshift=3pt]cross3.east) {}; \node[reprnode,fill=dblue!50!white,anchor=north] (self1) at ([yshift=-0.6cm]cross1.south) {}; \node[reprnode,fill=dblue!50!white,anchor=north] (self2) at ([yshift=-0.6cm]cross2.south) {}; \node[reprnode,fill=dblue!50!white,anchor=north] (self3) at ([yshift=-0.6cm]cross3.south) {}; \node[reprnode,fill=dblue!50!white,anchor=north] (self4) at ([yshift=-0.6cm]cross4.south) {}; \node[reprnode,fill=dblue!50!white,anchor=south] (ffn1) at ([yshift=0.6cm]cross1.north) {}; \node[reprnode,fill=dblue!50!white,anchor=south] (ffn2) at ([yshift=0.6cm]cross2.north) {}; \node[reprnode,fill=dblue!50!white,anchor=south] (ffn3) at ([yshift=0.6cm]cross3.north) {}; \node[reprnode,fill=dblue!50!white,anchor=south] (ffn4) at ([yshift=0.6cm]cross4.north) {}; \node[reprnode,fill=dblue!50!white,anchor=south] (output1) at ([yshift=0.6cm]ffn1.north) {}; \node[reprnode,fill=dblue!50!white,anchor=south] (output2) at ([yshift=0.6cm]ffn2.north) {}; \node[reprnode,fill=dblue!50!white,anchor=south] (output3) at ([yshift=0.6cm]ffn3.north) {}; \node[reprnode,fill=dblue!50!white,anchor=south] (output4) at ([yshift=0.6cm]ffn4.north) {}; \node[wordnode,anchor=north] (tw1) at ([yshift=-0.3cm]self1.south) {I}; \node[wordnode,anchor=base west] (tw2) at ([xshift=3pt]tw1.base east) {am}; \node[wordnode,anchor=base west] (tw3) at ([xshift=3pt]tw2.base east) {fine}; \node[wordnode,anchor=base west] (tw4) at ([xshift=3pt]tw3.base east) {.}; \node[wordnode,anchor=south] (ow1) at ([yshift=0.3cm]output1.north) {am}; \node[wordnode,anchor=base west] (ow2) at ([xshift=3pt]ow1.base east) {fine}; \node[wordnode,anchor=base west] (ow3) at ([xshift=3pt]ow2.base east) {.}; \node[wordnode,anchor=base west] (ow4) at ([xshift=3pt]ow3.base east) {$\langle$eos$\rangle$}; \foreach \i in {1,...,4} { \draw[-latex,thick,black] ([yshift=-0.3cm]self\i.south) to (self\i.south); \draw[-latex,thick,black] (output\i.north) to ([yshift=0.3cm]output\i.north); } \draw[-latex,dblue,thick] (self1.north) .. controls +(north:0.2cm) and +(south:0.4cm) .. (cross4.south); \draw[-latex,dblue,thick] (self2.north) .. controls +(north:0.1cm) and +(south:0.4cm) .. (cross4.south); \draw[-latex,dblue,thick] (self3.north) .. controls +(north:0.1cm) and +(south:0.4cm) .. (cross4.south); \draw[-latex,dblue,thick] (self4.north) to (cross4.south); \node[wordnode,text=dblue,anchor=south west] () at ([yshift=0.3cm]self1.north west) {Self-Attention}; \draw[-latex,ugreen,thick] (enc1.north) .. controls +(north:0.4cm) and +(south:0.5cm) .. (ffn4.south); \draw[-latex,ugreen,thick] (enc2.north) .. controls +(north:0.3cm) and +(south:0.5cm) .. (ffn4.south); \draw[-latex,ugreen,thick] (enc3.north) .. controls +(north:0.2cm) and +(south:0.5cm) .. (ffn4.south); \draw[-latex,ugreen,thick] (enc4.north) .. controls +(north:0.1cm) and +(south:0.5cm) .. (ffn4.south); \draw[-latex,ugreen,thick] (cross4.north) to (ffn4.south); \node[wordnode,text=ugreen,anchor=south west] () at ([yshift=0.3cm]enc2.north west) {Cross-Attention}; \draw[-latex,blue,thick] (ffn4) to node [midway,left,text=blue,font=\small] {FFN} (output4); \end{scope} \begin{pgfonlayer}{background} \node[rectangle,draw,fill=gray!10!white,rounded corners=2pt,inner sep=2pt,fit=(self1) (output4),label={[font=\small]right:$\times N$}] (declayer) {}; \end{pgfonlayer} \node[reprnode,fill=dblue!50!white,anchor=south west,label={[font=\small]right:Target Token}] (label1) at ([yshift=1cm]enc1.north west) {}; \node[reprnode,fill=ugreen!50!white,anchor=south west,label={[font=\small]right:Source Token}] (label2) at ([yshift=5pt]label1.north west) {}; \node[reprnode,fill=gray!10!white,anchor=south west,label={[font=\small]right:Decoder}] (label3) at ([yshift=5pt]label2.north west) {}; \draw[-latex,draw,thick,densely dotted] ([xshift=1cm]label3.east) .. controls +(east:1cm) and +(west:1cm) .. ([yshift=0.3cm]declayer.west); \end{tikzpicture} \label{fig:transformer} } \hfill \subfigure[\my{}] { \centering \begin{tikzpicture}[scale=1.5] \tikzstyle{reprnode} = [rectangle,draw,rounded corners=2pt,minimum height=0.2cm,minimum width=0.6cm,inner sep=3pt] \tikzstyle{wordnode} = [minimum width=0.6cm,font=\small,align=center,inner sep=1pt] \begin{scope}[local bounding box=ENCODER] \node[reprnode,fill=ugreen!50!white,anchor=west] (enc1) at (0,0) {}; \node[reprnode,fill=ugreen!50!white,anchor=west] (enc2) at ([xshift=3pt]enc1.east) {}; \node[reprnode,fill=ugreen!50!white,anchor=west] (enc3) at ([xshift=3pt]enc2.east) {}; \node[reprnode,fill=ugreen!50!white,anchor=west] (enc4) at ([xshift=3pt]enc3.east) {}; \node[wordnode,anchor=north] (sw1) at ([yshift=-1.1cm]enc1.south) {w\o3}; \node[wordnode,anchor=base west] (sw2) at ([xshift=3pt]sw1.base east) {h\en3}; \node[wordnode,anchor=base west] (sw3) at ([xshift=3pt]sw2.base east) {h\ao3}; \node[wordnode,anchor=base west] (sw4) at ([xshift=3pt]sw3.base east) {.}; \node[reprnode,minimum height=0.6cm,opacity=0,anchor=north] (es1) at ([yshift=-0.3cm]enc1.south) {}; \node[reprnode,minimum height=0.6cm,opacity=0,anchor=north] (es2) at ([yshift=-0.3cm]enc2.south) {}; \node[reprnode,minimum height=0.6cm,opacity=0,anchor=north] (es3) at ([yshift=-0.3cm]enc3.south) {}; \node[reprnode,minimum height=0.6cm,opacity=0,anchor=north] (es4) at ([yshift=-0.3cm]enc4.south) {}; \node[rectangle,draw,rounded corners=2pt,fill=gray!10!white,inner sep=0pt,fit=(es1) (es4)] (encoder) {}; \node[font=\small] () at (encoder) {Encoder}; \foreach \i in {1,...,4} { \draw[-latex,thick,black] (es\i.north) to (enc\i.south); \draw[-latex,thick,black] ([yshift=-0.3cm]es\i.south) to (es\i.south); } \end{scope} \begin{scope}[local bounding box=DECODER] \node[reprnode,fill=dblue!50!white,anchor=west] (cross1) at ([xshift=0.6cm]enc4.east) {}; \node[reprnode,fill=dblue!50!white,anchor=west] (cross2) at ([xshift=3pt]cross1.east) {}; \node[reprnode,fill=dblue!50!white,anchor=west] (cross3) at ([xshift=3pt]cross2.east) {}; \node[reprnode,fill=dblue!50!white,anchor=west] (cross4) at ([xshift=3pt]cross3.east) {}; \node[reprnode,fill=dblue!50!white,anchor=south] (output1) at ([yshift=0.6cm]cross1.north) {}; \node[reprnode,fill=dblue!50!white,anchor=south] (output2) at ([yshift=0.6cm]cross2.north) {}; \node[reprnode,fill=dblue!50!white,anchor=south] (output3) at ([yshift=0.6cm]cross3.north) {}; \node[reprnode,fill=dblue!50!white,anchor=south] (output4) at ([yshift=0.6cm]cross4.north) {}; \node[wordnode,anchor=north] (tw1) at ([yshift=-0.3cm]cross1.south) {I}; \node[wordnode,anchor=base west] (tw2) at ([xshift=3pt]tw1.base east) {am}; \node[wordnode,anchor=base west] (tw3) at ([xshift=3pt]tw2.base east) {fine}; \node[wordnode,anchor=base west] (tw4) at ([xshift=3pt]tw3.base east) {.}; \node[wordnode,anchor=south] (ow1) at ([yshift=0.3cm]output1.north) {am}; \node[wordnode,anchor=base west] (ow2) at ([xshift=3pt]ow1.base east) {fine}; \node[wordnode,anchor=base west] (ow3) at ([xshift=3pt]ow2.base east) {.}; \node[wordnode,anchor=base west] (ow4) at ([xshift=3pt]ow3.base east) {$\langle$eos$\rangle$}; \foreach \i in {1,...,4} { \draw[-latex,thick,black] ([yshift=-0.3cm]cross\i.south) to (cross\i.south); \draw[-latex,thick,black] (output\i.north) to ([yshift=0.3cm]output\i.north); } \draw[-latex,red,thick] (cross1.north) .. controls +(north:0.2cm) and +(south:0.4cm) .. (output4.south); \draw[-latex,red,thick] (cross2.north) .. controls +(north:0.1cm) and +(south:0.4cm) .. (output4.south); \draw[-latex,red,thick] (cross3.north) .. controls +(north:0.1cm) and +(south:0.4cm) .. (output4.south); \draw[-latex,red,thick] (cross4.north) to (output4.south); \draw[-latex,red,thick] (enc1.north) .. controls +(north:0.5cm) and +(south:0.4cm) .. (output4.south); \draw[-latex,red,thick] (enc2.north) .. controls +(north:0.4cm) and +(south:0.4cm) .. (output4.south); \draw[-latex,red,thick] (enc3.north) .. controls +(north:0.3cm) and +(south:0.4cm) .. (output4.south); \draw[-latex,red,thick] (enc4.north) .. controls +(north:0.2cm) and +(south:0.4cm) .. (output4.south); \node[wordnode,text=red,anchor=south west] () at ([yshift=0.35cm]enc1.north west) {Compressed-Attention}; \end{scope} \begin{pgfonlayer}{background} \node[rectangle,draw,fill=gray!10!white,rounded corners=2pt,inner sep=2pt,fit=(cross1) (output4),label={[font=\small]right:$\times N$}] (declayer) {}; \end{pgfonlayer} \node[reprnode,fill=dblue!50!white,anchor=south west,label={[font=\small]right:Target Token}] (label1) at ([yshift=1cm]enc1.north west) {}; \node[reprnode,fill=ugreen!50!white,anchor=south west,label={[font=\small]right:Source Token}] (label2) at ([yshift=5pt]label1.north west) {}; \node[reprnode,fill=gray!10!white,anchor=south west,label={[font=\small]right:Decoder}] (label3) at ([yshift=5pt]label2.north west) {}; \draw[-latex,draw,thick,densely dotted] ([xshift=1cm]label3.east) .. controls +(east:1cm) and +(west:1cm) .. ([yshift=0.3cm]declayer.west); \end{tikzpicture} \label{fig:man} } \hspace*{\fill} \caption{Transformer vs. \my{} (Chinese pinyin$\rightarrow$English: \emph{``w\o3 h\en3 h\ao3 .''} $\to$ \emph{``I am fine .''}).} \label{fig:comparison} \end{figure*} To summarize, our contributions are as follows: \begin{itemize} \item We propose \my{}, a novel architecture that accelerates Transformer by compressing its sub-layers for a higher degree of parallelism. \my{} is easy to be implemented. \item Our work is based on a stronger baseline, which is 2$\times$ faster than the widely used standard baseline. \item The extensive experiments on 14 WMT machine translation tasks show that \my{} is 1.42$\times$ faster than the stronger baseline and 2.82$\times$ for the standard baseline. \my{} also outperforms other approaches such as \SAN{} and \aan{}. \end{itemize} \section{Background: Transformer} Transformer is one of the state-of-the-art neural models in machine translation. It consists of a $N$-layer encoder and a $N$-layer decoder, where $N=6$ in most cases. The encoder maps the source sentence to a sequence of continuous representations and the decoder maps these representations to the target sentence. All layers in the encoder or decoder are identical to each other. The layer in the decoder consists of three sub-layers, including the self-attention, the cross-attention and the feed-forward network (FFN). The self-attention takes the output $X$ of the previous sub-layer as its input and produces a tensor with the same size as its output. It computes the attention distribution $A_x$ and then averages $X$ by $A_x$. We denote the self-attention as $Y_x=\mathrm{Self}(X)$, where $X\in\mathbb{R}^{t\times d}$, $t$ is the target sentence length and $d$ is the dimension of the hidden representation: \begin{align} A_x&=\mathrm{SoftMax}(\frac{XW_{q1}W_{k1}^TX^T}{\sqrt{d}})\label{eqn:self-weight}\\ Y_x&=A_xXW_{v1}\label{eqn:self-sum} \end{align} where $W_{q1},W_{k1},W_{v1}\in\mathbb{R}^{d\times d}$. The cross-attention is similar to the self-attention, except that it takes the encoder output $H$ as an additional input. We denote the cross-attention as $Y_h=\mathrm{Cross}(X,H)$, where $H\in\mathbb{R}^{s\times d}$, $s$ is the source sentence length: \begin{align} A_h&=\mathrm{SoftMax}(\frac{XW_{q2}W_{k2}^TH^T}{\sqrt{d}})\label{eqn:cross-weight}\\ Y_h&=A_hHW_{v2}\label{eqn:cross-sum} \end{align} where $W_{q2},W_{k2},W_{v2}\in\mathbb{R}^{d\times d}$. The FFN applies non-linear transformation to its input $X$. We denote the FFN as $Y_f=\mathrm{FFN}(X)$: \begin{equation} Y_f=\mathrm{ReLU}(XW_1+b_1)W_2+b_2\label{eqn:ffn} \end{equation} where $W_1\in\mathbb{R}^{d\times 4d}$, $b_1\in\mathbb{R}^{4d}$, $W_2\in\mathbb{R}^{4d\times d}$ and $b_2\in\mathbb{R}^{d}$. All sub-layers are coupled with the residual connection \cite{DBLP:conf/cvpr/HeZRS16}, i.e., $Y=f(X)+X$ where $f$ could be any sub-layer. Their inputs are also preprocessed by the layer normalization first \cite{DBLP:journals/corr/BaKH16}. \fig{fig:transformer} shows the architecture of Transformer decoder. For more details, we refer the reader to \citet{DBLP:conf/nips/VaswaniSPUJGKP17}. \section{Compressed Attention Network} \subsection{Compressing Self-Attention and Cross-Attention} As suggested by \citet{DBLP:conf/eccv/HuangSLSW16}, the output of one layer in the residual network can be decomposed into the sum of all outputs from previous layers. For the adjacent self-attention and cross-attention, we can write their final output as $Y=X+\mathrm{Self}(X)+\mathrm{Cross}(X',H)$, where $X$ is the input of self-attention and $X'=X+\mathrm{Self}(X)$ is the input of cross-attention. If $X$ and $X'$ are identical, we are able to accelerate the computation of $Y$ by parallelizing these two attentions, as $X'$ do not need to wait $\mathrm{Self}(X)$ to finish. \begin{figure}[t!] \centering \begin{tikzpicture} \begin{groupplot}[ group style={group size=2 by 1, horizontal sep=40pt}, width=\linewidth, height=0.5\linewidth, colormap/blackwhite, point meta min=0.7,point meta max=0.95, ] \nextgroupplot[ width=0.5\linewidth,height=0.5\linewidth, view={0}{90}, enlargelimits=false, ymin=-0.5,ymax=5.5, xmin=-0.5,xmax=5.5, xlabel={Cross-Attention}, ylabel={Self-Attention}, ytick={0,1,2,3,4,5}, yticklabels={1,2,3,4,5,6}, xtick={0,1,2,3,4,5}, xticklabels={1,2,3,4,5,6}, xtick style={draw=none}, ytick style={draw=none}, label style={font=\small}, every tick label/.append style={font=\small}, xticklabel pos=upper, ] \addplot3[matrix plot] table [meta=value] { x y value 0 0 0.8025 0 1 0.7510 0 2 0.5528 0 3 0.4033 0 4 0.2819 0 5 0.1932 1 0 0.5666 1 1 0.8943 1 2 0.8579 1 3 0.7125 1 4 0.5523 1 5 0.4244 2 0 0.3827 2 1 0.7534 2 2 0.9279 2 3 0.8817 2 4 0.7343 2 5 0.5816 3 0 0.2676 3 1 0.6112 3 2 0.8131 3 3 0.9429 3 4 0.8807 3 5 0.7337 4 0 0.1797 4 1 0.4725 4 2 0.6672 4 3 0.8337 4 4 0.9594 4 5 0.8837 5 0 0.1242 5 1 0.3623 5 2 0.5243 5 3 0.6894 5 4 0.8487 5 5 0.9638 }; \nextgroupplot[ width=0.5\linewidth,height=0.5\linewidth, view={0}{90}, enlargelimits=false, ymin=-0.5,ymax=5.5, xmin=-0.5,xmax=5.5, xlabel={FFN}, ylabel={Cross-Attention}, ytick={0,1,2,3,4,5}, yticklabels={1,2,3,4,5,6}, xtick={0,1,2,3,4,5}, xticklabels={1,2,3,4,5,6}, xtick style={draw=none}, ytick style={draw=none}, label style={font=\small}, every tick label/.append style={font=\small}, xticklabel pos=upper, ] \addplot3[matrix plot] table [meta=value] { x y value 0 0 0.8592 0 1 0.7867 0 2 0.6084 0 3 0.4756 0 4 0.3450 0 5 0.2484 1 0 0.6601 1 1 0.8813 1 2 0.8360 1 3 0.7140 1 4 0.5659 1 5 0.4297 2 0 0.4993 2 1 0.7553 2 2 0.8870 2 3 0.8655 2 4 0.7428 2 5 0.6011 3 0 0.3676 3 1 0.6049 3 2 0.7645 3 3 0.8897 3 4 0.8753 3 5 0.7593 4 0 0.2668 4 1 0.4742 4 2 0.6232 4 3 0.7689 4 4 0.8863 4 5 0.8839 5 0 0.1676 5 1 0.3644 5 2 0.4760 5 3 0.5962 5 4 0.7238 5 5 0.8716 }; \end{groupplot} \end{tikzpicture} \caption{The cosine similarity of inputs for every two adjacent sub-layers on WMT14 En-De translation task (a dark cell means the inputs are dissimilar).} \label{fig:identity} \end{figure} Previous work \cite{DBLP:conf/eccv/HeZRS16} has shown that inputs of adjacent layers are similar. This implies that $X$ and $X'$ are close and the parallelization is possible. We empirically verify this in the left part of \fig{fig:identity} by examining the cosine similarity between inputs of every self-attention and cross-attention pairs. It shows that $X$ and $X'$ are indeed close to each other (a high similarity $>0.9$ for the diagonal entries). Therefore we could assume $X$ and $X'$ are identical (we omit the layer normalization for simplicity): \begin{equation} Y=X+\mathrm{Self}(X)+\mathrm{Cross}(X,H)\label{eqn:self-cross-res} \end{equation} By observing that \eqn{eqn:self-sum} and \eqn{eqn:cross-sum} are essentially matrix multiplications, we could rewrite $\mathrm{Self}(X)+\mathrm{Cross}(X,H)$ as a single matrix multiplication: \begin{align} A&=\left[A_x^T,A_h^T\right]^T\\ \mathrm{Self}(X)+\mathrm{Cross}(X,H)&=A\left[XW_{v1},HW_{v2}\right]\label{eqn:self-cross-sum} \end{align} $[\cdot]$ is the concatenation operation along the first dimension. \citet{DBLP:conf/ijcai/XiaoLZ0L19} shows that some attention distributions $A_x$ and $A_h$ are duplicate. This means that there exists a certain redundancy in $\{W_{q1},W_{k1}\}$ and $\{W_{q2},W_{k2}\}$. Thus we could safely share $W_{q1}$ and $W_{q2}$ to parallelize the computation of the attention distribution $A$: \begin{align} \bar{A}&=\left(XW_q\left[XW_{k1},HW_{k2}\right]^T\right)/\sqrt{d}\\ A&=\left[\mathrm{SoftMax}(\bar{A}^T_{\cdot,1\ldots t}),\mathrm{SoftMax}(\bar{A}^T_{\cdot,t+1\ldots t+s})\right]^T \end{align} However, $A$ consists of two SoftMax distributions and is used in \eqn{eqn:self-cross-sum} without normalization. The output variance is then doubled and leads to poor optimization \cite{DBLP:journals/jmlr/GlorotB10}. It is advised to divide $A$ by $\sqrt{2}$ to preserve the variance. This way resembles a single distribution. So we use one SoftMax instead and this works well: \begin{equation} A=\mathrm{SoftMax}(\frac{XW_q\left[XW_{k1},HW_{k2}\right]^T}{\sqrt{d}})\label{eqn:self-cross-weight} \end{equation} Now, we can compute $Y$ in \eqn{eqn:self-cross-res} efficiently by using \eqn{eqn:self-cross-weight} as well as \eqn{eqn:self-cross-sum} to compute $\mathrm{Self}(X)+\mathrm{Cross}(X,H)$. \begin{figure}[t!] \centering \begin{tikzpicture} \tikzstyle{reprnode} = [rectangle,draw,rounded corners=2pt,minimum height=0.6cm,minimum width=0.2cm,inner sep=3pt] \tikzstyle{wordnode} = [minimum width=0.6cm,font=\small,align=center,inner sep=1pt] \node[reprnode,fill=ugreen!50!white,anchor=west] (enc1) at (0,0) {}; \node[reprnode,fill=ugreen!50!white,anchor=west] (enc2) at ([xshift=4pt]enc1.east) {}; \node[reprnode,fill=ugreen!50!white,anchor=west] (enc3) at ([xshift=4pt]enc2.east) {}; \node[reprnode,fill=ugreen!50!white,anchor=west] (enc4) at ([xshift=4pt]enc3.east) {}; \node[reprnode,fill=dblue!50!white,anchor=west] (dec1) at ([xshift=4pt]enc4.east) {}; \node[reprnode,fill=dblue!50!white,anchor=west] (dec2) at ([xshift=4pt]dec1.east) {}; \node[reprnode,fill=dblue!50!white,anchor=west] (dec3) at ([xshift=4pt]dec2.east) {}; \node[reprnode,fill=dblue!50!white,anchor=west] (dec4) at ([xshift=4pt]dec3.east) {}; \begin{pgfonlayer}{background} \node[rectangle,draw,densely dashed,thick,rounded corners=2pt,inner sep=4pt,fit=(enc1) (dec4),label={[font=\small,name=in]below:$\left[H,X\right]$}] (input) {}; \end{pgfonlayer} \draw[decorate,decoration={brace}] (input.south west) to node [midway,left,font=\small] {$d$} (input.north west); \begin{pgfonlayer}{background} \node[rectangle,draw,densely dashed,thick,rounded corners=2pt,inner sep=2pt,fit=(dec4)] (query) {}; \end{pgfonlayer} \node[reprnode,minimum height=1.2cm,fill=ugreen!50!white,anchor=west] (ev1) at ([xshift=1.5cm]dec4.east) {}; \node[reprnode,minimum height=1.2cm,fill=ugreen!50!white,anchor=west] (ev2) at ([xshift=4pt]ev1.east) {}; \node[reprnode,minimum height=1.2cm,fill=ugreen!50!white,anchor=west] (ev3) at ([xshift=4pt]ev2.east) {}; \node[reprnode,minimum height=1.2cm,fill=ugreen!50!white,anchor=west] (ev4) at ([xshift=4pt]ev3.east) {}; \node[reprnode,minimum height=1.2cm,fill=dblue!50!white,anchor=west] (dv1) at ([xshift=4pt]ev4.east) {}; \node[reprnode,minimum height=1.2cm,fill=dblue!50!white,anchor=west] (dv2) at ([xshift=4pt]dv1.east) {}; \node[reprnode,minimum height=1.2cm,fill=dblue!50!white,anchor=west] (dv3) at ([xshift=4pt]dv2.east) {}; \node[reprnode,minimum height=1.2cm,fill=dblue!50!white,anchor=west] (dv4) at ([xshift=4pt]dv3.east) {}; \begin{pgfonlayer}{background} \node[rectangle,draw,densely dashed,thick,rounded corners=2pt,inner sep=4pt,fit=(ev1) (dv4),label={[font=\small]below:$Y$}] (v) {}; \end{pgfonlayer} \draw[decorate,decoration={brace,mirror}] (v.south east) to node [midway,right,font=\small] {$4d$} (v.north east); \coordinate (p1) at ([yshift=2.2cm]enc1.north); \coordinate (p2) at ([yshift=2.2cm+0.1cm]enc2.north); \coordinate (p3) at ([yshift=2.2cm+0.3cm]enc3.north); \coordinate (p4) at ([yshift=2.2cm+0.7cm]enc4.north); \coordinate (p5) at ([yshift=2.2cm+0.7cm]dec1.north); \coordinate (p6) at ([yshift=2.2cm+0.3cm]dec2.north); \coordinate (p7) at ([yshift=2.2cm+0.1cm]dec3.north); \coordinate (p8) at ([yshift=2.2cm]dec4.north); \draw[blue,thick,rounded corners=5pt] (p1) -- (p2) -- (p3) -- (p4) -- (p5) -- (p6) -- (p7) -- (p8); \draw[->,black,thick] ([yshift=2cm]enc1.north west) to ([yshift=2cm]dec4.north east); \node[font=\small,anchor=east] (label) at ([yshift=2.8cm]dec4.north east) {$A$}; \node[reprnode,minimum width=1.2cm,minimum height=0.2cm,fill=dblue!50!white,anchor=south] (attn1) at ([yshift=1cm]v.north) {}; \node[reprnode,minimum width=1.2cm,minimum height=0.2cm,fill=dblue!50!white,anchor=south] (attn2) at ([yshift=1cm]attn1.north) {}; \node[reprnode,minimum width=0.6cm,minimum height=0.2cm,fill=dblue!50!white,anchor=south] (output) at ([yshift=1cm]attn2.north) {}; \draw[decorate,decoration={brace}] (output.north west) to node [midway,above,font=\small] {$d$} (output.north east); \draw[-latex,thick] (input.east) to node [pos=0.45,font=\scriptsize,rotate=-90,fill=white] {$Y=\left[H\widetilde{W}_{v2},X\widetilde{W}_{v1}\right]$} (v.west); \draw[-latex,thick] (input.north) to ([yshift=2cm-4pt]input.north); \draw[-latex,thick] (query.north) to [out=90,in=-90] ([yshift=2cm-4pt]input.north); \node[fill=white,font=\small,anchor=south] () at ([shift={(0.2cm,0.8cm)}]input.north) {\eqn{eqn:self-cross-weight}}; \draw[-latex,thick] (v.north) to node [midway,pos=0.4,fill=white,font=\small,name=eq1] {$Y=AY$} (attn1.south); \draw[-latex,thick] (attn1.north) to node [midway,pos=0.4,fill=white,font=\small,name=eq2] {$Y=XW_1+Y+b_1$} (attn2.south); \draw[-latex,thick] (query.north) to [out=90,in=180] (eq2.west); \draw[-latex,thick] (label.east) to [out=0,in=180] (eq1.west); \draw[-latex,thick] (attn2.north) to node [midway,pos=0.4,fill=white,font=\small] {$Y=\mathrm{ReLU}(Y)W_2+b_2$} (output.south); \node[font=\small,anchor=east,text=red] (label1) at ([xshift=-0.5cm]in.west) {Input}; \draw[->,thick,densely dotted] (label1) to (in); \node[font=\small,anchor=east,inner sep=1pt,text=red] (label2) at ([xshift=-0.5cm]output.west) {Output}; \draw[->,thick,densely dotted] (label2) to (output); \node[reprnode,minimum height=0.2cm,minimum width=0.6cm,fill=dblue!50!white,anchor=south west,label={[font=\small]right:Target Token $X$}] (label1) at ([yshift=3.7cm]enc1.north west) {}; \node[reprnode,minimum height=0.2cm,minimum width=0.6cm,fill=ugreen!50!white,anchor=south west,label={[font=\small]right:Source Token $H$}] (label2) at ([yshift=5pt]label1.north west) {}; \end{tikzpicture} \caption{Compressed-Attention.} \label{fig:process} \end{figure} \subsection{Compressing Attention and FFN} It is natural to consider to merge the attention and FFN with the same approach for further speed-up. As suggested by the right part of \fig{fig:identity}, the similarities between inputs of the adjacent cross-attention and FFN are low (dark diagonal entries). This implies that it is not ideal to make the identical input assumption to parallelize the cross-attention and FFN. Here we provide another solution. Given that attention is merely a weighted sum and FFN performs a linear projection first, we can merge them by exploiting the linearity. This way not only parallelizes the computation of attention and FFN but also removes redundant matrix multiplications. We substitute $X$ in \eqn{eqn:ffn} by $Y$ in \eqn{eqn:self-cross-res}: \begin{equation} Y_f=\mathrm{ReLU}(XW_1+A\left[XW_{v1},HW_{v2}\right]W_1+b_1)W_2+b_2 \end{equation} We can combine $W_1$ with $W_{v1}$ as well as $W_{v2}$ into $\widetilde{W}_{v1},\widetilde{W}_{v2}\in\mathbb{R}^{d\times 4d}$, as these matrices are learnable and matrix multiplied together: \begin{equation} Y_f=\mathrm{ReLU}(XW_1+A\left[X\widetilde{W}_{v1},H\widetilde{W}_{v2}\right]+b_1)W_2+b_2\label{eqn:self-cross-ffn} \end{equation} Furthermore, $XW_1$ can be computed in parallel with other transformations such as $XW_q$. This eventually gives us an more efficient decoder layer architecture, named \emph{Compressed-Attention}. The whole computation process is shown in \fig{fig:process}: it first computes the attention distribution $A$ by \eqn{eqn:self-cross-weight}, then performs the attention operation via \eqn{eqn:self-cross-ffn}, and produces $Y_f$ as the final result. The proposed \emph{Compressed Attention Network} (\my{}) stacks compressed-attentions to form its decoder. \fig{fig:comparison} shows the difference between Transformer and \my{}. \subsection{Balancing Encoder and Decoder Depths} Based on the findings of \citet{DBLP:journals/corr/abs-2006-10369}, we learn that a shallow decoder could offer a great speed gain, while a deep encoder could make up of the loss of a shallow decoder without adding a heavy computation overhead. Since their work is based on knowledge distillation \cite{DBLP:journals/corr/HintonVD15}, here we re-examine this idea under the standard training setting (without knowledge distillation). \begin{figure}[t!] \centering \begin{tikzpicture} \begin{axis}[ width=0.8\linewidth,height=0.6\linewidth, yticklabel style={/pgf/number format/fixed,/pgf/number format/precision=1}, ymin=26,ymax=28, enlarge y limits=0.15, ytick={26,27,28}, ylabel={BLEU [\%]}, ylabel near ticks, xlabel={\# of Encoder Layers/\# of Decoder Layers}, xlabel near ticks, symbolic x coords={6/6,9/4,12/2,14/1}, xmajorgrids=true, ymajorgrids=true, grid style=dashed, xtick=data, every tick label/.append style={font=\small}, label style={font=\small}, ] \addplot [lyyred,thick,mark=*] coordinates { (6/6,27.32) (9/4,27.63) (12/2,27.46) (14/1,26.20) };\label{bleu} \end{axis} \begin{axis}[ width=0.8\linewidth,height=0.6\linewidth, yticklabel style={/pgf/number format/fixed,/pgf/number format/precision=1}, ymin=100,ymax=300, enlarge y limits=0.15, xtick=\empty, ytick={100,200,300}, ylabel={Speed}, ylabel near ticks, axis y line*=right, symbolic x coords={6/6,9/4,12/2,14/1}, every tick label/.append style={font=\small}, label style={font=\small}, legend columns=2, legend pos=north west, legend style={font=\small}, ] \addlegendimage{/pgfplots/refstyle=bleu}\addlegendentry{BLEU} \addplot [lyyblue,thick,mark=square*] coordinates { (6/6,104.27) (9/4,144.16) (12/2,219.53) (14/1,292.49) };\addlegendentry{Speed} \end{axis} \end{tikzpicture} \caption{Performance (BLEU) and translation speed (token/sec) vs. the numbers of encoder and decoder layers on WMT14 En-De translation task.} \label{fig:balance} \end{figure} \fig{fig:balance} shows the performance and speed if we gradually reduce the decoder depth while adding more encoder layers. We see that although the overall number of parameters remains the same, the baseline can be 2$\times$ faster without losing any performance (12/2 vs. 6/6). This justifies the previous idea. We thereby choose a stronger baseline with a 12-layer encoder and a 2-layer decoder for a more convincing comparison. This setting is also applied to \my{}. \section{Experiments} \subsection{Experimental Setup} \begin{table}[t!] \centering \renewcommand\tabcolsep{2.5pt} \begin{tabular}{l|l|r|r|r|r|r|r} \hline \multicolumn{1}{c|}{\multirow{2}*{Source}} & \multicolumn{1}{c|}{\multirow{2}*{Lang.}} & \multicolumn{2}{c|}{Train} & \multicolumn{2}{c|}{Valid} & \multicolumn{2}{c}{Test} \\ \cline{3-8} & & \multicolumn{1}{c|}{sent.} & \multicolumn{1}{c|}{word} & \multicolumn{1}{c|}{sent.} & \multicolumn{1}{c|}{word} & \multicolumn{1}{c|}{sent.} & \multicolumn{1}{c}{word} \\ \hline \multirow{2}*{WMT14} & En$\leftrightarrow$De & 4.5M & 220M & 3000 & 110K & 3003 & 114K \\ \cline{2-8} & En$\leftrightarrow$Fr & 35M & 2.2B & 26K & 1.7M & 3003 & 155K \\ \cline{1-8} \multirow{5}*{WMT17} & En$\leftrightarrow$De & 5.9M & 276M & 8171 & 356K & 3004 & 128K \\ \cline{2-8} & En$\leftrightarrow$Fi & 2.6M & 108M & 8870 & 330K & 3002 & 110K \\ \cline{2-8} & En$\leftrightarrow$Lv & 4.5M & 115M & 2003 & 90K & 2001 & 88K \\ \cline{2-8} & En$\leftrightarrow$Ru & 25M & 1.2B & 8819 & 391K & 3001 & 132K \\ \cline{2-8} & En$\leftrightarrow$Cs & 52M & 1.2B & 8658 & 354K & 3005 & 118K \\ \hline \end{tabular} \caption{Data statistics (\# of sentences and \# of words).} \label{tab:data} \end{table} \subsubsection{Datasets} We evaluate our methods on 14 machine translation tasks (7 datasets $\times$ 2 translation directions each), including WMT14 En$\leftrightarrow$\{De, Fr\} and WMT17 En$\leftrightarrow$\{De, Fi, Lv, Ru, Cs\}. WMT14 En$\leftrightarrow$\{De, Fr\} datasets are tokenized by a script from Moses\footnote{\url{https://github.com/moses-smt/mosesdecoder/blob/master/scripts/tokenizer/tokenizer.perl}}. We apply BPE \cite{DBLP:conf/acl/SennrichHB16a} with 32K merge operations to segment words into subword units. Sentences with more than 250 subword units are removed. The first two rows of \tab{tab:data} are the detailed statistics of these two datasets. For En-De, we share the source and target vocabularies. We choose \emph{newstest-2013} as the validation set and \emph{newstest-2014} as the test set. For En-Fr, we validate the system on the combination of \emph{newstest-2012} and \emph{newstest-2013}, and test it on \emph{newstest-2014}. All WMT17 datasets are the official preprocessed version from WMT17 website\footnote{\url{http://data.statmt.org/wmt17/translation-task/preprocessed/}}. BPE with 32K merge operations is similarly applied to these datasets. We use the concatenation of all available preprocessed validation sets in WMT17 datasets as our validation set: \begin{itemize} \item En$\leftrightarrow$De. We use the concatenation of \emph{newstest2014}, \emph{newstest2015} and \emph{newstest2016} as the validation set. \item En$\leftrightarrow$Fi. We use the concatenation of \emph{newstest2015}, \emph{newsdev2015}, \emph{newstest2016} and \emph{newstestB2016} as the validation set. \item En$\leftrightarrow$Lv. We use \emph{newsdev2016} as the validation set. \item En$\leftrightarrow$Ru. We use the concatenation of \emph{newstest2014}, \emph{newstest2015} and \emph{newstest2016} as the validation set. \item En$\leftrightarrow$Cs. We use the concatenation of \emph{newstest2014}, \emph{newstest2015} and \emph{newstest2016} as the validation set. \end{itemize} We use \emph{newstest2017} as the test set for all WMT17 datasets. Detailed statistics of these datasets are shown in \tab{tab:data}. For all 14 translation tasks, we report case-sensitive tokenized BLEU scores\footnote{\url{https://github.com/moses-smt/mosesdecoder/blob/master/scripts/generic/multi-bleu.perl}}. \begin{table}[t!] \centering \renewcommand\tabcolsep{4pt} \begin{tabular}{c|l|c|r|c|r|r} \hline & \multicolumn{1}{c|}{System} & \multicolumn{1}{c|}{Test} & \multicolumn{1}{c|}{\small$\Delta_{\mathrm{BLEU}}$} & \multicolumn{1}{c|}{Valid} & \multicolumn{1}{c|}{Speed} & \multicolumn{1}{c}{\small$\Delta_{\mathrm{Speed}}$} \\ \hline \multirow{5}*{\rotatebox{90}{En-De}} & Baseline & 27.32 & \multicolumn{1}{c|}{-} & 26.56 & 104.27 & \multicolumn{1}{c}{-} \\ & Balanced & 27.46 & 0.00 & 26.81 & 219.53 & 0.00\% \\ \cline{2-7} & \SAN{} & 26.91 & -0.55 & 26.04 & 229.89 & +4.72\% \\ & \aan{} & 27.36 & -0.10 & 26.11 & 233.58 & +6.40\% \\ & \my{} & 27.32 & -0.14 & 26.47 & 290.08 & +32.14\% \\ \hline \multirow{5}*{\rotatebox{90}{De-En}} & Baseline & 30.50 & \multicolumn{1}{c|}{-} & 30.34 & 103.97 & \multicolumn{1}{c}{-} \\ & Balanced & 30.76 & 0.00 & 30.37 & 206.00 & 0.00\% \\ \cline{2-7} & \SAN{} & 30.09 & -0.67 & 30.11 & 240.52 & +16.76\% \\ & \aan{} & 30.15 & -0.61 & 30.07 & 232.08 & +12.66\% \\ & \my{} & 30.37 & -0.39 & 30.17 & 293.16 & +42.31\% \\ \hline \hline \multirow{5}*{\rotatebox{90}{En-Fr}} & Baseline & 40.82 & \multicolumn{1}{c|}{-} & 46.80 & 104.65 & \multicolumn{1}{c}{-} \\ & Balanced & 40.55 & 0.00 & 46.87 & 206.54 & 0.00\% \\ \cline{2-7} & \SAN{} & 40.45 & -0.10 & 46.69 & 208.68 & +1.04\% \\ & \aan{} & 40.50 & -0.05 & 46.57 & 210.29 & +1.82\% \\ & \my{} & 40.25 & -0.30 & 46.56 & 263.83 & +27.74\% \\ \hline \multirow{5}*{\rotatebox{90}{Fr-En}} & Baseline & 36.33 & \multicolumn{1}{c|}{-} & 47.03 & 105.85 & \multicolumn{1}{c}{-} \\ & Balanced & 36.86 & 0.00 & 46.89 & 201.13 & 0.00\% \\ \cline{2-7} & \SAN{} & 36.73 & -0.13 & 46.82 & 213.30 & +6.05\% \\ & \aan{} & 36.52 & -0.34 & 46.74 & 215.97 & +7.38\% \\ & \my{} & 36.67 & -0.19 & 46.63 & 266.63 & +32.57\% \\ \hline \end{tabular} \caption{Comparison of BLEU scores [\%] and translation speeds (token/sec) of different attention models on WMT14 En$\leftrightarrow$\{De, Fr\} translation tasks.} \label{tab:wmt14} \end{table} \subsubsection{Model Setup} Our baseline system is based on the open-source implementation of the Transformer model presented in \citet{DBLP:conf/naacl/OttEBFGNGA19}. For all machine translation tasks, the standard Transformer baseline (Baseline) consists of a 6-layer encoder and a 6-layer decoder. The embedding size is set to 512. The number of attention heads is 8. The FFN hidden size equals to 4$\times$ embedding size. Dropout with the value of 0.1 is used for regularization. We adopt the inverse square root learning rate schedule with 8,000 warmup steps and $0.0007$ learning rate. We stop training until the model stops improving on the validation set. All systems are trained on 8 NVIDIA TITIAN V GPUs with mixed-precision training \cite{DBLP:conf/iclr/MicikeviciusNAD18} and a batch size of 4,096 tokens per GPU. We average model parameters in the last 5 epochs for better performance. At test time, the model is decoded with a beam of width 4 and half-precision. For an accurate speed comparison, we decode with a batch size of 1 to avoid paddings. The stronger balanced baseline (Balanced) shares the setting with this standard baseline, except that its encoder depth is 12 and decoder depth is 2. We compare \my{} and other model acceleration approaches with our baselines. We choose Sharing Attention Network (\SAN{}) \cite{DBLP:conf/ijcai/XiaoLZ0L19} and Average Attention Network (\aan{}) \cite{DBLP:conf/acl/XiongZS18} for comparison, as they have been proven to be effective in various machine translation tasks \cite{DBLP:conf/aclnmt/BirchFLNO18}. All hyper-parameters of \my{}, \SAN{} and \aan{} are identical to the balanced baseline system. Results are the average of 3 runs. \begin{table}[t!] \centering \renewcommand\tabcolsep{4pt} \begin{tabular}{c|l|c|r|c|r|r} \hline & \multicolumn{1}{c|}{System} & \multicolumn{1}{c|}{Test} & \multicolumn{1}{c|}{\small$\Delta_{\mathrm{BLEU}}$} & \multicolumn{1}{c|}{Valid} & \multicolumn{1}{c|}{Speed} & \multicolumn{1}{c}{\small$\Delta_{\mathrm{Speed}}$} \\ \hline \multirow{3}*{\rotatebox{90}{En-De}} & Baseline & 28.40 & \multicolumn{1}{c|}{-} & 31.30 & 106.58 & \multicolumn{1}{c}{-} \\ & Balanced & 28.65 & 0.00 & 31.39 & 218.35 & 0.00\% \\ \cline{2-7} & \my{} & 28.30 & -0.35 & 30.94 & 280.57 & +28.50\% \\ \hline \multirow{3}*{\rotatebox{90}{De-En}} & Baseline & 34.48 & \multicolumn{1}{c|}{-} & 35.36 & 103.04 & \multicolumn{1}{c}{-} \\ & Balanced & 34.38 & 0.00 & 35.16 & 220.05 & 0.00\% \\ \cline{2-7} & \my{} & 33.99 & -0.39 & 34.82 & 286.23 & +30.07\% \\ \hline \hline \multirow{3}*{\rotatebox{90}{En-Fi}} & Baseline & 21.28 & \multicolumn{1}{c|}{-} & 18.31 & 103.84 & \multicolumn{1}{c}{-} \\ & Balanced & 21.38 & 0.00 & 18.67 & 207.73 & 0.00\% \\ \cline{2-7} & \my{} & 21.14 & -0.24 & 18.19 & 286.36 & +37.85\% \\ \hline \multirow{3}*{\rotatebox{90}{Fi-En}} & Baseline & 25.54 & \multicolumn{1}{c|}{-} & 21.32 & 106.59 & \multicolumn{1}{c}{-} \\ & Balanced & 25.63 & 0.00 & 21.29 & 209.88 & 0.00\% \\ \cline{2-7} & \my{} & 25.25 & -0.38 & 21.31 & 287.57 & +37.02\% \\ \hline \hline \multirow{3}*{\rotatebox{90}{En-Lv}} & Baseline & 16.14 & \multicolumn{1}{c|}{-} & 21.33 & 107.20 & \multicolumn{1}{c}{-} \\ & Balanced & 15.98 & 0.00 & 21.21 & 219.02 & 0.00\% \\ \cline{2-7} & \my{} & 15.90 & -0.08 & 20.75 & 287.33 & +31.19\% \\ \hline \multirow{3}*{\rotatebox{90}{Lv-En}} & Baseline & 18.74 & \multicolumn{1}{c|}{-} & 24.79 & 106.25 & \multicolumn{1}{c}{-} \\ & Balanced & 18.69 & 0.00 & 24.54 & 216.06 & 0.00\% \\ \cline{2-7} & \my{} & 18.21 & -0.48 & 24.16 & 275.89 & +27.69\% \\ \hline \hline \multirow{3}*{\rotatebox{90}{En-Ru}} & Baseline & 30.44 & \multicolumn{1}{c|}{-} & 30.67 & 106.46 & \multicolumn{1}{c}{-} \\ & Balanced & 30.28 & 0.00 & 30.59 & 214.52 & 0.00\% \\ \cline{2-7} & \my{} & 29.89 & -0.39 & 30.28 & 287.13 & +33.85\% \\ \hline \multirow{3}*{\rotatebox{90}{Ru-En}} & Baseline & 34.44 & \multicolumn{1}{c|}{-} & 32.39 & 107.24 & \multicolumn{1}{c}{-} \\ & Balanced & 34.24 & 0.00 & 32.22 & 213.78 & 0.00\% \\ \cline{2-7} & \my{} & 33.95 & -0.29 & 31.92 & 287.86 & +34.65\% \\ \hline \hline \multirow{3}*{\rotatebox{90}{En-Cs}} & Baseline & 24.00 & \multicolumn{1}{c|}{-} & 28.09 & 106.18 & \multicolumn{1}{c}{-} \\ & Balanced & 23.69 & 0.00 & 28.03 & 212.65 & 0.00\% \\ \cline{2-7} & \my{} & 23.59 & -0.10 & 27.71 & 272.37 & +28.08\% \\ \hline \multirow{3}*{\rotatebox{90}{Cs-En}} & Baseline & 30.00 & \multicolumn{1}{c|}{-} & 33.01 & 104.00 & \multicolumn{1}{c}{-} \\ & Balanced & 30.06 & 0.00 & 32.86 & 202.96 & 0.00\% \\ \cline{2-7} & \my{} & 29.87 & -0.19 & 32.99 & 269.70 & +32.88\% \\ \hline \end{tabular} \caption{BLEU scores [\%] and translation speeds (token/sec) on WMT17 En$\leftrightarrow$\{De, Fi, Lv, Ru, Cs\} translation tasks.} \label{tab:wmt17} \end{table} \subsection{Results} \tab{tab:wmt14} shows the results of various systems on WMT14 En$\leftrightarrow$\{De, Fr\}. Our balanced baseline has nearly the same performance as the standard baseline, but its speed is 2$\times$ faster on average. A similar phenomenon is also observed from WMT17 experiments in \tab{tab:wmt17}. This observation indicates that existing systems do not well balance the encoder and decoder depths. We also report the performance of \aan{}, \SAN{} and the proposed \my{}. All three approaches have similar BLEU scores and slightly underperform the balanced baseline. \my{} is more stable than the others, as its maximum $\Delta_{\mathrm{BLEU}}$ is -0.39, while \SAN{} is -0.67 and \aan{} is -0.61. For speeds of these systems, \SAN{} and \aan{} have a similar level of acceleration (1$\sim$16\%) over the balanced baseline. \my{}, on the other hand, provides a higher level of acceleration (27$\sim$42\%). Interestingly, we find that the acceleration is more obvious in De-En than in others, e.g., 42\% in De-En and 27\% in En-Fr for \my{}. We find that the length ratio between the translation and the source sentence in De-En is higher than others, e.g., 1.0 for De-En and 0.981 for En-Fr. In this case the decoder tends to predict more words and consumes more time in De-En, and thus acceleration approaches that work on the decoder are more effective. In addition, though not reported in \tab{tab:wmt14}, we find that applying \my{} on the standard baseline hurt the performance less (-0.09 BLEU points on average) than on the balanced baseline (-0.25 BLEU points on average). More experimental results to justify the effectiveness of \my{} are presented in \tab{tab:wmt17}. We evaluate the balanced baseline as well as \my{} on five WMT17 language pairs. The results again show that the balanced baseline is indeed a strong baseline with BLEU scores close to the standard baseline and is consistently 2$\times$ faster. \my{} also shows a similar trend that it slightly underperforms the balanced baseline ($<0.5$ BLEU scores) but is $>27\%$ faster. \section{Analysis} \begin{figure*}[t!] \centering \begin{tikzpicture} \begin{groupplot}[ group style={group size=3 by 1, horizontal sep=50pt}, width=\linewidth, height=0.25\linewidth, legend style={ column sep=10pt, legend columns=1, }, legend cell align={left}, ] \nextgroupplot[ width=0.32\linewidth,height=0.25\linewidth, yticklabel style={/pgf/number format/fixed,/pgf/number format/precision=1}, ymax=450, ylabel={Speed}, ylabel near ticks, xlabel={Beam Size}, xlabel near ticks, enlargelimits=0.05, symbolic x coords={1,4,16,64,256}, xmajorgrids=true, ymajorgrids=true, grid style=dashed, xtick=data, every tick label/.append style={font=\small}, label style={font=\small}, ylabel style={yshift=5pt}, legend pos=north east, legend style={column sep=3pt}, ] \addplot [lyyred,thick,mark=square*] coordinates { (1,259.02) (4,219.53) (16,145.62) (64,46.50) (256,12.43) };\addlegendentry{Balanced} \addplot [lyyblue,thick,thick,mark=triangle*] coordinates { (1,359.40) (4,290.08) (16,168.54) (64,48.63) (256,15.28) };\addlegendentry{\my{}} \nextgroupplot[ width=0.32\linewidth,height=0.25\linewidth, yticklabel style={/pgf/number format/fixed,/pgf/number format/precision=1}, ylabel={Speed}, ylabel near ticks, xlabel={Length}, xlabel near ticks, enlargelimits=0.05, symbolic x coords={10,20,30,40,50+}, xmajorgrids=true, ymajorgrids=true, grid style=dashed, xtick=data, every tick label/.append style={font=\small}, label style={font=\small}, ylabel style={yshift=5pt}, legend pos=south east, legend style={column sep=3pt}, ] \addplot [lyyred,thick,mark=square*] coordinates { (10,51.33) (20,126.07) (30,134.39) (40,176.06) (50+,186.26) };\addlegendentry{Balanced} \addplot [lyyblue,thick,thick,mark=triangle*] coordinates { (10,69.71) (20,161.19) (30,201.81) (40,218.78) (50+,237.85) };\addlegendentry{\my{}} \nextgroupplot[ width=0.32\linewidth,height=0.25\linewidth, symbolic x coords={CAN,SAN,AAN}, ymin=26, enlarge x limits=0.3, enlarge y limits={upper,value=1.1}, ylabel={Translation Length}, ylabel near ticks, ybar=0pt, xtick=data, ytick=\empty, nodes near coords, every node near coord/.append style={rotate=90,anchor=west,font=\small,/pgf/number format/fixed,/pgf/number format/fixed zerofill,/pgf/number format/precision=1}, every tick label/.append style={font=\small}, xticklabel style={rotate=45,anchor=north east,font=\small,inner sep=0pt,outer sep=2pt}, bar width=10pt, xmajorgrids=true, ymajorgrids=true, grid style=dashed, label style={font=\small}, legend pos=north east, legend image code/.code={ \draw [#1] (0cm,-0.15cm) rectangle (0.4cm,0.15cm); }, legend columns=2, legend style={at={(0.5,0.98)},anchor=north,column sep=3pt}, ] \addplot [draw=lyyblue!80,fill=lyyblue!60,pattern=north west lines,pattern color=lyyblue] coordinates { (CAN,26.94) (SAN,26.97) (AAN,27.07) };\addlegendentry{En-De} \addplot [draw=lyygreen!80,fill=lyygreen!60,pattern=north east lines,pattern color=lyygreen] coordinates { (CAN,30.32) (SAN,30.43) (AAN,30.43) };\addlegendentry{En-Fr} \end{groupplot} \end{tikzpicture} \caption{Translation speed (token/sec) vs. beam size and translation length on WMT14 En-De translation task.} \label{fig:sensitivity} \end{figure*} \subsection{Knowledge Distillation} \begin{table}[t!] \centering \begin{tabular}{l|c|r|c|r} \hline \multicolumn{1}{c|}{\multirow{2}*{System}} & \multicolumn{2}{c|}{Before KD} & \multicolumn{2}{c}{After KD} \\ \cline{2-5} & \multicolumn{1}{c|}{Test} & \multicolumn{1}{c|}{\small$\Delta_{\mathrm{BLEU}}$} & \multicolumn{1}{c|}{Test} & \multicolumn{1}{c}{\small$\Delta_{\mathrm{BLEU}}$} \\ \hline Balanced & 27.46 & 0.00 & 27.82 & 0.00 \\ \hline \SAN{} & 26.91 & -0.55 & 27.76 & -0.06 \\ \aan{} & 27.36 & -0.10 & 27.85 & +0.03 \\ \my{} & 27.32 & -0.14 & 28.08 & +0.26 \\ \hline \end{tabular} \caption{BLEU scores [\%] of applying knowledge distillation (KD) on WMT14 En-De translation task.} \label{tab:kd} \end{table} Although \SAN{}, \aan{} and \my{} offer considerable speed gain over the balanced baseline, they all suffer from the performance degradation as shown in \tab{tab:wmt14} and \tab{tab:wmt17}. The popular solution to this is knowledge distillation (KD). Here we choose sequence-level knowledge distillation \cite{DBLP:conf/emnlp/KimR16} for better performance in machine translation tasks. The balanced baseline is used to generate the pseudo data for KD. \tab{tab:kd} shows that KD closes the performance gap between the fast attention models (\SAN{}, \aan{} and \my{}) and the balanced baseline. This fact suggests that all three systems have enough capacity for a good performance, but training from scratch is not able to reach a good convergence state. It suggests that these systems might require a more careful hyper-parameters tuning or a better optimization method. \subsection{Ablation Study} \begin{table}[t!] \centering \renewcommand\tabcolsep{3pt} \begin{tabular}{l|c|r|r|r} \hline \multicolumn{1}{c|}{System} & \multicolumn{1}{c|}{Test} & \multicolumn{1}{c|}{\small$\Delta_{\mathrm{BLEU}}$} & \multicolumn{1}{c|}{Speed} & \multicolumn{1}{c}{\small$\Delta_{\mathrm{Speed}}$} \\ \hline Balanced & 27.46 & 0.00 & 219.53 & 0.00\% \\ \hline + Compress Attention & 27.09 & -0.37 & 263.64 & +20.09\% \\ + Compress FFN & 27.69 & +0.23 & 233.17 & +6.21\% \\ + Compress All & 27.32 & -0.14 & 290.08 & +32.14\% \\ \hline \end{tabular} \caption{Ablation study on WMT14 En-De translation task (Compress Attention: compress the self-attention and cross-attention only; Compress FFN: compress the cross-attention and FFN only; Compress All: compress the self-attention, cross-attention and FFN).} \label{tab:ablation} \end{table} To investigate in which part \my{} contributes the most to the acceleration as well as the performance loss, we only compress the self-attention and cross-attention or compress the cross-attention and FFN for study. \tab{tab:ablation} shows the results of this ablation study. We can see that compressing the two attentions provides a 20.09\% speed-up, while only 6.21\% for compressing attention and FFN. This is because FFN is already highly parallelized and accelerating itself does not bring much gain. Note that the second row of \tab{tab:ablation} is exactly \citet{DBLP:conf/emnlp/ZhangTS19}'s work (without AAN). We see that \my{} is faster and performs better. On the other hand, compressing attentions brings the most performance loss, which shows that the identical input assumption is strong. \fig{fig:identity} shows that inputs of the adjacent layers are not very similar in lower layers. Therefore using \my{} in low layers might bring a great loss. We also find that compressing attention and FFN has an even better result. This might be that we remove the redundant parameters in the model. \subsection{Sensitivity Analysis} We study how the speed could be affected by other factors in \fig{fig:sensitivity}, e.g., the beam size and the translation length. The left of \fig{fig:sensitivity} shows that \my{} is consistently faster than the balanced baseline with different beam size. As the acceleration provided by \my{} is constantly proportional to the speed of the baseline, it becomes less obvious when the baseline is slow, i.e., translating with a large beam. An opposite trend happens in the middle of \fig{fig:sensitivity} for the translation length. This is because overheads such as data preparation dominate the translation time of short sentences. This way results in a slow speed even when the translation time is short. As both the baseline and \my{} get faster when generating longer translations, one might suspect that the superior acceleration of \my{} over other approaches comes from the fact that \my{} generates longer translations. Further analysis is conducted and shown in the right of \fig{fig:sensitivity}. We see that \my{}, \SAN{} and \aan{} generate translations with similar lengths in two WMT14 translation tasks. This observation justifies that the superior acceleration brought by \my{} did come from its design rather than translation lengths. \subsection{Error Analysis} \begin{figure} \centering \begin{tikzpicture} \begin{groupplot}[ group style={group size=2 by 1, horizontal sep=50pt}, width=\linewidth, height=0.7\linewidth, ] \nextgroupplot[ width=0.49\linewidth,height=0.6\linewidth, yticklabel style={/pgf/number format/fixed,/pgf/number format/fixed zerofill,/pgf/number format/precision=0}, ylabel={BLEU [\%]}, ylabel near ticks, xlabel={Frequency ($\times 10^5$)}, xlabel near ticks, enlargelimits=0.1, ymax=45, symbolic x coords={6,12,18,24,30+}, xmajorgrids=true, ymajorgrids=true, grid style=dashed, xtick=data, every tick label/.append style={font=\small}, label style={font=\small}, ylabel style={yshift=5pt}, legend style={legend columns=1}, legend pos=north west, legend cell align={left}, ] \addplot [lyyred,thick,mark=square*] coordinates { (6,36.83) (12,34.14) (18,32.54) (24,35.20) (30+,40.43) };\addlegendentry{Balanced} \addplot [lyyblue,thick,thick,mark=triangle*] coordinates { (6,35.83) (12,33.04) (18,33.54) (24,34.73) (30+,37.22) };\addlegendentry{\my{}} \nextgroupplot[ width=0.49\linewidth,height=0.6\linewidth, yticklabel style={/pgf/number format/fixed,/pgf/number format/fixed zerofill,/pgf/number format/precision=0}, ylabel={BLEU [\%]}, ylabel near ticks, xlabel={Length}, xlabel near ticks, enlargelimits=0.1, ymax=40, symbolic x coords={10,20,30,40,50+}, xmajorgrids=true, ymajorgrids=true, grid style=dashed, xtick=data, every tick label/.append style={font=\small}, label style={font=\small}, ylabel style={yshift=5pt}, legend style={legend columns=1}, legend pos=north west, legend cell align={left}, ] \addplot [lyyred,thick,mark=square*] coordinates { (10,34.76) (20,33.49) (30,31.96) (40,34.29) (50+,36.94) };\addlegendentry{Balanced} \addplot [lyyblue,thick,thick,mark=triangle*] coordinates { (10,33.19) (20,32.97) (30,32.87) (40,34.21) (50+,36.21) };\addlegendentry{\my{}} \end{groupplot} \end{tikzpicture} \caption{BLEU score [\%] vs. word frequency ($\times 10^5$) and translation length on WMT14 En-De translation task.} \label{fig:error} \end{figure} As shown in \tab{tab:wmt14} and \tab{tab:wmt17}, the acceleration of \my{} comes at the cost of performance. Here we conduct experiments to better understand in which aspect \my{} scarifies for speed-up. We first evaluate the sentence-level BLEU score for each translation, then cluster these translations according to their averaged word frequencies or lengths. \fig{fig:error} shows the results. The left of \fig{fig:error} indicates that \my{} did well on sentences with low frequencies, but not on those with high frequencies. The right of \fig{fig:error} shows that \my{} does not translate short sentences well but is quite good at translating long sentences. These facts are counterintuitive as one might expect a poor model could do well on easy samples (high frequency and short sentences) but not on hard ones (low frequency and long sentences). This might due to the identical input assumptions we used to derive \my{} are critical to easy samples. We left this for the future exploration. \subsection{Parallelism Study} A simple approach to obtain a higher parallelism without modifying the architecture is to increase the batch size at inference. \fig{fig:parallel} compares the inference time of the balanced baseline and \my{} by varying the batch size. We can see that both systems run faster with a larger batch size and \my{} is consistently faster than the balanced baseline. But the acceleration of \my{} over the baseline $\Delta_{\mathrm{Speed}}$ diminishes when the batch size gets larger. In this case we observe that \my{} reaches the highest parallelism (a nearly 100\% GPU utility) in a smaller batch size ($\geq 32$) than the baseline ($>64$). This means that enlarging the batch size no longer provides acceleration for \my{}, while the baseline can still be further speeded up. We expect \my{} could be faster if more tensor cores are available in the future. \begin{figure}[t!] \centering \begin{tikzpicture} \begin{axis}[ width=0.8\linewidth,height=0.6\linewidth, yticklabel style={/pgf/number format/fixed,/pgf/number format/precision=1}, scaled y ticks=false, enlarge y limits=0.15, ylabel={Speed}, ylabel near ticks, xlabel={Batch Size}, xlabel near ticks, xmajorgrids=true, ymajorgrids=true, grid style=dashed, xmin=-10,xmax=70, xtick={0,20,40,60}, ymin=0,ymax=10000, ytick={0,2000,4000,6000,8000,10000}, every tick label/.append style={font=\small}, label style={font=\small}, ] \addplot [lyyred,thick,mark=square*] coordinates { (1,219.53) (2,401.33) (4,778.29) (8,1422.26) (16,2570.12) (32,4491.53) (64,8033.22) };\label{baseline} \addplot [lyyblue,thick,mark=triangle*] coordinates { (1,290.08) (2,529.92)(4,992.64) (8,1818.88) (16,3062.25) (32,5586.18) (64,8232.19) };\label{ours} \end{axis} \begin{axis}[ width=0.8\linewidth,height=0.6\linewidth, yticklabel style={/pgf/number format/fixed,/pgf/number format/precision=1}, enlarge y limits=0.15, xtick=\empty, xmin=-10,xmax=70, ylabel={$\Delta_\mathrm{Speed}$ [\%]}, ylabel near ticks, ymin=0,ymax=50, ytick={0,10,20,30,40,50}, axis y line*=right, every tick label/.append style={font=\small}, label style={font=\small}, legend columns=2, legend pos=north west, legend style={font=\small}, legend cell align={left}, ] \addlegendimage{/pgfplots/refstyle=baseline}\addlegendentry{Balanced} \addlegendimage{/pgfplots/refstyle=ours}\addlegendentry{\my{}} \addplot [lyygreen,thick,densely dashed,mark=*] coordinates { (1,32.14) (2,32.04) (4,27.54) (8,27.89) (16,19.15) (32,24.37) (64,2.48) };\addlegendentry{$\Delta_{\mathrm{Speed}}$} \end{axis} \end{tikzpicture} \caption{Speed (token/sec) and $\Delta_{\mathrm{Speed}}$ [\%] vs. batch size on WMT14 En-De translation task.} \label{fig:parallel} \end{figure} \subsection{Training Study} We plot the training and validation loss curve of the standard baseline, the balanced baseline and \my{} in \fig{fig:curve} for studying their convergence. We can see that all systems converge stably. The balanced baseline has a higher loss than the standard baseline in both the training and validation sets, but their BLEU scores are close as shown in \tab{tab:wmt14}. This is due to the shallow decoder in the balanced baseline. Since the loss is determined by the decoder, a shallow decoder with less capacity would have a higher loss. \citet{DBLP:conf/acl/WangLXZLWC19} indicates that the encoder depth has a greater impact than the decoder on BLEU scores, therefore the deep encoder makes up the performance loss of the shallow decoder. We also see that \my{} has a higher loss than the balanced baseline because we compress the decoder. Since we do not enhance the encoder, the BLEU score drops accordingly. \section{Related Work} \subsection{Model Acceleration} Large Transformer has demonstrated its effectiveness on various natural language processing tasks, including machine translation \cite{DBLP:conf/nips/VaswaniSPUJGKP17}, language modelling \cite{DBLP:conf/iclr/BaevskiA19} and etc. The by-product brought by this huge network is the slow inference speed. Previous work focuses on improving model efficiency from different perspectives. For example, knowledge distillation approaches treat the large network output as the ground truth to train a small network \cite{DBLP:conf/emnlp/KimR16}. Low-bit quantization approaches represent and run the model with 8-bit integer \cite{DBLP:conf/ijcai/LinLLXLZ20}. Our work follows another line of researches, which purses a more efficient architecture. \citet{DBLP:conf/acl/FosterVUMKFJSWB18} show that the attention of Transformer benefits the encoder the most and the decoder could be safely replaced by a recurrent network. This way reduces the complexity of the decoder to linear time but incurs a high cost in training. \citet{DBLP:conf/acl/XiongZS18} show that the self-attention is not necessary and a simple averaging is enough. \citet{DBLP:conf/ijcai/XiaoLZ0L19} indicate that most attention distributions are redundant and thus share these distributions among layers. \citet{DBLP:conf/iclr/KitaevKL20} use locality-sensitive hashing to select a constant number of words and perform attention on them. \citet{DBLP:conf/iclr/FanGJ20} train a large Transformer and drop some layers at testing for fast inference. \citet{DBLP:conf/iclr/Gu0XLS18} use a non-autoregressive decoder to predict the whole sentence at one time instead of generating it word by word. This approach makes a linear time translation process to constant time via the parallel computation. Perhaps the most related works are \citet{DBLP:conf/nips/HeTXHQ0L18,DBLP:conf/emnlp/ZhangTS19}. They merge the self-attention and cross-attention and share their parameters. We, on the other hand, use different sets of parameters for each attention and mathematically prove that this way is equivalent to the standard Transformer under some mild conditions. We further show that the attention and FFN could also be merged together due to their linearity. \subsection{Deep Transformer} Recent studies have shown that deepening the Transformer encoder is more beneficial than widening the encoder or deepening the decoder \cite{DBLP:conf/emnlp/BapnaCFCW18}. \citet{DBLP:conf/acl/WangLXZLWC19} show that placing the layer normalization before (Pre-Norm) rather than behind (Post-Norm) the sub-layer allows us to train deep Transformer. \citet{DBLP:journals/corr/abs-2002-04745} prove that the success of the Pre-Norm network relies on its well-behaved gradient. \citet{DBLP:conf/emnlp/ZhangTS19} suggest that a proper initialization is enough to train a deep Post-Norm network. \citet{DBLP:journals/corr/abs-2006-10369} similarly exploit this observation but to build a faster instead of a better model. They show that using knowledge distillation, a deep encoder and shallow decoder model could run much faster without losing any performance. Based on their work, we use this model as our baseline system and evaluate it on extensive machine translation tasks without knowledge distillation. \begin{figure} \centering \begin{tikzpicture} \begin{axis}[ width=0.8\linewidth,height=0.6\linewidth, yticklabel style={/pgf/number format/fixed,/pgf/number format/precision=1}, ylabel={Loss}, ylabel near ticks, xlabel={\#Epoch}, xlabel near ticks, enlargelimits=0.05, xtick distance=3, xmajorgrids=true, ymajorgrids=true, grid style=dashed, every tick label/.append style={font=\small}, label style={font=\small}, ylabel style={yshift=5pt}, legend style={font=\small,inner sep=3pt}, legend image post style={scale=1}, legend columns=1, legend cell align={left}, ] \addplot [lyygreen,very thick] coordinates { (1,7.695) (2,5.222) (3,4.870) (4,4.713) (5,4.626) (6,4.569) (7,4.528) (8,4.496) (9,4.471) (10,4.450) (11,4.433) (12,4.418) (13,4.404) (14,4.393) (15,4.383) (16,4.373) (17,4.365) (18,4.357) (19,4.350) (20,4.344) (21,4.338) }; \addlegendentry{Baseline} \addplot [lyyred,very thick] coordinates { (1,8.129) (2,5.515) (3,5.151) (4,4.990) (5,4.901) (6,4.843) (7,4.800) (8,4.768) (9,4.741) (10,4.720) (11,4.701) (12,4.685) (13,4.672) (14,4.660) (15,4.649) (16,4.639) (17,4.630) (18,4.622) (19,4.615) (20,4.608) (21,4.601) }; \addlegendentry{Balanced} \addplot [lyyblue,very thick] coordinates { (1,8.384) (2,5.663) (3,5.306) (4,5.144) (5,5.055) (6,4.996) (7,4.952) (8,4.919) (9,4.893) (10,4.870) (11,4.852) (12,4.835) (13,4.821) (14,4.809) (15,4.797) (16,4.787) (17,4.778) (18,4.770) (19,4.762) (20,4.755) (21,4.748) }; \addlegendentry{\my{}} \addplot [lyygreen,dashed,very thick] coordinates { (1,4.759) (2,4.220) (3,4.004) (4,3.914) (5,3.868) (6,3.825) (7,3.797) (8,3.775) (9,3.770) (10,3.759) (11,3.740) (12,3.729) (13,3.724) (14,3.715) (15,3.719) (16,3.707) (17,3.701) (18,3.700) (19,3.691) (20,3.682) (21,3.682) }; \addplot [lyyred,dashed,very thick] coordinates { (1,5.057) (2,4.451) (3,4.211) (4,4.106) (5,4.047) (6,3.993) (7,3.964) (8,3.940) (9,3.932) (10,3.923) (11,3.898) (12,3.893) (13,3.885) (14,3.871) (15,3.874) (16,3.864) (17,3.863) (18,3.857) (19,3.853) (20,3.846) (21,3.846) }; \addplot [lyyblue,dashed,very thick] coordinates { (1,5.270) (2,4.619) (3,4.362) (4,4.261) (5,4.203) (6,4.145) (7,4.111) (8,4.191) (9,4.080) (10,4.072) (11,4.053) (12,4.040) (13,4.033) (14,4.025) (15,4.027) (16,4.013) (17,4.009) (18,4.008) (19,4.003) (20,3.993) (21,3.986) }; \end{axis} \end{tikzpicture} \caption{Loss vs. \# of epochs on WMT14 En-De translation task (solid lines are the training losses, dashed lines are the validation losses).} \label{fig:curve} \end{figure} \section{Conclusion} In this work, we propose \my{}, whose decoder layer consists of only one attention. \my{} offers consistent acceleration by providing a high degree of parallelism. Experiments on 14 WMT machine translation tasks show that \my{} is 2.82$\times$ faster than the baseline. We also use a stronger baseline for comparison. It employs a deep encoder and a shallow decoder, and is 2$\times$ faster than the standard Transformer baseline without loss in performance. \section*{Acknowledgments} This work was supported in part by the National Science Foundation of China (Nos. 61876035 and 61732005), and the National Key R\&D Program of China (No. 2019QY1801). The authors would like to thank anonymous reviewers for their comments.
{'timestamp': '2021-07-20T02:26:31', 'yymm': '2101', 'arxiv_id': '2101.00542', 'language': 'en', 'url': 'https://arxiv.org/abs/2101.00542'}
arxiv
\subsection{Interdisciplinary research in terms of citation interactions} Various research questions such as ``which field will collaborate with which field in future?", ``Which field will receive more citations from recently published papers?", etc., can be addressed with the help of the underlying citation networks among the articles. Nowadays, research is performed by combining the ideas from multiple disciplines. In~\cite{Hazra:2019} the authors have analyzed the interdisciplinarity among the two basic science fields -- Mathematics and Physics and one fast growing field -- Computer Science. Further they observe how the citation from papers of one discipline flows to the papers of another discipline over the years. They observe that in initial years huge amount of citation flows from Physics to Mathematics and vice versa. Over the years, Computer Science started gaining citation from Mathematics. In the recent years, both the basic science fields tend to massively cite papers from Computer Science. They observe how popularity of some topics decreases over the time. They found that the Computer Science papers mostly cites the quantum physics sub-field for long time span. In late '90s, Physics mostly cites information theory papers of Computer Science but in recent times it mostly cites papers from machine learning and social \& information networks domain. Further, interdisciplinarity has been studied in different fields including biology~\cite{Morillo:2003}, mathematics~\cite{Morillo:2003}, cognitive science~\cite{Till:2016,Kwon:2017}, social science~\cite{Pedersen:2016}, humanities~\cite{Pedersen:2016}. Various studies ~\cite{Barthel:2017,Sayama:2012,Till:2016} have attempted to propose novel metrics to measure the degree of interdisciplinarity based on researchers’ scientific impact, collaborator’s knowledge, publication history, etc. In addition, metric for measuring interdisciplinarity of an article has been proposed~\cite{Till:2016} where authors’ research area, publications in different domains have been used to define the metric. A study~\cite{Chen:2015} has been carried out to analyze the interdisciplinarity nature of highly cited articles from Thomson Reuters’ databases published in between 1900-2012 years. \subsection{Analyzing and modelling the citation dynamics} Several studies have been carried out in the past to model the temporal dynamics of citation networks. In order to model the temporal dynamics of citation networks, researchers traditionally used preferential attachment~\cite{RevModPhys.74.47} and copying based~\cite{ravikumarFOCS2000} models. In~\cite{verstak2014shoulders}, the authors investigated the citation behavior of older papers in various fields. They concluded that older articles receive more citations over the years. It is observed that in 2013, 36\% of citations flowed toward the at least ten years old papers. However, a re-investigation of this study showed that the observations are only partly true since the authors did not take into account the accelerating volume of publications over time. In order to tackle the tug-of-war between obsolescence and entrenchment, recently, in~\cite{relaylink}, the authors proposed a complex model based on the idea of \textit{relay-linking} where the older article relays a citation to a recently published article. This model has very less number of parameters and fits with the real data much better than the traditional models. Yet another novel citation growth model called RefOrCite~\cite{PANDEY2020101003} have been proposed recently where the authors allow copying from the references (out-edges) and citations (in-edges) of an article (as opposed to only references in the traditional setup). It is observed that RefOrCite model fits well with real compared to the previous models. \subsection*{Citation count prediction} Predicting future impact of scientific articles is important for making decision in fund allocation (by funding agencies), recruitment etc. There are various works~\cite{10.1007/978-3-319-18038-0_51, 10.5555/3060832.3060995, Yuan2018ModelingAP, li-etal-2019-neural} that have been carried out in the past to automatically estimate the citation count of scientific articles. In this article, we shall mainly focus on the recent literature. In 2015, the authors in~\cite{10.1007/978-3-319-18038-0_51} proposed Trend-based Citation Count Prediction (T-CCP) model where the model first would first learn the type of the citation trends of the articles and then predict the citation count for that trend. All the articles were categorized into five citation trend categories based on the ``burst’’ time (``burst time’’ is the time when the paper gets maximum citations) -- early burst, middle burst, late burst, multi bursts, and no bursts. Two types of features have been used – (a) publication related features like author centric features (i.e., h-index, number of papers published, citation count, number of collaborators), publication venue (average citation count, impact factor etc.) and (b) reinforcement features which are the graph based features (i.e., PageRank, HITS etc.) calculated from weighted citation network among authors. In their model, they mainly use SVR and SVM (LibLinear) for citation count prediction and classification task respectively. In paper~\cite{MayankCIKM2015}, the authors found that the knowledge gathered from citation context within the article could help to predict future citation count. Number of occurrences of the citations for a paper within the article and the average number of words in citation context, have been derived from citation context knowledge. Further they categorized the articles into six citation profiles (PeakInit, PeakMul, PeakLate, MonDec, MonIncr, Oth) and found that the above two citation context based features are able to nicely distinguish these six categories. In~\cite{MayankJCDL2017}, the authors observed that the long term citation of an article depends on the citations it receives in the early years (within one or two years from its publication date). The authors who cite an article in its early years are called early citer. Early citers based on whether they are influential or not affect the long term citation count of the article. In most cases, influential authors negatively affect the long term citation of an article. In~\cite{10.5555/3060832.3060995}, the authors have proposed a novel point process method to predict the citations of individual articles. In their approach they tried to capture two properties -- the ``rich gets richer'' effect and the recency effect. The authors in~\cite{Yuan2018ModelingAP} used four factors -- intrinsic quality (citation count) of a paper, aging effect, Mathew effect and recency effect to derive a model called long term individual level citation count prediction (LT-CCP). In this model they mainly use RNN with LSTM units. It is observed that LT-CPP model achieves better performance than existing models. Authors in~\cite{li-etal-2019-neural} proposed a neural model for predicting citation count with the help of peer review text. They mainly learn two deep features -- (a) the abstract-review match mechanism (in order to learn the abstract aware review representation) and (b) the cross review match from peer review text. \subsection{Citation recommendation} Often new researchers face difficulties in finding appropriate published research papers while exploring the domain literature and citing published papers. Citation recommendation is a technique that recommends appropriate published articles for the given text/sentence. The sentences present around the reference (placeholder) are called context sentences. Citation recommendation task can be divided into two parts – (i) local citation recommendation, and (ii) global citation recommendation. In case of local citation recommendation, only the context sentences are used. In case of global citation recommendation, the whole article is used as input and the system outputs a list of published papers as output. In cite~\cite{bhagavatula-etal-2018-content} the authors proposed a model for the global citation recommendation task where they embedded the textual information (i.e., the title and the abstract) of the candidate citations in a vector space and considered the nearest neighbors as the candidate citations for the target document. Further, re-ranking of the candidate citations was done. They used DBLP (50K articles having an average citation of 5 per article) and PubMed (45K articles with average citation of 17 per article) datasets and also introduced a new dataset OpenCorpus (7 million articles) in the paper. They showed that their model achieved state-of-the-art performance without using metadata (authors, publication venues, keyphrases). In paper~\cite{jeong2019contextaware}, the authors proposed a deep learning model (consists of context encoder and citation encoder) and used a dataset~\cite{10.1145/1772690.1772734} for context aware citation recommendation. Pre-trained BERT~\cite{devlin-etal-2019-bert} model has been used in order to learn the embedding of the context sentences. GCN has been employed to learn the citation graph embedding from the paper-paper citation graph. They mainly revised two existing datasets -- AAN and FullTextPeerRead (revised version of PeerRead). They showed that their model performed three times better than the SOTA approaches (CACR etc.). The authors in~\cite{10.1145/3383583.3398609} proposed a novel method -- ConvCN -- based on the citation knowledge graph embedding. \subsection{Detection of anomalous citation flows} Various anomalous citation patterns have been found to emerge over the years. Various ways of maliciously increasing one’s citation are through {\em self-citations}, {\em citation stacking} among journals, and {\em citation cartel}. Nowadays, authors are more concerned about their position in academia, publication pressure etc. and this leads to most of them adopting unfair means to increase their citation. {\em Citation cartel} is one of the anomalous citation patterns which was first reported in late '90s\footnote{\url{https://science.sciencemag.org/content/286/5437/53}}. {\em Citation cartel} is formed by a group of authors/editors/journals where they cite each other heavily for mutual benefit. The relationship in citation cartel could be author-author, editor-author, journal-journal etc. There are a few cases found where the journal’s impact factor increases rapidly due to this anomalous behavior. {\em Cell Transplantation}\footnote{\url{https://www.cognizantcommunication.com/journal-titles/cell-transplantation}} is a medical journal whose impact factor rapidly increased between 2006 and 2010 (3.48 to 6.20). After investigation carried out by JCR publisher, it was found that one review article published in this journal {\em Medical Science Monitor}\footnote{\url{http://www.medscimonit.com/}} cited almost 91\% papers published in {\em Cell Transplantation} from the time bucket 2008--2009. It was found that the impact factor of the journal {\em Cell Transplantation} was calculated based on this time bucket\footnote{\url{https://scholarlykitchen.sspnet.org/2012/04/10/emergence-of-a-citation-cartel/}}. Surprisingly, the authors (three out of four) are from the editorial board of this journal. In cite~\cite{10.3389/fphy.2016.00049} the authors tried to detect citation cartels. They defined a citation cartel as a group of authors citing each other excessively than they do with other authors' works in the same domain. They observed that there could be multiple reasons like academic pressure, ``publish or perish” concept in academia, fear of losing job, scientific competition etc. behind establishing such citation cartels. It was observed that such unfair means are mostly adopted by low ranked researchers~\cite{Fister2016ANP}. In their work, they prepared a multilayer graph where they include paper-paper citation network (directed graph), authors’ collaboration network and authors’ citation networks (weighted directed graph). Finally, citation cartel has been captured from the authors’ citation network. Cartels have been discovered by using Resource Description Framework (RDF) and RDF query language and some threshold has been declared to identify the existence of citation cartel among authors. The authors in~\cite{kojaku2020detecting} proposed a novel algorithm -- {\em Citation Donors and REcipients} (CIDRE) to detect the {\em citation cartel} among the journals that cite each other disproportionately to increase the impact factor of the journal. CIDRE algorithm first distinguishes between the normal and malicious citation exchange with the help of few parameters. These parameters are similarity in research areas, citation inflow and outflow. A weighted citation network among 48K journals was constructed from the dataset collected from MAG\footnote{\url{https://www.microsoft.com/en-us/research/project/microsoft-academic-graph/}}. With the help of the algorithm, more than half of the malicious journals were detected (those were actually suspended by Thomson Reuters) in the same year. In addition, CIDRE algorithm detected few malicious journal groups in 2019 whose journals received 30\% of its in-flow citation from the journals in the same group. Such anomalous citations help to grow the impact factor of the journals over the years. In~\cite{mayankICADL}, the authors studied how malicious journals are increasing in the Indian research community and avoiding proper rules and regulations. The analysis has been carried out on Indian publishing group OMICS (considered as predatory by the research community). Surprisingly they observed that such malicious journals share very similar characteristics with various reputed journals. \noindent\textbf{Future directions}: In order to gather more citations, malpractices among the journals are rapidly increasing. More research is required to build a mechanism which can automatically predict those (predatory) journals (depending on the topics of the journal). In case of citation recommendation, there is a need for improving the recommendation system such that the system is able to recommend papers that are conceptually similar or exhibit conflicting claims~\cite{F_rber_2020}. Also, prioritizing the citation recommendation would be another help to maintain the page limit given by many conferences~\cite{F_rber_2020}. \section*{Article Title} {\label{350486}} The title should not exceed 20 words. Please be original and try to include keywords, especially before a colon if applicable, as they will increase the discoverability of your article.~\href{https://authorservices.wiley.com/author-resources/Journal-Authors/Prepare/writing-for-seo.html}{Tips on Search Engine Optimization} \section*{Article Type} {\label{925764}} The \href{http://wires.wiley.com/go/forauthors\#ArticleTypes}{Article Type} denotes the intended level of readership for your article. Please select one of the below article type options. An Editor may have mentioned a specific Article Type in your invitation letter; if so, please let them know if you think a different Article Type better suits your topic.~ \begin{itemize} \tightlist \item Opinion \item Primer \item Overview \item Advanced Review \item Focus Article \item Software Focus \end{itemize} \section*{Authors} {\label{290010}} List each person's full name, ORCID iD, affiliation, email address, and any conflicts of interest. Please use an asterisk (*) to indicate the corresponding author. The preferred (but optional) format for author names is First Name, Middle Initial, Last Name.~~ The submitting author is required to provide an~\href{https://authorservices.wiley.com/author-resources/Journal-Authors/Submission/orcid.html}{ORCID iD}, and all other authors are encouraged to do so.~ Wiley requires that all authors disclose any potential conflicts of interest. Any interest or relationship, financial or otherwise, that might be perceived as influencing an author's objectivity is considered a potential conflict of interest. The existence of a conflict of interest does not preclude publication. \section*{Abstract} {\label{468816}} The abstract should be a concise (less than 250 words) description of the article and its implications. It should include all keywords associated with your article, as keywords increase its discoverability (\href{https://authorservices.wiley.com/author-resources/Journal-Authors/Prepare/writing-for-seo.html}{Tips on Search Engine Optimization}). Please try not to include generic phrases such as ``This article discusses \ldots{}'' or ``Here we review,'' or references to other articles. Note: You will be required to copy this abstract into the submission system when uploading your article. Optional: If you would like to submit your abstract in an additional language,~\href{http://wires.wiley.com/go/forauthors\#Resources}{read more}. \section*{Graphical/Visual Abstract and Caption} {\label{750712}} Include an attractive full color image to go under the text abstract and in the online Table of Contents.~\textbf{You will also need to upload this as a separate file during submission.~}It may be a figure or panel from the article or may be specifically designed as a visual summary. While original images are preferred, if you need to look for a thematically appropriate stock image, you can go to~\href{http://pixabay.com/}{pixabay.com}~(not affiliated with Wiley) to find a free stock image with a CC0 license. Another option you have is to utilize professional illustrators with Wiley's~\href{https://wileyeditingservices.com/en/article-preparation/graphical-abstract-design}{Graphical Abstract Design service}. Size: The minimum resolution is 300 dpi. Please keep the image as simple as possible because it will be displayed in multiple sizes. Multiple panels and text other than labels are strongly discouraged. Caption: This is a narrative sentence to convey the article's essence and wider implications to a non-specialist audience. The maximum length is 50 words, but consider using 280 characters or less to facilitate social media sharing, which can increase the discoverability of your article. \par\null \section*{1. Introduction} {\label{252565}} Introduce your topic in \textasciitilde{}2 paragraphs, \textasciitilde{}750 words. While Wiley does consider articles on preprint servers (ArXiv, bioRxiv, psyArXiv, SocArXiv, engrXiv, etc.) for submission to primary research journals, preprint articles should not be cited in WIREs manuscripts as review articles should discuss and draw conclusions only from peer-reviewed research. Remember that original research/unpublished work should also not be included as it has not yet been peer-reviewed and could put the work in jeopardy of getting published in the primary press. Citations are automatically generated by Authorea. Select~\textbf{cite} to find and cite bibliographic resources. The citations will automatically be generated for you in APA format, the style used by most WIREs titles. If you are writing for~\emph{WIREs Computational Molecular Science} (WCMS), you will need to use the Vancouver reference and citation style, so before exporting click Export-\textgreater{} Options and select a Vancouver export style. A sample citation:~~\hyperref[csl:1]{(Murphy et al., 2019)} \section*{2. Hatespeech} {\label{350277}} Begin the main body of the text here, using a maximum of 3 levels of headings (style as shown below and numbered). Try to create headings that: \begin{itemize} \tightlist \item help the reader find information quickly;~ \item are descriptive yet specific; \item are compatible in phrasing and style; and~ \item are concise (less than 50 characters) \end{itemize} \par\null \subsection*{2.1 Spread} {\label{733281}} \subsection*{2.2~Detection} {\label{557980}} \subsection*{2.3~Conterspeech} {\label{791825}}\par\null \section*{3.~Bias and Fairness} {\label{513867}} \subsection*{} {\label{827380}} \subsection*{3.1 Media Bias} \subsection*{3.2~Bias/Fairness in social networks/RINs etc.} \par\null \section*{4. Citation Dynamics (recent trends mostly)} {\label{191005}}\par\null \section*{5.~Wikipedia} {\label{345299}} \subsection*{5.1~Quality} {\label{454445}} \subsection*{5.2~Vandalism, edit war, anomaly} {\label{989700}} \subsection*{} {\label{827380}}\par\null \par\null \section*{Figures and Tables} {\label{432859}} Figures and tables should be numbered separately, in the order in which they appear in the manuscript. Please embed them in the correct places in the text to facilitate peer review. Permission to \textbf{reuse or adapt} previously published materials must be submitted before article acceptance. \href{http://wires.wiley.com/go/forauthors\#Resources}{Resources} Production quality figure files with captions are still to be submitted separately. \href{https://authorservices.wiley.com/asset/photos/electronic_artwork_guidelines.pdf}{Figure preparation and formatting} \textbf{Captions should stand alone} and be informative outside of the context of the article. This will help educators who may want to use a PowerPoint slide of your figure. Explain any abbreviations or symbols that appear in the figure and make sure to include \textbf{credit lines} for any previously published materials. \section*{Conclusion} {\label{880788}} Sum up the key conclusions of your review, highlighting the most promising scientific developments, directions for future research, applications, etc. The conclusion should be \textasciitilde{}2 paragraphs, \textasciitilde{}750 words total. \section*{Funding Information} {\label{974317}} You will be required to enter your funding information into the submission system so that we can apply proper IDs to your funders and help you comply with any funder mandates. \section*{Research Resources} {\label{808103}} List sources of non-monetary support such as supercomputing time at a recognized facility, special collections or specimens, or access to equipment or services. \href{https://orcid.org/organizations/research-orgs/resources}{Research Resources} can also be added to ORCiD profiles. For biomedical researchers, the \href{https://scicrunch.org/resources}{Resource Identification Portal} supports NIH's new guidelines for Rigor and Transparency in biomedical publications. \section*{Acknowledgments} {\label{749861}} List contributions from individuals who do not meet the criteria for authorship (for example, to recognize people who provided technical help, collation of data, writing assistance, acquisition of funding, or a department chairperson who provided general support), \textbf{with permission} from the individual. Thanks to anonymous reviewers are not appropriate. \section*{Notes} {\label{390481}} Authors writing from a humanities or social sciences perspective may use notes if a \textbf{comment or additional information} is needed to expand on a citation. (Notes only containing citations should be converted to references. Conversely, any references containing comments, such as ``For an excellent summary of\ldots{},'' should be converted to notes.) Notes should be indicated by \textbf{superscript letters}, both in the text and in the notes list. Citations within notes should be included in the reference section, as indicated below. \section*{Further Reading} {\label{153582}} For readers who may want more information on concepts in your article, provide full references and/or links to additional recommended resources (books, articles, websites, videos, datasets, etc.) that are not included in the reference section. Please do not include links to non-academic sites, such as Wikipedia, or to impermanent websites. \section*{\texorpdfstring{{Note About References}}{Note About References}} {\label{514168}} References are automatically generated by Authorea. Select~\textbf{cite~}to find and cite bibliographic resources. The bibliography will automatically be generated for you in APA format, the style used by most WIREs titles. If you are writing for~\emph{WIREs Computational Molecular Science}~ (WCMS), you will need to use the~Vancouver reference style, so before exporting click Export-\textgreater{} Options and select a Vancouver export style.~ \selectlanguage{english} \FloatBarrier \section*{References}\sloppy \phantomsection \label{csl:1}{Understanding institutions for water allocation and exchange: Insights from dynamic agent-based modeling}. (2019). \textit{Wiley Interdisciplinary Reviews: Water}, \textit{6}(6). \url{https://doi.org/10.1002/wat2.1384} \end{document} \subsubsection{Fairness in recommendation} The digital platform is full of choices. To help users make intelligent choices, different information filtering systems are deployed in online platforms. Recommendation systems (RSs) are one such omnipresent module. From consumers' perspective, RSs help in finding useful contents; while from platforms' and producers' perspectives RSs bring revenue and profit~\cite{gomez2016netflix, sharma2015estimating}. Given the multi-stakeholder setup and importance of RSs in the livelihood of many of the stakeholders, recommendation fairness is of utmost importance. \vspace{1mm} \noindent \textbf{Filter bubble and evolution of fairness in RSs}: Traditionally, RSs like other information filtering systems are keyed to relevance~\cite{linden2003amazon, smith2017two}. However, over dependency on relevance has led to differential services to different users or different user groups. To describe these effects succinctly, Eli Pariser coined a term `\textit{filter bubble}'~\cite{pariser2011filter}. The filter bubble problem is a concern that personalization technologies, including RSs, narrow and bias the topics of information provided to people while they do not notice these facts. To account for these effects, the field of fairness in recommendation first evolved as `Information Neutrality in RSs'. Focusing on customer fairness (information neutrality toward customers) Kamishima et. al. \cite{kamishima2012enhancement,kamishima2011fairness} tried to solve the unfairness issue in RSs by adding a regularization term that enforces \textit{demographic parity}\footnote{$U_{par}=|E_g[y]-E_{\neg g}[y]|$ can be an instantiation of such demographic parity based regularizers~\cite{yao2017beyond}.}. Such objectives penalized the differences among the average predicted ratings of user groups (based on sensitive attributes, e.g., gender). However, demographic parity is only appropriate when preferences are unrelated to the sensitive features. In tasks such as recommendation, user preferences are indeed influenced by sensitive features such as gender, race, and age~\cite{chausson2010watches,daymont1984job}. Taking a leaf out of the progresses in fairness literature in supervised machine learning~\cite{hardt2016equality, mehrabi2019survey}, Yao et. al.~\cite{yao2017beyond} put forward fairness notions to bridge the gap. They formulated different customer fairness metric by taking a leaf out of the evolution of fairness in supervised learning~\cite{hardt2016equality} and showed their effectiveness in improving customer fairness in recommendation~\cite{yao2017beyond}. Following their footsteps a number of works focused on `group fairness' in personalized recommendations~\cite{zhu2018fairness,edizel2019fairecsys} where first they quantified biases due to recommendation algorithms toward socially salient groups and proposed methodologies to mitigate such biases. However, a major drawback of many of these works was their negligence toward one of the major stakeholder in RSs, i.e., the producer of items/services. This led to a second school of thought when Burke et. al.~\cite{burke2017multisided, burke2018balanced} first advocated for fairness toward both customers and providers in a recommendation framework. Considering RSs as a two-sided affair many nuanced algorithms came into existence considering fairness toward both customers and producers and thus taking a giant step toward a fair marketplace~\cite{mehrotra2018towards,patro2020fairrec,geyik2019fairness}. \begin{figure}[h] \centering \includegraphics[width=4in]{figure/FairRecsys.pdf} \caption{The figure shows the genesis of notions of fairness in recommendation frameworks. In early 2010, it started with the notion of `neutrality in recommendation and by the end of the decade it has evolved into multi-sided fairness toward building a fair marketplace.} \label{Fig: FairRecsys} \end{figure} \vspace{1mm} \noindent \textbf{Auditing RSs}: While the fairness community seems to have covered different forms of biases, there is a lack of understanding of the existing online recommendation systems and biases thereof. Understanding of these systems are especially important today due to the emergence of different private label products (and in-house products) in e-commerce (and OTT) platforms~\cite{Barrett2016Wired,faherty2017amazon,Amazon2019Online}. A private label product is often produced and sold under the retailer's brand name, providing enough monetary incentive to the platforms to be discriminative against several other products (or producers) on the platform. Note that no third party (3P) regulator can quantify such biases because of the lack of access to the exact underlying algorithms and the exact user-item interaction details. To enable such 3P audits, in one of our works, we presented a novel network-based technique that enabled us to extract important parameters for auditing RSs by considering them as black-boxes~\cite{dash2019network}. With detailed analysis on three different existing online RSs, we first proposed ways to quantify their induced diversity and extent of information segregation~\cite{dash2019network}. The usefulness of such a framework is manifold: (a)~it sheds light on how recommendations are formed between items based on different item-centric properties, (b)~it can be used as a tool for quantifying and auditing for different consumer-focused metrics e.g., relevance, diversity, information-segregation etc., (c)~it can be used to quantify different biases toward the associated producers of different items/services, and (d)~finally, it also can be used as a tool for mitigating the existing biases by re-wiring few of the recommendation edges. In another follow-up work, we analyzed the sponsored recommendation on e-commerce marketplaces and showed how they are utilized as a trojan-horse to improve sales of products having special relationship with the marketplace (e.g., private label products)~\cite{dash2021When}. Given that sponsored recommendations potentially have delayed impact on their organic counterparts (by affecting the sales and visibility of products), such studies open up a completely new avenue of research. \noindent \textbf{Future directions: }While the fairness community seems to have covered different forms of biases in recommendation frameworks, it has overlooked the special relationships that may exist between the digital marketplace and a subset of stakeholders, and the biases thereof. Hence, studies of unfairness discovery and mitigation considering the special relationships of platforms remain an under-explored avenue of research till date. The introduction of sponsored search and recommendations complicates the scenario even further. Policies that allow sponsored results to deviate from organic results; while adhering to fairness of marketplace can be another interesting broad direction for further research. \section*{Article Title} \if{0}\begin{itemize} \tightlist \item Opinion \item Primer \item Overview \item Advanced Review \item Focus Article \item Software Focus \end{itemize} \fi \if{0}{\label{290010}} List each person's full name, ORCID iD, affiliation, email address, and any conflicts of interest. Please use an asterisk (*) to indicate the corresponding author. The preferred (but optional) format for author names is First Name, Middle Initial, Last Name.~~ The submitting author is required to provide a~\href{https://authorservices.wiley.com/author-resources/Journal-Authors/Submission/orcid.html}{ORCID iD}, and all other authors are encouraged to do so.~ Wiley requires that all authors disclose any potential conflicts of interest. Any interest or relationship, financial or otherwise, that might be perceived as influencing an author's objectivity is considered a potential conflict of interest. The existence of a conflict of interest does not preclude publication. \fi \if{0}\section*{Abstract} {\label{468816}} The abstract should be a concise (less than 250 words) description of the article and its implications. It should include all keywords associated with your article, as keywords increase its discoverability (\href{https://authorservices.wiley.com/author-resources/Journal-Authors/Prepare/writing-for-seo.html}{Tips on Search Engine Optimization}). Please try not to include generic phrases such as ``This article discusses \ldots{}'' or ``Here we review,'' or references to other articles. Note: You will be required to copy this abstract into the submission system when uploading your article. Optional: If you would like to submit your abstract in an additional language,~\href{http://wires.wiley.com/go/forauthors\#Resources}{read more}. \section*{Graphical/Visual Abstract and Caption} {\label{750712}} Include an attractive full color image to go under the text abstract and in the online Table of Contents.~\textbf{You will also need to upload this as a separate file during submission.~}It may be a figure or panel from the article or may be specifically designed as a visual summary. While original images are preferred, if you need to look for a thematically appropriate stock image, you can go to~\href{http://pixabay.com/}{pixabay.com}~(not affiliated with Wiley) to find a free stock image with a CC0 license. Another option you have is to utilize professional illustrators with Wiley's~\href{https://wileyeditingservices.com/en/article-preparation/graphical-abstract-design}{Graphical Abstract Design service}. Size: The minimum resolution is 300 dpi. Please keep the image as simple as possible because it will be displayed in multiple sizes. Multiple panels and text other than labels are strongly discouraged. Caption: This is a narrative sentence to convey the article's essence and wider implications to a non-specialist audience. The maximum length is 50 words, but consider using 280 characters or less to facilitate social media sharing, which can increase the discoverability of your article.\fi \par\null \section{Introduction} {\label{252565}} \textit{Online infosphere}\footnote{\url{https://en.wikipedia.org/wiki/Infosphere}} is the term corresponding to the Internet becoming a virtual parallel world formed from billions of networks of \textit{artificial life} at different scales ranging from tiny pieces of software to massive AI tools running a factory or driving a car. The motivations for this are diverse, seeking to both help mankind and harm it. In this article, we shall attempt to portray some of the areas that are increasingly gaining importance in research related to the evolution of this infosphere. In particular, we would begin with infosphere as a collaborative platform, Wikipedia being the prime point of discussion. As a next step we would discuss how the infosphere has influenced the evolution of scientific citations and collaborations. Finally, we shall outline the emerging research interest in the governance of this infosphere to eradicate discrimination, bias, abuse and hate. \subsection{Infosphere as a collaborative platform} The infosphere hosts numerous collaborative platforms including question answering sites, folksonomies, microblogging sites and above all encyclopedias. In this survey we shall focus on Wikipedia which is one of the largest online collaborative encyclopedia. We shall primarily discuss two of the most important aspects of Wikipedia -- (a) the quality of an article and its indicators and (b) the collaboration dynamics of Wikipedia editors who constitute the backbone of this massive initiative. Under the first topic we shall identify the different features of an article like its language, structure and stability as well as their quality~\cite{zhang2020mining,halfaker2019ores,sarkar2019stre}. We shall further summarise attempts that have been made to automatically predict the quality of an article~\cite{guda2020nwqm,marrese2019edit}. Within the second topic we shall briefly describe various issues related to the community of editors including anomalies, vandalism and edit wars\cite{Kiesel2017SpatioTemporalAO,Tran2015CrossLanguageLF}. Finally, we shall talk about ways to enabling retention of editors on the platform~\cite{halfaker2013rise,muric2019collaboration,steinmacher2015social}. \subsection{Infosphere shaping scientific citations and collaborations Citations play a crucial role in shaping the evolution of a scientific discipline. With an exponential growth of research publications in various disciplines it has become very important for researchers and scientists to grasp different concepts within a short period of time. We would explore how the infosphere has influenced the growth and interaction of different scientific disciplines over the period of last few years by investigating several different aspects of citation networks. Our survey includes -- (a) a detailed account of how the basic sciences and the computer sciences have interacted with each other over the years resulting in an interdisciplinary research landscape~\cite{Hazra:2019,Morillo:2003} (b) the temporal dynamics of citations~\cite{relaylink}, (c) ways for assessment of article quality, and finally (d) a brief account of anomalous citation flows. \subsection{Governance of the infosphere} The stupendous growth of the infosphere has resulted in the emergence of various online communities that have massively started infusing bias, discrimination, hatred and abuse often resulting in violence in the offline world. In this segment, we shall primarily focus our discussion on the following topics -- (a) analysis, spread, detection and mitigation of online hate speech and (b) biases that manifest across news media and in traditional recommendation systems. Within the first topic we shall motivate the need to tackle online hate speech by citing some of the adverse consequences of the same. In particular, we shall see how unmoderated hate speech spreads in a social network~\cite{Mathew2019,binny_temporalCSCW}, what are the challenges to automatically detect online hate speech~\cite{Gomez2020,aluru2020deep} and the possible techniques to combat this problem~\cite{mathew2020interaction,binnyCounter}. Within the second topic we shall discuss two important forms of biases. The first one corresponds to political biases that manifest due to the massive production of unverified (and in many cases false) news generated in the form of news/blog/tweets etc. We shall also discuss the difficulties faced by modern machine learning techniques in preventing the infusion of such biases. The second one narrates the idea of formation of \textit{filter bubbles}~\cite{pariser2011filter} in traditional recommendation systems followed by a discussion on the need to systematically audit such systems~\cite{dash2019network, dash2021When}. \if{0}{ In this article we have leveraged our four recent and important study on hate-speech, bias and fairness, citation dynamics and wikipedia. With the exponential growth of using social media such as twitter, facebook etc the online hatespeech has become pervasive and raise a serious concern for online communities, social media platforms and government organisations. At the extreme scenario this could even cause for genocide, riots and mass shooting. Though the actual definition of hate-speech varies according to the literature it can be generalized as "abusive language that is used to express hatred towards a targeted group or individual". In the study we have focused on the challenges detecting hate-speech automatically in online social media platforms, advantages and disadvantages previous research works, user-based approach for detecting hate-speech and it's spread. We have analysed the network structure of the spread of hate-speech in online platforms. Lastly we have shown the study of Counter speech to tackle the online hate-speech automatically. Secondly we have shown our study regarding media bias and fairness in recommendation systems. As the booming increase of usage of internet, more specifically social media the sharing of unverified content has become a trend for the normal people as well as for the news media and this has led to fake news propagation by the most of the reputed news media. These unverified contents mostly inclined towards particular aspect and quantifying the bias has become an important area for research. We have shown the vulnerabilities for a mathematical models for detecting media bias as it is strongly relies on the beliefs of the data annotators. Now coming to the recommendation system, it is one of the most important features for any e-commerce sites to provide a strong relevant product information to a customer. However, due to the over dependency on relevance has led to a bias on the topics of information. We leverage the Filter Bubble problem in this article and have shown our research on fairness in recommendation systems. Detecting the citation dynamics and predicting the emerging topics is always an important field of research. We have framed a citation network and tried to analyze the corresponding research problems with the help of citation network. We have shown the interdisciplinary research in terms of citation interaction and observed the interdisciplinary citation flow. We also analyzed the dynamics of citation network and compare it with the 'rich gets richer' property. We have studied the importance of citation count prediction and analyzed several simple statistical models and also neural network models for predicting citation count of scientific articles. Citation recommendation is also an important study for new researchers to find appropriate published articles for their given research problems. We have differentiated the local and global citation recommendations based on the context of citation and analyzed several neural network based models. There is also possibility of malicious citation flow by the authors for self-benefit in the citation network and it is also important to detect those malicious citation flow in the dynamics of citation network. We have also studied few effective algorithm to prevent these anomalous citation flow. The wiki model acts as an open and free knowledge base including large variety of information ranging from history, arts and politics to science and technology and many more fields using wide variety of languages. We have shown our study on the quality of wiki-data based on the article structure, article stability, automatic methods for quality detection and many other features. Apart from that we have also discussed the problems regarding anomaly and vandalism for content editing and retention of reliable editors. Introduce your topic in \textasciitilde{}2 paragraphs, \textasciitilde{}750 words. While Wiley does consider articles on preprint servers (ArXiv, bioRxiv, psyArXiv, SocArXiv, engrXiv, etc.) for submission to primary research journals, preprint articles should not be cited in WIREs manuscripts as review articles should discuss and draw conclusions only from peer-reviewed research. Remember that original research/unpublished work should also not be included as it has not yet been peer-reviewed and could put the work in jeopardy of getting published in the primary press. Citations are automatically generated by Authorea. Select~\textbf{cite} to find and cite bibliographic resources. The citations will automatically be generated for you in APA format, the style used by most WIREs titles. If you are writing for~\emph{WIREs Computational Molecular Science} (WCMS), you will need to use the Vancouver reference and citation style, so before exporting click Export-\textgreater{} Options and select a Vancouver export style. A sample citation:~~\hyperref[csl:1]{(Murphy et al., 2019)} } \fi \section{Wikipedia as a collaborative platform} Wikipedia models a hypertext collaborative platform along with an open and free knowledge base catering a large variety of information ranging from history, arts, culture, politics to science, technology and many more fields. Being one of the most widely viewed sites (within top ten) in the world since 2007, it spans over 208 languages with a copious amount of articles in each edition. For example, the English-language Wikipedia, the largest in volume, contains more than 6 million articles as of February, 2020. Owing to the collaborative nature and an open-access policy announced by Wikipedia as ``anyone can edit'', a number of challenges have cropped up in maintaining the veracity-quality balance of the content. Although Wikipedia has enforced several rules and strict administrative policies to protect the encyclopedia from malicious activities, a lack of authoritative vigilance prohibits its trustworthiness in academics. In contrast, Wikipedia's structured, complete and detailed evolution history receives increasing attention of the research community in discovering automated solution (e.g. bots, software, API etc.) to meet the goal of quality management. \subsection{Quality} The elementary purpose of Wikipedia is free, unbiased, accurate information curation. To achieve this objective Wikimedia foundation which is the governing body of the platform, has developed labyrinth of guidelines which editors are expected to follow so that highest encyclopedic standards are maintained. These guidelines also enhance accessibility of the Wikipedia articles to a broad community of netizens. We enumerate these guidelines into three categories as discussed below. \subsubsection{Article language} Expressions describing a subject should be neutral. Promotion bearing words such as {\em renowned, visionary, iconic, virtuoso etc.} should not be used. Subject importance should be demonstrated using facts and attribution\footnote{\url{https://en.wikipedia.org/wiki/Wikipedia:Manual\_of\_ Style/Words\_to\_watch}} Prose should have active voice. Jargon needs to be elaborated or substantiated with reference. Any effort to propagate myth or contentious content should be curtailed. An example for this is addition of prefix {\em pseudo} or suffix {\em -gate} which encourages the reader to assume that the subject is factitious or scandalous respectively. Euphemisms (e.g., {\em passed away, collateral damage} and cliches (e.g., { \em lion's share, tip of the iceberg}) disallows presentation of prose directly and hence is restricted. Any unnecessary emphasis in the form of italics, quotations etc. is discouraged. For a complete list of details of content guidelines for the English Wikipedia we refer the reader to the Wikipeida manual of style\footnote{\url{https://en.wikipedia.org/wiki/Wikipedia:Manual\_of\_Style}}. \subsubsection{Article structure} These guidelines include proper formatting of the Wikipedia article in terms of section headings, infobox, article name, section organisation etc. The lead section should not be of arbitrary length. The following sections should not be exorbitant in size and bigger sections should be broken into coherent smaller sections. Another requirement is proper positioning of the images with captions and references. In order to alleviate manual labor in improving article structure there have been some automated approaches leveraging advances in machine learning techniques~\cite{jana2018wikiref}. \subsubsection{Article stability} These guidelines denote stability of the article, i.e., the respective article should not be subject of frequent \textit{edit wars}. There should not be abusive language exchange among editors and discussions toward improving article quality should organically reach consensus. This is the most difficult objective in collaborative content creation and generally the onus lies in the hands of senior level editors and moderators for smooth conflict arbitration. \subsubsection{Peer review framework} Although Wikipedia has grown significantly in terms of volume and veracity over the last decade, the quality of articles is not uniform~\cite{warncke2015success}. The quality of Wikipedia articles is monitored through a rating system where each article is assigned one of several class indicators. Some of the {\em major} article categories are \textbf{FA}, \textbf{GA}, \textbf{B}, \textbf{C}, \textbf{Start} and \textbf{Stub}. Most complete and dependable content is annotated by an FA ({\em aka featured article}) tag while the lowest quality content is annotated with a Stub tag. The intention behind this elaborate scheme is to notify editors regarding current state of the article and extent of effort needed for escalating to encyclopedic standards\footnote{\url{wiki/Wikipedia:WikiProject Wikipedia/Assessment}}. The editors are expected to rigorously follow the aforementioned guidelines. As has been evident from the guidelines, they are circuitous and often require experience for implementation. Such strict policy adherence have also been sometimes a barrier for onboarding of new editors on Wikipedia which has led to the decline of newcomers over the past decade~\cite{steinmacher2015social,halfaker2011don}. Since it is nontrivial to discern qualifying differences between articles manually, it has given rise to the emergence of automated techniques using machine learning models. \subsubsection{Computational methods for quality prediction} Automatic article assessment is one of the key research agendas of the Wikimedia foundation\footnote{\UrlFont{www.mediawiki.org/wiki/ORES}}. One of the preliminary approaches~\cite{halfaker2015artificial} seeking to solve this problem extracted structural features such as presence of infobox, references, level 2 headings etc. as indicators of the article quality.~\cite{dang2016quality} proposed the first application of deep neural networks into quality assessment task where they employed distributional representation of documents~\cite{le2014distributed} without using manual features. The authors in \cite{shen2017hybrid} introduce a hybrid approach, where textual content of the Wikipedia articles are encoded using a BILSTM model. The hidden representation captured by the sequence model is further augmented with handcrafted features and the concatenated feature vector is used for final classification. ~\cite{zhang2018history} is an edit history based approach where every version of an article is represented by $17$ dimensional handcrafted features. Hence, an article with $k$ versions will be represented by $k \times 17$ matrix. This $k$ length sequence is passed through a stacked LSTM for final representation used in classification. ~\cite{shen2019joint} proposed a multimodal information fusion approach where embeddings obtained from both article text as well as html rendering of the article webpage is used for final classification. ~\cite{guda2020nwqm} proposed the first approach which incorporates information from three modes for quality assessment, i.e., article text, article image and article talk page.~\cite{guda2020nwqm} obtains $8\%$ improvement over~\cite{shen2019feature} approach and achieves the SOTA result. A complementary direction of exploration has been put forward by~\cite{li2015automatically,de2015measuring} where correlation between article quality and structural properties of co-editor network and editor-article network has been exploited. An orthogonal direction of research looks into edit level quality prediction which is a fine-grained approach toward article content management~\cite{sarkar2019stre}. \subsection{Collaboration among editors} The workhorse behind the success story of Wikipedia is the large pool of its voluntary editors; an encouragement toward global collaboration influences people to contribute on almost all wikipages. These group of people maintain Wikipedia pages behind the scenes which includes creating new pages, adding facts and graphics, citing references, keeping the wording and formatting appropriate etc. to lead the articles to the highest level of quality. The achievement of any open collaborative project is hinged on the continued and active participation of its collaborators, and hence, Wikipedia needs to manage its voluntarily contributing editor community carefully. In the days of extreme socio-cultural polarization, algorithmically crafted filter bubbles and fake information represented as facts, editors are highly motivated to contribute to the largest non-biased knowledge sharing platform although their works are not financially compensated most of the times \cite{littlejohn2018becoming}. In these lines there have been several works \cite{yang2016did,muric2019collaboration}, which attempt to understand the dynamics of interaction behaviours of the community in sustaining the health of Wikipedia. \subsubsection{Anomaly} While investigating the editing behaviours of editors in general context, researchers have found out a taxonomy of semantic intentions behind the edits, and conflicts and controversy are inherent components of the classification. Wikipedia owes its success for several reasons and openness is one of those pillars. Sometimes, the very openness misguides editors to violate Wikipedia's strict guidelines of the neutral-point of view (NPOV), and their disruptive edits cause various kinds of anomalies. We describe the two dominant disputes, produced by the damaging edits as follows. \noindent\textit{Vandalism}: With the freedom of editing anything by anyone, Wikipedia has to struggle in stopping the malicious practice of contaminating articles by bad faith edits intentionally. The popular pages like famous celebrities, controversial topics etc. become the frequent targets of vandalism where vandals try to mislead the readers by addition, deletion or modification, which can be termed as hoax. Wikipedia has enforced several strict policies such as blocking and banning Vandals (registered / unregistered editors), patrolling recent changes by adding watch-lists, protecting articles (ex, semi-protected pages) from new editors, random IP addresses etc. In addition to the administrative decisions, bots \footnote{\url{https://en.wikipedia.org/wiki/User:ClueBot\_NG}} are employed to detect and revert the vandalism automatically and finally warn the editors without human intervention. Researchers have proposed various automated ways \cite{Spezzano2019DetectingPT,Kiesel2017SpatioTemporalAO}, i.e., the state-of-the-art techniques based on machine learning \cite{Kumar2015VEWSAW, Susuri2016MachineLB} and deep neural methods~\cite{MartinezRico2019CanDL,Tran2015CrossLanguageLF} in preventing Wikipedia from vandalism. \noindent\textit{Edit war}: Apart from the intended malpractice of vandalism, editors often engage themselves in disagreement which further influence them to override each other's contribution instead of dispute resolution. Any such actions violating the three-revert rule\footnote{\url{https://en.wikipedia.org/wiki/Wikipedia:Edit\_warring}} is coined as edit warring in Wikipedia and it promotes a toxic environment in the community. Ultimately in the long-term, the integrity of the encyclopedia will be affected significantly by the damaging effects of edit wars \cite{Ruprechter2020RelatingWA}. Although Wikipedia encourages editors to be \textit{bold}, in contrast a constant refusal to \textit{get the point} is also not entertained. \subsubsection{Retention of editors} Historically, Wikipedia managed the numbers of its volunteers quite successfully; however, experts \cite{halfaker2013rise} note that it is at the danger of sharp decline of its active editors due to the lack of the socialization effort. Editors may choose to leave the platform for personal reasons as well as for their disagreement/conflict with their fellow editors. The damage is happening in both ways - when new editors fail to inherit the rules and policies they easily become upset and leave eventually. Experienced editors, on the other hand, can get discouraged because of the continuous upgradation of policies to retain newcomers, or even for the nuisances by the newbies. Two way effort are being taken to combat with this problem -- researchers are coming up with various approaches (see~\cite{Morgan2013TeaAS,Morgan2018EvaluatingTI,yazdanian2019eliciting} and the refereces therein) while Wikipedia itself is running several wikiprojects\footnote{\url{https://en.wikipedia.org/wiki/Wikipedia:WikiProject\_Editor\_Retention}}$^{,}$\footnote{\url{https://en.wikipedia.org/wiki/Wikipedia:Expert\_retention}} to proactively retain its contributors. \noindent \textbf{Future directions}: Due to the enormous volume of data publicly available from various multilingual wikiprojects, several interesting future directions can be explored. One of the directions is combating repeat abusers who add malicious content annonymously after being blocked through sockpuppetry~\cite{maity2017detection} or collusion. A large volume of effort has been invested in understanding editor behaviour; however, similar large scale exploration need to be done on understanding readers. A promising start in this direction includes the following ~\cite{johnson2020global,ribeiro2020sudden}. However, further work needs to explore the interplay between editors and readers and how these two stakeholders can forge a partnership in mutually beneficial fashion. We refer to the mediawiki research index \footnote{\url{https://meta.wikimedia.org/wiki/Research:Index}} for a comprehensive take on this emerging research scope. \section{Recent trends in citation dynamics} \input{CitationDynamics.tex} \section{Governance} As noted in the introduction, this section is laid out into two major parts. The former part centers around the spread, automatic detection and containment of hate speech. The latter part deals with bias in media outlets and online recommendation platforms. \subsection{Hate speech} \subsubsection{Spread} The Internet is one of the greatest innovations of mankind which has brought together people from every race, religion, and nationality. Social media sites such as Twitter and Facebook have connected billions of people\footnote{\url{https://techcrunch.com/2018/07/25/facebook-2-5-billion-people}} and allowed them to share their ideas and opinions instantly. That being said, there are several ill consequences as well such as online harassment, trolling, cyber-bullying, and \emph{hate speech}. \noindent\textbf{The rise of hate speech}: Hate speech has recently received a lot of research attention with several works that focus on detecting hate speech in online social media~\cite{davidsonautomated,del2017hate,Badjatiya:2017:DLH:3041021.3054223,saha2018hateminers,kshirsagar2018predictive}. Even though several government and social media sites are trying to curb all forms of hate speech, it is still plaguing our society. With hate crimes increasing in several states\footnote{\url{http://www.aaiusa.org/unprecedented_increase_expected_in_upcoming_fbi_hate_crime_report}}, there is an urgent need to have a better understanding of how the users spread hateful posts in online social media. Companies like Facebook have been accused of instigating anti-Muslim mob violence in Sri Lanka that left three people dead\footnote{\url{https://www.theguardian.com/world/2018/mar/14/facebook-accused-by-sri-lanka-of-failing-to-control-hate-speech}} and a United Nations report blamed them for playing a leading role in the possible genocide of the Rohingya community in Myanmar by spreading hate speech\footnote{\url{https://www.reuters.com/investigates/special-report/myanmar-facebook-hate}}. In response to the UN report, Facebook later banned several accounts belonging to Myanmar military officials\footnote{\url{https://www.reuters.com/article/us-myanmar-facebook/facebook-bans-myanmar-army-chief-others-in-unprecedented-move-idUSKCN1LC0R7}} for spreading hate speech. In the recent Pittsburgh synagogue shooting\footnote{\label{pittsburg_shooting} \url{https://en.wikipedia.org/wiki/Pittsburgh_synagogue_shooting}}, the sole suspect, \emph{Robert Gregory Bowers}, maintained an account (@onedingo) on Gab\footref{https://gab.com/} and posted his final message before the shooting\footnote{\url{https://www.independent.co.uk/news/world/americas/pittsburgh-synagogue-shooter-gab-robert-bowers-final-posts-online-comments-a8605721.html}}. Inspection of his Gab account shows months of anti-semitic and racist posts that were endorsed by a lot of users on Gab. \noindent\textbf{Understanding the spread of hate speech}: We perform the first study which looks into the diffusion dynamics of the posts by hateful users in Gab~\cite{Mathew2019}. We choose Gab for all our analysis. This choice is primarily motivated by the nature of Gab, which allows users to post content that may be hateful in nature without any fear of repercussion. This provides an unique opportunity to study how the hateful content would spread in the online medium, if there were no restrictions. To this end, we crawl the Gab platform and acquire 21M posts by 341K users over a period of 20 months (October, 2016 to June, 2018). Our analysis reveals that the posts by hateful users tend to spread faster, farther, and wider as compared to normal users. We find that the hate users in our dataset (which constitute 0.67\% of the total number of users) are very densely connected and are responsible for 26.80\% of posts generated in Gab. We also study the temporal effect of hate speech on the users and the platform as well~\cite{binny_temporalCSCW}. To understand the temporal characteristics, we needed data from consecutive time points in Gab. As a first step, using a heuristic~\cite{meeder2011we}, we generate successive graphs which capture the different time snapshots of Gab at one month intervals. Then, using the DeGroot model~\cite{degroot1974reaching}, we assign a hate intensity score to every user in the temporal snapshot and categorize them based on their degrees of hate. We then perform several \textit{linguistic} and \textit{network} studies on these users across the different time snapshots. We find that the amount of hate speech in Gab is consistently increasing. This is true for the new users joining as well. We further find that the recently joining new users take much less time to turn hateful as compared to those that joined at earlier time periods. In addition, the fraction of users becoming hateful is increasing as well. Also, we find that the language used by the community as a whole is becoming more correlated with that of the hateful users as compared to the non-hateful ones. The hateful users also seem to be playing a pivotal role from the network point of view. \subsubsection{Detection} Due to the massive scale of online social media, methods that automatically detect hate speech are required. In this section, we explore a few of the methods that try to automatically detect hate speech. Some of the approaches utilize Keyword-based techniques, machine learning models, etc. Perceiving the right features for a classification problem can be one of the challenging tasks when using machine learning. Though surface-level features, such as bag of words, uni-grams, larger n-grams, etc.~\cite{chen2012,vanhee2015} have been used for this problem, since hate speech detection is usually applied on small pieces of text, one may face a data sparsity problem. Lately, neural network based distributed word/paragraph representations, also referred to as \textit{word embeddings/paragraph embeddings}~\cite{Djuric2015} have been proposed. Using large (unlabelled) text corpus, for each word or for a paragraph a vector representation is induced~\cite{mikolov2014} that can eventually be used as classification features, replacing binary features indicating the presence or frequency of particular words. Hate speech detection is a task that cannot always be solved by using only lexicon based features/ word embedding. For instance, \textit{`6 Million Wasn't Enough`} may not be regarded as some form of hate speech when observed in isolation. However, when the context is given that the utterance is directed toward Jewish people who were killed in the holocaust by white supremacists and Neo Nazis\footnote{\url{https://www.vice.com/en/article/y3z9aj/a-national-guard-twitch-streamer-said-6-million-wasnt-enough-on-stream}}, one could infer that this is a hate speech against Jews. The above example shows us whether a message is hateful or not can be highly dependent on world knowledge. In~\cite{leigeo2017}, the authors annotated context dependant hate speech and showed that incorporating context information improved the overall performance of the model. Apart from world knowledge, meta-information (i.e., background information about the user of a post, number of posts by a user, geographical origin) can be used as a feature to improve the hate speech detection task. Since the data commonly comes from the online social media platform, variety of meta-information about the post can be collected while crawling the data. A user who is known to post mostly hateful content, may do so in the future. Existing research~\cite{Mathew2019} has found that, high number of hateful messages are generated from less number of users. It has been also observed that men are more likely to spread hate speech than women~\cite{Waseem2016}. Also, the number of profane words in the post history of user has been used as a feature for hate speech classification task~\cite{Dadvar2013}. Nowadays the number of posts which consists of images, audios, and video content are getting shared more in Social media platforms. In~\cite{Gomez2020}, the authors have explored the textual and visual information of images for the hate speech detection task. Most of the methods that have been explored earlier were supervised and heavily dependant on the annotated data. Off-the-shelf classifiers such as logistic regression, support vector machines have been extensively used. Recently, deep neural models are being extensively used for the classification task. In~\cite{aluru2020deep}, the authors explored several models such as CNN-GRU, BERT, mBERT for the classification task in 9 languages and observed that with increasing training data, the classifier performance increased. Another key observation they made was that the relative performance seemed to vary depending on the language and the model. While better models for hate speech detection are continually being developed, little study has been done to understand the bias and interpretability aspect of hate speech. In \cite{mathew2020hatexplain}, the authors release a benchmark dataset which could be used to study this. In their work, they show that the models that perform very well in classification do not score high on explainability metrics. \subsubsection{Counter speech} After detection of hate speech, we need proper mitigation strategies to stop it from becoming viral. The current methods largely depend on blocking or suspending the users, deleting the tweets etc. This is performed mostly by moderators which is a tedious task for them given the information rate. Many companies like Facebook have started to automate this process but both these methods have the risk of violating free speech. This work~\cite{Katzenbach2020-KATACM-4} identifies various pitfalls with respect to trust, fairness and bias of these algorithms. A more promising direction could be to counter with speech which are popularly known as \textit{counter speech}. Specifically, counter speech is a direct non-hostile response/comment that \textit{counters} the hateful or harmful speech~\cite{richards2000counterspeech}. The idea that `more speech' is a remedy for dangerous speech has been familiar in liberal democratic thought at least since the U.S. Supreme Court Justice Louis Brandeis declared it in 1927. There are several initiatives with the aim of using counter speech to tackle hate speech. For example, UNESCO released a study~\cite{gagliardone2015countering} titled `Countering Online Hate Speech', to help countries deal with this problem. The frameworks for mitigating hate speech using counter speech involves two school of thoughts. One of them will be to develop fully automatic counter speech generation system, which can output contextually relevant counter speech given a hate speech. Since generating contextual replies to a text is still a nascent area in natural language processing, generating counter speech is expected to be further difficult for AI systems due to the variety of socio-political variables present in them. Hence, a more practical approach could be to find a task force of moderators who can suitably edit system generated counter speech for large scale use. One of the earliest computational studies attempted to identify hate and counter users on Twitter and further observe how they interact in online social media~\cite{mathew2020interaction}. The authors created a small dataset of hate-counter reply pairs and observed how different communities responded differently to the hate speech targeting them. The paper further tried to build a machine learning model to classify a user as hate or counter. A followup study~\cite{binnyCounter} on YouTube comments was conducted further to understand how different communities attempted to respond to hate speech. Taking the YouTube videos that contain hateful content toward three target communities: {\sl Jews}, {\sl African-American} (\textit{Blacks}) and {\sl LGBT}, the authors collected user comments to create a dataset which contained counter speech. The dataset is rich since it not only has the counter/non-counter binary classes but also a detailed fine-grained classification of the counter class as described in~\cite{wright-etal-2017-vectors} with a slight modification to the `Tone' Category. The authors observed that the LGBT community usually responded to hate speech via ``humour" whereas the Jew community used messages with a ``positive tone". The work further adds a classification model which can identify a text as counter speech and its type. The authors in~\cite{qian-etal-2019-benchmark} generated a large scale dataset having hate and their counter replies. They further used this dataset for counter speech generation using seq2seq models and variational autoencoders. One of the limitations of this paper was that the counter speech data annotated through crowd-sourcing were very generic in nature. Hence, a later work~\cite{chung-etal-2019-conan} took help from experts from and NGO to curate a dataset of counter speech toward Islamophobic statements from the social media. While this dataset provides diverse and to the point reply to hate speech, it largely depends on the experts availability. These challenges were compiled in~\cite{tekiroglu2020generating}, where the authors showed how data collection and counter speech generation is dependant on the assistance from the experts. The former paper also highlighted the weakness of the generation models with around 10\% of the automatic responses being proper response to the given hate speech. This reinstates the fact that current generation systems are not capable of understanding the hidden nuances required to generate proper counter speech. Another important question that lurks around in the research community is the ``effect of counter speech". While in the case of banning or suspension the effect, i.e., removal of tweet/user is visible, the effect of counter speech is rather subjective in nature. In a recent work~\cite{garland2020countering}, the authors used a classifier to identify ~100,000 hate-counter speech pairs and found reduction of hate speech due to the organised counter speech. While whether this solely was caused by the counter speech or some other reason is still an open question to the research community. Overall the counter speech research shows promise but has several unanswered questions about its data collection, execution and effect. Nevertheless, fighting hate speech in this way has some benefits: it is faster, more flexible and responsive, capable of dealing with extremism from anywhere and in any language and it does not form a barrier against the principle of free and open public space for debate. We hope gradually by using counter speech, it will be slowly possible to move toward an online world where differences could exist but not divisions. \textbf{Future directions: } Increased polarization seems to be spreading hate speech more. Most of the current models have been developed for English language. There is a need for larger and better hate speech datasets for other languages as well. Using transfer learning for improving the task is another direction. Zero or few shot learning would allow models to be able to build models for low resource languages. Finally, an orthogonal but very interesting direction is to understand the complexity of the annotation task itself. Due to the subjective nature of the task, the perception of hate speech is different for people belonging to different demographics. Another important direction is to integrate the detection and counter systems to build an end-to-end framework for effective hate speech detection and countering mechamism, as shown in figure~\ref{Fig: mitigation_framework}. \begin{figure}[h] \centering \includegraphics[width=4in]{figure/framework_hs.pdf} \caption{An overview of the hate speech framework.} \label{Fig: mitigation_framework} \end{figure} \subsection{Bias and fairness} As outlined in the introduction, in this section we shall talk about two types of important biases (out of many more that dwells in the online world) -- bias in news reporting and bias in online recommendation systems. \subsubsection{Media bias} \input{MediaBias/MediaBias.tex} \input{RIN.tex} \if{0}\section*{Figures and Tables} {\label{432859}} Figures and tables should be numbered separately, in the order in which they appear in the manuscript. Please embed them in the correct places in the text to facilitate peer review. Permission to \textbf{reuse or adapt} previously published materials must be submitted before article acceptance. \href{http://wires.wiley.com/go/forauthors\#Resources}{Resources} Production quality figure files with captions are still to be submitted separately. \href{https://authorservices.wiley.com/asset/photos/electronic_artwork_guidelines.pdf}{Figure preparation and formatting} \textbf{Captions should stand alone} and be informative outside of the context of the article. This will help educators who may want to use a PowerPoint slide of your figure. Explain any abbreviations or symbols that appear in the figure and make sure to include \textbf{credit lines} for any previously published materials.\fi \section{Conclusion} {\label{880788}} In this survey we have presented a critical rundown on the evolution of the \textit{online infosphere} by depicting some of the research areas that are becoming very crucial at current times. We started our discussion with a view of the infosphere as a collaborative platform, with a dedicated focus on Wikipedia. Wikipedia, the freely available and one of the largest knowledge base, containing a wide variety of information has been a primary focus of an extensive research so far. In this survey we have presented a detailed account of the works on article quality monitoring, editor behaviour and their retention and malicious activities like vandalism. In the next section we have detailed the growth of the citations and collaborations within and across various scientific disciplines that have their roots in the infosphere. In fact, this has resulted in the birth of many new interdisciplinary landscapes. We also discussed how machine learning algorithms can be used to predict future citations as well as for recommending citations. Finally we touched upon various issues related to anomalous citation flows and their behaviour. Finally, we summarised the research drives for patrolling the infosphere to suppress the rising volume of harmful content. The discussion started with analyzing the concept of hate speech and its growth over the past few years through the online social media platforms and the adverse impact, thereby, on both the online and the real world. We have shown the massive efforts the research community have put forward in detection and mitigation of such hateful behaviour. However, a lot of issues still remain as open problems and need immediate attention. We observed dense connectivity in the hateful users network by crawling Gab platform and analyzing their data and found that a significant amount of posts are generated by these hateful users in social media platforms. Additionally, we studied the temporal effect of hate speech on the users by using the Gab data and found the increasing rate of hateful users in the social network. After skimming through the recent literature we have pointed out that by incorporating knowledge based context information for a given post improves the overall performance of hatespeech detection rather than by analyzing only the textual information. Apart from that we have observed that by adding the user information of a given post can be further analyzed to improve the hatespeech detection task. The last segment of the discussion dealt with the bias and discrimination that are becoming pervasive across different online environments like recommendation and news media platforms. To conclude, the above mentioned research aspects related to the \emph{online infosphere} have attracted a lot of attention across the board including scientific communities, industry stakeholders and policy-makers. This paper discusses the technical challenges and possible solutions in a direction that utilizes the immense power of AI for solving real world problems but also considers the societal implications of these solutions. As a final note, we could see that the problems related to the anomalies in scientific collaborations and citations, hate speech detection and mitigation in social media and the bias and unfairness in news media and recommendation systems have a lot of open ends thus enabling exciting opportunities for future research. \if{0}Sum up the key conclusions of your review, highlighting the most promising scientific developments, directions for future research, applications, etc. The conclusion should be \textasciitilde{}2 paragraphs, \textasciitilde{}750 words total. \section*{Funding Information} {\label{974317}} You will be required to enter your funding information into the submission system so that we can apply proper IDs to your funders and help you comply with any funder mandates. \section*{Research Resources} {\label{808103}} List sources of non-monetary support such as supercomputing time at a recognized facility, special collections or specimens, or access to equipment or services. \href{https://orcid.org/organizations/research-orgs/resources}{Research Resources} can also be added to ORCiD profiles. For biomedical researchers, the \href{https://scicrunch.org/resources}{Resource Identification Portal} supports NIH's new guidelines for Rigor and Transparency in biomedical publications. \section*{Acknowledgments} {\label{749861}} List contributions from individuals who do not meet the criteria for authorship (for example, to recognize people who provided technical help, collation of data, writing assistance, acquisition of funding, or a department chairperson who provided general support), \textbf{with permission} from the individual. Thanks to anonymous reviewers are not appropriate. \section*{Notes} {\label{390481}} Authors writing from a humanities or social sciences perspective may use notes if a \textbf{comment or additional information} is needed to expand on a citation. (Notes only containing citations should be converted to references. Conversely, any references containing comments, such as ``For an excellent summary of\ldots{},'' should be converted to notes.) Notes should be indicated by \textbf{superscript letters}, both in the text and in the notes list. Citations within notes should be included in the reference section, as indicated below. \section*{Further Reading} {\label{153582}} For readers who may want more information on concepts in your article, provide full references and/or links to additional recommended resources (books, articles, websites, videos, datasets, etc.) that are not included in the reference section. Please do not include links to non-academic sites, such as Wikipedia, or to impermanent websites. \section*{\texorpdfstring{{Note About References}}{Note About References}} {\label{514168}} References are automatically generated by Authorea. Select~\textbf{cite~}to find and cite bibliographic resources. The bibliography will automatically be generated for you in APA format, the style used by most WIREs titles. If you are writing for~\emph{WIREs Computational Molecular Science}~ (WCMS), you will need to use the~Vancouver reference style, so before exporting click Export-\textgreater{} Options and select a Vancouver export style.~ \fi \selectlanguage{english} \FloatBarrier \bibliographystyle{acm}
{'timestamp': '2021-01-05T02:17:42', 'yymm': '2101', 'arxiv_id': '2101.00454', 'language': 'en', 'url': 'https://arxiv.org/abs/2101.00454'}
arxiv
\section{Introduction}\label{sec:introduction}} \IEEEPARstart{G}{raph} is a flexible data structure, which can store data and reflect the underlying topological relationship between data. Because of this, graph structure is widely used in various fields, including social networks \cite{1}, biological protein-protein networks \cite{2}, drug molecule graphs \cite{3}, knowledge network \cite{4}, etc. For example, in a drug molecule graph, a node can represent an atom, and nodes are connected with edges indicating that there are chemical bonds between atoms. By this way, people can easily store the data information in the network and access the relational knowledge about the interactive entities from this structured knowledge base at any time. The traditional methods of extracting information from graphs depend on the statistics (degree, clustering coefficient \cite{5}, centrality \cite{6,7}, etc.) of graphs, or kernel functions \cite{8} (or other characteristic functions) which are carefully designed. However, with the development of information technology, the amount of data increases rapidly, which makes the graph network more and more complex. Therefore, the traditional manual feature extraction methods becomes expensive, time-consuming and unreliable -- can not extract valid information from complicated organizations. In this case, representation learning has played a key role to efficiently extracts information in the graph. The graph representation learning method is a technical method for learning graph structure data, which hopes to transform complex original data into easy-to-process low-dimensional vector representations. In essence, the graph representation learning method is to learn a function, and this function maps the input graph or node to a point in the low-dimensional vector space. Compared with traditional methods, the representation learning method treats the problem of capturing graph information as part of the learning task itself, rather than just as a preprocessing link. In fact, the representation learning method uses data-driven methods to obtain features, avoiding the trouble of traditional manual feature extraction. The goal of representation learning is not simply to obtain results directly, but to obtain an efficient representation of the original data. In other words, the choice of representation usually depends on subsequent learning tasks, and a good representation should make the learning of downstream tasks easier. In recent years, representation learning on graphs is very popular, and many good results have been obtained. Belkin et al. \cite{9} propose Laplacian feature map in 2002, which is one of the earliest and most famous representation learning methods. Then a large number of methods are proposed, and the representative ones such as Grarep (Cao et al. \cite{10}), Deepwalk (Perozzi et al. \cite{11}), node2vec (Grover et al. \cite{12}), GNN (Scarselli et al. \cite{13}), GCN (Kipf et al. \cite{14}), etc. However, on the one hand, these methods are based on the binary relationship (i.e., edges) in the graph, and can not leverage the local structure of the graph; on the other hand, due to the sparseness of the edges in the graph, many methods are Encountered difficulties in generalization in many cases. Thus, our method is proposed in order to leverage the high-order connection patterns that are essential for understanding the control and regulation of the basic structure of complex network systems, and to alleviate the problem of edge sparsity in the graph. \vspace{2ex} \noindent\textbf{Present work.} This paper develops a new framework -- wGCN, a controllable and supervised representation learning method. wGCN can be regarded as a two-stage task: in the first stage, according to the original graph structure data, we execute a random walk algorithm on the graph, and then use the generated walk to redistribute the weight of the graph network to obtain the reconstructed graph; in the second stage, we connect the reconstructed image to the graph convolutional neural network, and combine the original features and labels for training. This new framework can improve the accuracy of prediction tasks while spending a little more time. We prove that it has the same level of time complexity as the graph convolutional neural network, and conduct a large number of experiments on a variety of actual datasets, all of which have obtained better test results than the baselines. The rest of this article is organized as follows. In Section 2, the related work in the past is summarized, and in Section 3, our representation learning method wGCN is introduced in detail. Our experiment will be introduced in Section 4, and the results will be given in Section 5. In Section 6, conclusions and future work will be discussed. \section{Related Work} This part will focus on previous work closely related to wGCN. Specifically, we first introduce random walk, and then introduce some classic graph representation learning methods, which inspires our methods. \subsection{Random Walk} Random walk refers to the behavior that can not predict future development steps and directions based on past performance. The core concept is that the conserved quantities of any irregular walker correspond to a law of diffusion and transportation, which is the ideal mathematical state of Brownian motion. \begin{figure} \center \includegraphics[width=\linewidth]{fig1.png} \caption{The image on the left is the original graph, and the image on the right shows a random walk of length 8 (8 nodes, marked in red). The red arrow shows the walking order, and this random walk is recorded as $v_{i_1}v_{i_2}...v_{i_8}.$} \label{fig:1} \end{figure} The random walk on the graph refers to starting from one or a series of nodes and moving between nodes in the graph according to specific rules. For example, a walker randomly selects a vertex to start, walks to the neighbor node of this vertex with probability $p \ (0<p\leq1)$, and jumps to any node in the graph with probability $1-p$, which is called a jump-turn probability. Each walk will result in a probability distribution reflecting the node to be visited, which is used as the input of the next step of the random walk. And the above process is iterated continuously. When certain conditions are met, the results of the iteration will tend to converge, resulting in a stable probability distribution. Fig.1 gives a specific random walk on graph. Random walk is widely used in the field of information retrieval. The well-known PageRank \cite{15} algorithm is a classic application of random walk. \subsection{Representation Learning Method} The graph representation learning method is a technical method for learning graph structure data. It hopes to transform complex raw data into a low-dimensional representation that is convenient to develop and process by machine learning. To a certain extent, it can also be regarded as a method of dimensionality reduction. According to whether neural network is used, graph representation learning methods can be divided into two categories: i) direct coding methods that do not use neural networks; ii) neural network-based coding methods. \vspace{2ex} \noindent\textbf{Direct coding methods.} Early learning node representation methods are concentrated in the matrix factorization framework. Belkin et al. present Laplacian eigenmaps method, which is a encoder-decoder framework measured by Euclidean distance in the coding space \cite{9}. Following the Laplacian eigenmaps method, Ahmed et al. \cite{16} and Cao et al. \cite{10} propose Graph Factorization (GF) and GraRep separately, whose main difference is the way the basic matrix is used. The original adjacency matrix of graph is used in GF and GraRep is based on various powers high order relationship of the adjacency matrix. And Mingdong er al. present High Order Proximity preserved Embedding (HOPE), which can preserve the asymmetric transitivity of the directed graph \cite{17}. \begin{figure} \subfigure[]{ \begin{minipage}[t]{0.2\linewidth} \centering \includegraphics[width=1.2in]{fig2_a.png} \end{minipage} }% \subfigure[]{ \begin{minipage}[t]{0.85\linewidth} \centering \includegraphics[width=2.2in]{fig2_b.png} \end{minipage} }% \caption{\textbf{Explanation of node2vec.} In subfigure (a), node $s$ is the source node of a random walk, and node $c$ is the current node. Hyperparameters $p$ and $q$ control the walking probability of the next step (from node $c$ to its neighbors). As marked in subfigure (a), the probability of returning node $s$ from node $c$ is $1/p$; the probability from node $c$ to node $v_1$ or $v_4$ is $1$ as $v_1$ and $v_4$ are also neighbors of node $s$; and the probability from node $c$ to node $v_2$ or $v_3$ is $1/q$ as $v_2$ and $v_3$ are the second-order neighbors of node $c$. Thus, when $p$ decreases, walking tends to return to the source node (i.e., "more local"); when $q$ decreases, walking tends to move away from the source node (i.e., "more global"). The consequence is shown in subfigure (b), red arrows show the walking which is "more local", and blue arrows show the walking which is "more global".} \label{fig:2} \end{figure} On the other hand, there are also some classic methods based on random walk instead of matrix factorization, thus becoming more flexible. Here, two representative methods are DeepWalk \cite{11} and node2vec \cite{12}. DeepWalk uses random walk to disassemble the graph which is nonlinear structure into multiple linear node sequences, then the node sequences treated as "sentences" (the nodes are treated as "words") are processed by SkipGram \cite{18}. As for node2vec, it allows an adjustable random walk on the graph. In particular, node2vec creatively uses two hyperparameters $p$ and $q$ to control the random walk "more local" or "more global", in other words, depth-first search or breadth-first search (relative to the starting node, see Fig.2). \vspace{2ex} \noindent\textbf{Neural network-based coding methods.} The above direct encoding methods independently generate a representation vector for each node, which results in no shared parameters between nodes, high computational complexity, and underutilized node attribute information. Considering to solve these problems, many graph neural network methods have been proposed in recent years. Scarselli et al. \cite{13} present the Graph Neural Network (GNN) model which can implement a function that maps the graph and one of its nodes to Euclidean space. And Inspired by the success of Convolutional Neural Network in image processing (Convolutional Neural Network extremely reduces the number of parameters by using convolution kernels to gather the information of local pixels on the image. However, CNN has encountered difficulties on the graph, due to the irregularity of the graph, that is, the number of neighbors is uncertain), Kipf et al. \cite{14} propose the well-known Graph Convolutional Network (GCN) method. The GCN method cleverly applies the convolution operation to the graph structure, which means that the information of neighbor nodes is aggregated on the irregular graph structure. \vspace{4ex} \section{Method} We first perform random walk operation on the original graph, and then use the obtained "walks" to reconstruct the graph network. After that, the graph convolution operation is performed on the obtained reconstructed graph to obtain the representation vectors of the nodes. We believe that these approaches can combine the nodes of the graph at multiple levels to obtain a more informative representation. Finally, the obtained representation vectors are sent to the downstream classifier (such as knn, mlp and so on) to complete the node classification task. Next, we will introduce the technical details of our method. First, the random walk and the reconstructed graph is introduced in detail in Section 3.1; then, the wGCN embedding algorithm to generate embeddings for nodes is described in Section 3.2; finally in Section 3.3, we give an analysis of the complexity of the algorithm and prove it at the same time. \subsection{Reconstructed Graph} We will explain reconstructed graph utilizing random walks in detail in this section. For the convenience of explanation, some commonly used symbols are given below: Formally, let graph $G=(V,E)$, where $V$ is the set of the nodes in network, $|V|$ represents the number of nodes, and $E \subseteq (V \times V)$ is the set of the edges. Given a labeled network with node feature information $G=(V,E,X,Y)$, where $X \in R^{(N \times T)}$ ($N$ is the number of the nodes in network, $T$ is the feature dimension) is the feature information matrix and $Y \in R^{(N \times L)}$ ($L$ is the feature dimension) is the label information matrix, our goal is to use the labels of some of the nodes for training, and generate a vector representation matrix $Z$ of the nodes. Then, we give: \noindent\textbf{Definition 1:} Given a graph $G=(V,E,X,Y)$ ($V=\{v_1, v_2, ..., v_{|V|}\}$) and initial node $v_{i_1}$, a random walk of length $n$ rooted at $v_{i_1}$ is denoted as $W_{v_{i_1}}=\{(v_{i_1},v_{i_2}),(v_{i_2},v_{i_3}),...,{(v_{i_{n-1}},v_{i_n})}\}$, where $1 \le i_1,i_2,...,i_n \le |V|$ and the two nodes in the same parenthesis are neighbors (i.e., there is an edge connection between $v_{i_j}$ and $v_{i_{j+1}}$). Or for convenience, $W_{v_{i_1}}=\{v_{i_1}v_{i_2}v_{i_3}...v_{i_{n-1}}v_{i_n}\}$. \begin{figure*} \begin{center} \includegraphics[width=0.9\linewidth]{fig3.png} \end{center} \caption{\textbf{Example of reconstructing graph using random walk.} Subfigure (a) is the original graph, in which the node $c$ is the source node marked in red. And the "walks" are marked with red lines and extracted in subfigure (b). Subfigure (c) is the reconstructed graph, where the weights $\alpha^k,k=1,2,3$ is used to weight the original k-hop nodes away from node $c$.} \label{fig:1} \end{figure*} As shown in the Fig.3, we first perform random walk operation on the graph (subfigure (a)) to obtain "walks" (subfigure (b)). After that, we can use the obtained "walks" to reconstruct the graph network. A node that appears in the same walk with node $c$ is considered to be related to node $c$, and this node is connected to node $c$ in the reconstructed graph (the red lines in subfigure (c)). And we assign different weights to distinguish the distance between the nodes and node $c$ in "walks". Thus in the reconstructed graph, the weight $w_{ij}$ for nodes $i,j$ can be given by the following formula: \begin{equation} w_{ij}=a_{ij}+\sum_{k \in \{the ~ spacing ~ of ~ i,j ~ in ~ "walks"\}}\alpha^k, \end{equation} \noindent where $a_{ij}$ indicates the original adjacency matrix, which is defined as follows: \begin{equation} a_{ij}=\begin{cases} 0,& \text{if nodes $i,j$ are not connected in the original graph}\\ 1,& \text{if nodes $i,j$ are connected in the original graph} \end{cases}, \end{equation} \noindent and $\alpha$ is a parameter to be determined indicating the decay speed with distance, satisfying $0<\alpha<1$. And k is the exponent, whose values are the distance between nodes $i,j$ in the "walks". For example, node $c$ and node $v_{{}_{12}}$ are not connected in the original graph (subfigure (a)), thus $a_{cv_{{}_{12}}}=0$; and node $c$ and node $v_{{}_{12}}$ have a distance of $2$ in "walks" (subfigure (b)), thus $k=2$; in summary: \begin{eqnarray} w_{cv_{{}_{12}}}&=&a_{cv_{{}_{12}}}+\sum_{k \in \{2\}}\alpha^k \nonumber \\ &=&0+\alpha^2 \\ &=&\alpha^2 \nonumber. \end{eqnarray} \noindent In the next section, we give the complete algorithm. \subsection{Embedding Algorithm} \begin{algorithm} \caption{\textbf{:} wGCN embedding algorithm.} \label{alg:Framwork} \begin{algorithmic}[1] \Require Graph $(V,E)$; Adjacency matrix $A$; The number of walks from each node $T$; Walks length $L$; Reconstructed scale parameter $\lambda$; Node feature matrix $X$; The number of graph convolutional neural network layers $H$; \Ensure Representation matrix $Z$; \State Initialize the random walk matrix $\mathcal{A}$ as zero; \For{$t=1...T$} \For{$v \in V$} \State $W_{v}^t=RandomWalk(G,v,L)$ \EndFor \EndFor \For{$t=1...T$} \For{$v \in V$} \For{$l=2...L$} \State $\alpha_{vW_{v}^t[l]}=\alpha_{vW_{v}^t[l]}+\alpha^{l-1}$; \EndFor \EndFor \EndFor \State $\tilde{A}=A+ \lambda \cdot \mathcal{A}$ \State $h_v^{0}=x_v, \forall v \in V$; \For{$k=1...H$} \For{$v \in V$} \State $h_v^{k} \leftarrow f(h_v^{k-1},h_u^{k-1}),u \in N_{\tilde{A}}(v)$; \EndFor \EndFor \State $z_v=h_v^{H}, \forall v \in V$; \State \textbf{return} $Z$ (whose column vectors are $z_v, v \in V$); \end{algorithmic} \end{algorithm} After entering the required data, we first initialize the random walk matrix $\mathcal{A}$ to a zero matrix in line 1. The random walk matrix $\mathcal{A}$ refers to the matrix generated by random walk, whose element $\alpha_{uv}$ indicates the weight attached to the nodes $u,v$ by the "walks". And in lines 2-14, the reconstructed graph matrix is built as described in section 3.1: \noindent 1. Generate $T$ "walks" of length $L$ at each node ($RandomWalk(\cdot)$) in lines 2-5; \noindent 2. Update the elements of the random walk matrix $\mathcal{A}$ in lines 7-13; \noindent 3. Obtain the reconstructed graph matrix $\tilde{A}$ in line 14. Note that the "walk" returned by $RandomWalk(\cdot)$ is a node list. For example, $W_{v_{1}}^1=RandomWalk(G,v_{1},L)=[v_{1}v_{2}...v_{L}]$, in which $v_{i+1}$ is the neighbor of $v_{i}$, $1 \leq i \leq L-1$, and $W_{v_{1}}^1[2]=v_{2}$. In addition, the adjacency matrix $A$ and the random walk matrix $\mathcal{A}$ are mixed and normalized to obtain the reconstructed graph matrix $\tilde{A}$ in line 14, where $\lambda$ is the mixing ratio coefficient. And $Normalized(\cdot)$ is a symmetric normalization function: \begin{equation} Normalized(X)=D^{-\frac{1}{2}}(I+X)D^{-\frac{1}{2}}, \end{equation} \noindent where $X$ is a square matrix, $I$ is the identity matrix and $D$ is a diagonal matrix, satisfying $D_{ii}=\sum_{j}X_{ij}$. Then the graph convolution operation is performed. The number of graph convolutional neural network layers is specified by users in advance. And the initial representation of all nodes is expressed as: $h_v^{0}=x_v, \forall v \in V$, in line 15; In lines 16-20, we perform a graph convolution operation based on reconstructed graph, in the formula $h_v^{k} \leftarrow f(h_v^{k-1},h_u^{k-1}),u \in N_{\tilde{A}}(v)$, $f(\cdot)$ represents a weighted nonlinear aggregation function, whose purpose is to reorganize the information of the target node and its neighbors. Formally, \begin{equation} h_v^{k}=\sigma(\sum_{u \in N_M(v) \cup \{v\}}\tilde{a_{vu}} \cdot h_u^{k-1} \cdot W_k), \end{equation} \noindent where $h_v^{k}$ is the hidden representation of node $v$ in the $k$-th layer; $\tilde{a_{vu}}$ is the number on the $v$-row and $u$-column of the reconstructed graph matrix $\tilde{A}$, indicating the closeness between nodes of $v$ and $u$; $W_k$ is the parameter matrix to be trained of layer $k$; $N_{\tilde{A}}(v)$ is the neighborhood nodes set of node $v$ in the reconstructed graph; $\sigma( \cdot )$ represents for ReLU function: \begin{equation} f(x)=\text{max}(0,x). \end{equation} Then, the final representation vector $z_v$ of node $v$ is obtained. And the representation vectors can be sent to the downstream classifier (such as softmax classifier) to obtain the predicted category vectors $\hat{y_{v}},v \in V$. If softmax classifier is chosen (the form is as follows), \begin{equation} \text{Softmax}(z)_{i}=\frac{\text{exp}(z_{i})}{\sum_{j=1}^d\text{exp}(z_{j})},~~~ i=1...d, \end{equation} \noindent where $z$ is the representation vector, Softmax$(z)_{i}$ is the $i$-th component of the vector Softmax$(z)$, and $d$ is the dimension of the representation vector $z$, then the cross entropy function can be used as the loss function to train the parameters of our model: \begin{equation} loss = \sum_v(y_v \cdot log (\hat{y_{v}}) + (1-y_v) \cdot log (1-\hat{y_{v}})),~~~v \in trainset, \end{equation} \noindent where $y_v$ is the true label of the node $v$. \subsection{Complexity Analysis} Our method is based on GCN. And from the related work of Kipf et al. \cite{14}, we know that the computational complexity of the original GCN based on the following formula is $\mathcal{O}(|\mathcal{E}|CHF)$, where $\mathcal{E}$ is the edge set of the graph: \begin{equation} Z = f(X,A) = softmax \left( \hat{A} ~ {\rm ReLU}\left(\hat{A}XW^{(0)}\right) W^{(1)}\right), \end{equation} where $A$ is the adjacency matrix and $X$ is the feature matrix. And $\hat{A}$ is the normalized processing matrix of the adjacency matrix $A$. $W^{(0)} \in \mathbb{R}^{C \times H}$ is an input-to-hidden weight matrix and $W^{(1)} \in \mathbb{R}^{H \times F}$ is a hidden-to-output weight matrix, where $C$ is input channels, $H$ is the number of feature maps in the hidden layer and $F$ is the number of feature maps in the output layer \cite{14}. The time of our algorithm is mainly consumed in the training phase of the neural network. Thus, we will prove that the calculation complexity of our method in the training phase of the neural network is also $\mathcal{O}(|\mathcal{E}|CHF)$, while keeping the number of hidden layers unchanged. \begin{proof} Let $L$ be the "walks" length in random walk, $T$ denotes the number of "walks" from each node, and $A, \mathcal{A}, \tilde{A}$ denotes the original adjacency matrix, reconstructed graph matrix and random walk matrix respectively. We compare the number of non-zero elements in $A$ and $\tilde{A}$. Since each node has $T$ "walks" of length $L$, then the maximum number of non-zero elements per node in the random walk matrix $\mathcal{A}$ is $T(L-1)$ (in this case, the "walks" guided by the starting node have no duplicate nodes except the starting node itself). So $\tilde{A}$ has at most $|V|T(L-1)$ non-zero elements more than $A$ ($|V|$ is the number of nodes). And in experiments, $L$ is set to 5 and $T$ is generally set to $2|\mathcal{E}|/|V|$ ($2|\mathcal{E}|/|V|$ is the average degree of the graph), thus $T(L-1) \ll \mathcal{E}$. Therefore, the computational complexity satisfies: \begin{eqnarray} &&\mathcal{O}((|\mathcal{E}|+|V|T(L-1))CHF) \nonumber \\ &=&\mathcal{O}((|\mathcal{E}|+2|V|(|\mathcal{E}|/|V|)(5-1)CHF) \nonumber \\ &=&\mathcal{O}(9|\mathcal{E}|CHF) \\ &=&\mathcal{O}(|\mathcal{E}|CHF) \nonumber. \end{eqnarray} \end{proof} \section{Experiments and Result} In section 4.1, we introduce the datasets used in the experiment, and the specific settings of the experiment are described in section 4.2. In section 4.3, a wide variety of baselines and previous approaches are introduced, and the results are shown in section 4.4. \subsection{Datasets} \begin{table*} \renewcommand{\tablename} \caption{\centering{\textbf{Table 1: Summary of the datasets.}}} \vspace{2ex} \renewcommand{\arraystretch}{1.4} \setlength\tabcolsep{15pt} \centering \label{tab:1} \begin{tabular}{l l c c c c c} \toprule Datasets & Types & Undirected & Nodes & Edges & Features & Classes \\ \midrule Cora & Citation & yes & 2708 & 5429 & 1433 & 7 \\ Citeseer & Citation & yes & 3327 & 4732 & 3703 & 6 \\ Pubmed & Citation & yes & 19717 & 44338 & 500 & 3 \\ 107Ego(F) & Social & yes & 1045 & 53498 & 576 & 9 \\ 414Ego(F) & Social & yes & 159 & 3386 & 105 & 7 \\ 1684Ego(F) & Social & yes & 792 & 28048 & 319 & 16 \\ 1912Ego(F) & Social & yes & 755 & 60050 & 480 & 46 \\ 2106Ego(G) & Social & no & 2457 & 174309 & 2094 & 2 \\ 3600Ego(G) & Social & no & 2356 & 582827 & 995 & 3 \\ 5249Ego(G) & Social & no & 826 & 435569 & 2627 & 2 \\ 7461Ego(G) & Social & no & 997 & 1270141 & 2882 & 2 \\ \bottomrule \end{tabular} \end{table*} \noindent\textbf{Citation Network Datasets: Citeseer, Cora, and Pubmed.} In these three standard citation network datasets, nodes represent documents and edges (undirected) represent citation links. The three citation network datasets contain a sparse feature vector for each document and each document has a category label \cite{14}. As shown in the Table 1, the Cora, Citeseer and Pubmed datasets contain 1433 features, 3703 features and 500 features per node respectively, and the number of label categories are 7, 6 and 3 respectively. \noindent\textbf{Social Network Datasets: Ego-Facebook and Ego-Gplus.} For Ego-Facebook, this dataset consists of 'circles' (or 'friends lists') from Facebook \cite{19}. There are many subsets of the Ego-Facebook dataset. Take '107Ego(F)' as an example. This dataset is a network with the node '107' as the core, where the nodes represent users and the edges (undirected) represent interactions between users. And each user has a feature attribute vector and a category label. As for Ego-Gplus, it is similar to Ego-Facebook, except that the data comes from Google$+$ and the edges are directed \cite{19}. We choose the suitable subsets of Ego-Facebook and Ego-Gplus for experiments (to facilitate the distinction, (F) represents a subset of Ego-Facebook and (G) represents a subset of Ego-Gplus). And after preprocessing, the data whose information has been lost is removed. \subsection{Experimental Setup} \begin{table*} \renewcommand{\tablename} \caption{\centering{\textbf{Table 2: Parameter setting on social network datasets.}}} \vspace{2ex} \renewcommand{\arraystretch}{1.4} \setlength\tabcolsep{18pt} \centering \begin{tabular}{l c c c c c c} \toprule Datasets & $W_1$ & $W_2$ & $W_3$ & $T$ & $\alpha$ & $\lambda$ \\ \midrule 107Ego(F) & $\mathbb{R}^{576\times128}$ & $\mathbb{R}^{128\times32}$ & $\mathbb{R}^{32\times9}$ & 40 & 0.8 & 0.8 \\ 414Ego(F) & $\mathbb{R}^{105\times36}$ & $\mathbb{R}^{36\times12}$ & $\mathbb{R}^{12\times4}$ & 24 & 0.8 & 0.7 \\ 1684Ego(F) & $\mathbb{R}^{319\times128}$ & $\mathbb{R}^{128\times40}$ & $\mathbb{R}^{40\times13}$ & 35 & 0.5 & 0.9 \\ 1912Ego(F) & $\mathbb{R}^{480\times160}$ & $\mathbb{R}^{160\times60}$ & $\mathbb{R}^{60\times19}$ & 80 & 0.8 & 0.9 \\ 2106Ego(G) & $\mathbb{R}^{2094\times128}$ & $\mathbb{R}^{128\times16}$ & $\mathbb{R}^{16\times2}$ & 30 & 0.8 & 0.8 \\ 3600Ego(G) & $\mathbb{R}^{995\times128}$ & $\mathbb{R}^{128\times16}$ & $\mathbb{R}^{16\times3}$ & 200 & 0.5 & 0.9 \\ 5249Ego(G) & $\mathbb{R}^{2627\times256}$ & $\mathbb{R}^{256\times16}$ & $\mathbb{R}^{16\times2}$ & 50 & 0.8 & 0.9 \\ 7461Ego(G) & $\mathbb{R}^{2882\times256}$ & $\mathbb{R}^{256\times16}$ & $\mathbb{R}^{16\times2}$ & 30 & 0.8 & 0.7 \\ \bottomrule \end{tabular} \end{table*} \noindent\textbf{Citation Network Datasets.} On citation network datasets, we apply a two-layer wGCN model. Specifically, we perform random walk operation 8 times for each node, and stop after passing 4 different nodes every time on Cora dataset. And the decay rate (i.e., $\alpha$, mentioned in section 3.1) is set to 0.8 and the mixing ratio coefficient (i.e., $\lambda$, mentioned in section 3.2) is set to 0.9; on Citation dataset, the random walk operation is performed 3 times for each node, and stop after passing 4 different nodes every time. The decay rate is set to 0.8 and the mixing ratio coefficient is set to 0.73; on Pubmed dataset, the random walk operation is performed 5 times for each node, and also stop after passing 4 different nodes every time. The decay rate and the mixing ratio coefficient ars set to 0.8 and 0.9, respectively. The remaining parameter settings follow the settings in \cite{14}. \noindent\textbf{Social Network Datasets.} On social network datasets, we apply a three-layer wGCN model. Specifically, the shape of the parameter matrix ($W_1,W_2,W_3$) of the three-layer model, the number $T$ of random walk operation from each node, the decay rate $\alpha$ and the mixing ratio coefficient $\lambda$ on 8 subdatasets are shown in Table 2. In addition, the learning rates on subdatasets of Ego-Facebook and Ego-Gplus are set to 0.02 and 0.01 respectively. And the random walk operation for each node is also stopped after passing 4 different nodes every time. \vspace{1.5ex} \subsection{Baselines and Previous Approaches} \noindent\textbf{Citation Network Datasets.} On citation network datasets (Citeseer, Cora, and Pubmed), our method is compared with the same strong baselines and previous approaches as specified in \cite{14}, including label propagation (LP) \cite{20}, semi-supervised embedding (SemiEmb) \cite{21}, manifold regularization (ManiReg) \cite{22}, iterative classification algorithm (ICA) \cite{23} and Planetoid \cite{24}. Here, DeepWalk is a method based on random walks, as stated at the beginning of the article, whose sampling strategy can be seen as a special case of node2vec with $p=1$ and $q=1$. As for method named GCN, which is the first method to achieve convolution on the graph, it is the best performing baseline method. \noindent\textbf{Social Network Datasets.} On social network datasets (Ego-Facebook and Ego-Gplus), our method is compared against Deepwalk, GraRep and again GCN, which is the strongest baseline in the above experiment. And here, GraRep \cite{10} works by utilizing the adjacency matrix of each order and defining a more accurate loss function that allows non-linear combinations of different local relationship information to be integrated. \subsection{Results} The results of our comparative evaluation experiments are summarized in Tables 3 and 4. \begin{table}[h] \renewcommand{\tablename} \caption{\centering{\textbf{Table 3: The results of classification accuracy on citation network datasets.}}} \vspace{2ex} \renewcommand{\arraystretch}{1.2} \setlength\tabcolsep{16pt} \centering \begin{tabular}{c c c c} \toprule \textbf{Method} & \textbf{Cora} & \textbf{Citeseer} & \textbf{Pubmed} \\ \midrule ManiReg & 59.5 & 60.1 & 70.7 \\ SemiEmb & 59.0 & 60.1 & 71.1 \\ LP & 68.0 & 45.3 & 63.0 \\ DeepWalk & 67.2 & 43.2 & 65.3 \\ ICA & 75.1& 69.1 & 73.9 \\ Planetoid & 75.7 & 64.7 & 77.2 \\ GCN & 81.5 & 70.3 & 79.0 \\ \midrule wGCN & \textbf{81.8} & \textbf{72.4} & \textbf{79.5} \\ \bottomrule \end{tabular} \end{table} As shown in Table 2, our method achieves the best results on all datasets, and compared with the strongest baseline, our method improve upon GCN by a margin of 0.3, 2.1 and 0.5 on Cora, Citeseer and Pubmed respectively. Next, we use the social network datasets (Ego-Facebook and Ego-Gplus) for the experiments, and compare the experimental results with the classic method based on adjacency matrix $--$ GraRep [] and based on random walk $--$ Deepwalk [], and the best performing baseline method $--$ GCN []. The experimental results are shown in the Table 3: \begin{table}[h] \renewcommand{\tablename} \caption{\centering{\textbf{Table 4: The results of classification accuracy on social network datasets.}}} \vspace{2ex} \renewcommand{\arraystretch}{1.2} \setlength\tabcolsep{6pt} \centering \begin{tabular}{c c c c c} \toprule \textbf{Method} & \textbf{107Ego(F)} & \textbf{414Ego(F)} & \textbf{1684Ego(F)} & \textbf{1912Ego(F)} \\ \midrule DeepWalk & 77.5 & 79.2 & 64.4 & 66.5 \\ GraRep & 90.0 & 85.4 & 76.3 & 77.0 \\ GCN & 92.5 & 93.8 & 81.9 & 77.0 \\ \midrule wGCN & \textbf{95.0} & \textbf{97.9} & \textbf{85.0} & \textbf{81.0} \\ \bottomrule \end{tabular} \vspace{4ex} \setlength\tabcolsep{5pt} \begin{tabular}{c c c c c} \toprule \textbf{Method} & \textbf{2106Ego(G)} & \textbf{3600Ego(G)} & \textbf{5249Ego(G)} & \textbf{7461Ego(G)} \\ \midrule DeepWalk & 75.8 & 47.5 & 76.2 & 65.6 \\ GraRep & 87.9 & 62.3 & 98.9 & 77.4 \\ GCN & 92.3 & 95.7 & \textbf{99.5} & 80.2 \\ \midrule wGCN & \textbf{93.4} & \textbf{98.1} & \textbf{99.5} & \textbf{83.1} \\ \bottomrule \end{tabular} \end{table} As can be seen from Table 3, the experimental results of both parts of our method are significantly higher than the results of Deepwalk and GraRep. And except for '5249Ego(G)' (the result is as good as the result of GCN), the other results of our method are also better than the results of GCN. \section{Conclusion} In this paper, we have designed a new framework combined with random walk $--$ wGCN, which can reconstruct the graph to capture higher-order features through random walk, and can effectively aggregate node information. We conduct experiments on a series of datasets (citation network and social network, directed and undirected). The results have shown that wGCN can effectively generate embeddings for nodes of unknown category and get the better results than the baseline methods. There are many extensions and potential improvements to our method, such as exploring more random walk methods with different strategies and extending wGCN to handle multi-graph mode or time-series-graph mode. Another interesting direction for future work is to extend the method to be able to handle edge features, which will allow the model to have wider applications. \ifCLASSOPTIONcompsoc \section*{Acknowledgments} \else \section*{Acknowledgment} \fi This work is supported by the Research and Development Program of China (No.2018AAA0101100), the Fundamental Research Funds for the Central Universities, the International Cooperation Project No.2010DFR00700, Fundamental Research of Civil Aircraft No. MJ-F-2012-04, the Beijing Natural Science Foundation (1192012, Z180005) and National Natural Science Foundation of China (No.62050132). \ifCLASSOPTIONcaptionsoff \newpage \fi \bibliographystyle{IEEEtran}
{'timestamp': '2021-01-05T02:15:13', 'yymm': '2101', 'arxiv_id': '2101.00417', 'language': 'en', 'url': 'https://arxiv.org/abs/2101.00417'}
arxiv
\section*{Acknowledgements} This work was done during the first author's internship at NVIDIA. It was also partially supported by Canada CIFAR AI Chair held by Prof.\ Hamilton. We would like to thank the anonymous reviewers for providing valuable feedback and recommendations. We would also like to thank the administrators of the \href{https://www.top500.org/system/179842/}{Selene} supercomputer for their assistance in facilitating the large-scale runs. \section{Training Details} \label{sec:training_details} We provide the training details of all the experiments below. We use the same training settings for both the base and large model configurations and use the open-source Megatron-LM toolkit~\cite{shoeybi2019megatron} to implement the models.\footnote{\url{https://github.com/NVIDIA/Megatron-LM}} To train the models, we employed mixed-precision training~\cite{micikevicius2018mixed} and leveraged distributed training feature as implemented in the Pytorch framework~\cite{shen2020pytorch}. All of our experiments were performed on the \href{https://blogs.nvidia.com/blog/2020/06/22/top500-isc-supercomputing/}{Selene} cluster which consists of NVIDIA A100 GPUs. \subsection{Language Models Training} We train BERT~\cite{devlin2019bert,Lan2020ALBERT} and T5~\cite{raffel2020t5} language models from scratch, whose hyperparameters for both the base and large configurations are detailed in Table~\ref{table:bert-t5}. We used 32 GPUs to train the BERT-large (330M) model and 128 GPUs to train the T5-large (770M) model. \begin{table*}[t] \small \centering \begin{tabular}{l c c} \toprule \textbf{Hyperparameter} & \textbf{BERT} & \textbf{T5} \\ \midrule Dataset & Wikipedia, BookCorpus & Wikipedia, CC-Stories, RealNews, OpenWebText \\ Hidden Size & \{768, 1024\} & \{768, 1024\} \\ Attention Heads & \{12, 16\} & \{12, 16\} \\ Dropout & 0.1 & 0.1 \\ Attention Dropout & 0.1 & 0.1 \\ Optimizer & Adam & Adam \\ Training Steps & 1M & 1M \\ Warmup Steps & 10k & 10k \\ Peak Learning Rate & 1e-4 & 1e-4 \\ Weight Decay & 1e-2 & 1e-2 \\ Batch Size & 256 & 2048 \\ Learning Rate Decay & Linear & Linear \\ Gradient Clipping & 1.0 & 1.0 \\ \bottomrule \end{tabular} \caption{Hyperparameters for pre-training BERT and T5 models.} \label{table:bert-t5} \end{table*} \subsection{Retriever Training} \paragraph{Supervised:} We use Adam optimizer~\cite{kingma2014adam}, a batch size of $128$, learning rate of 2e-5 with a linear decay, and train for $80$ epochs. Training was performed on 16 GPUs. \paragraph{ICT training:} We initialize the parameters of both the question and context encoders using BERT weights trained with Megatron-LM. We train the model on Wikipedia paragraphs with maximum length of 256 tokens. We use a batch size of $4,096$, learning rate of 1e-4 with linear decay, and train the model for $100,000$ steps using Adam optimizer. This corresponds to training the model for roughly $20$ epochs over the Wikipedia dataset. We set the weight decay to $0.01$ and the warmup ratio of the optimizer to $0.01$. With a probability of $0.1$, we also keep the query sentence in the context. We train the large ICT model using 128 GPUs. \paragraph{Masked salient spans generative training:} We initialize the retriever with ICT training and pre-train the T5 reader on an aggregated dataset from~\cite{shoeybi2019megatron}. We use the pre-trained models provided by the Stanza toolkit~\cite{qi2020stanza} to segment Wikipedia paragraphs into sentences and extract named entities.\footnote{We use the model trained on OntoNotes~\cite{pradhan2012conll} to extract named entities for $10$ selected categories.} The masked sentence is used as a query to retrieve evidence documents with the help of which the reader predicts the masked words. The model is trained according to Equation~\ref{eq:indiv-topk} and~\ref{eq:loss}. We train the model for $100,000$ steps with Adam optimizer using a learning rate of 2e-5 and a warmup ratio of $0.05$. Similar to~\cite{guu2020realm}, we also compute the evidence embeddings asynchronously and update the evidence index every $500$ steps. Training was performed on 240 GPUs. \subsection{End-to-End Supervised Training} As the performance of the ICT pre-trained retriever and masked salient spans pre-trained retriever is similar when all the training data is used (Sec.~\ref{subsec:ret-init}), we select the retriever pre-trained with ICT initialization and finetuned with supervised data. For the reader, we use a pre-trained T5 model. For all experiments, we train for $10$ epochs using a batch size of $64$, learning rate of 2e-5 with linear decay, and weight regularization of $0.1$. For \emph{Individual Top-k} approach, during training, the evidence embeddings index is refreshed after every $500$ steps. The number of retrieved evidence documents for the reader is considered as a hyperparameter and is selected via performance on the dev set. Training of Individual Top-k was performed on 240 GPUs while training of Joint Top-k was performed on 64 GPUs. For retrieving the top-k documents from our evidence ($\sim$21M documents), we perform exact search. Specifically, we utilize matrix multiplication and top-k functionalities as provided by the PyTorch framework. This matrix multiplication operation is highly optimized for GPU computations and we observed that performing exact search was not a bottleneck during training. We therefore did not optimize or approximate the similarity search using LSH~\cite{andoni2015lsh} or efficient maximum inner product search~\cite{srivastava2014lsh}. \paragraph{NQ and TriviaQA Specific Details:} For both datasets, we uniformly sample the target answer from the list of provided answers during the training process. For answer extraction, similar to ~\cite{guu2020realm}, we did not append the title of the Wikipedia article with the corresponding top-k retrieved document as the reader's input. \subsection{Individual Top-k Inference} During inference, the reader model first greedily generates an answer for each retrieved document. We then score each generated answer using Eq.~\ref{eq:indiv-topk} and finally select the answer with the highest likelihood score. \subsection{Example Outputs from Retriever} We present few examples in Table~\ref{table:examples} when the ICT + Supervised retriever is evaluated on the NQ test dataset. \begin{table*}[t] \begin{minipage}{\linewidth} \small \centering \begin{tabularx}{\linewidth}{@{} X l X @{}} \toprule \textbf{Question from NQ test} & \textbf{Answer} & \textbf{Top-1 Document Retrieved by ICT + Supervised} \\ \midrule what parts make up the peripheral nervous system & autonomic nervous system & \ldots The connection between CNS and organs allows the system to be in two different functional states: sympathetic and parasympathetic. The peripheral nervous system is divided into the somatic nervous system, and the \textbf{autonomic nervous system}. The somatic nervous system is under voluntary control, and transmits signals from the brain to end organs such as muscles. The sensory nervous system is part of the somatic nervous system and transmits signals from senses such as taste and touch (including fine touch and gross touch) to the spinal cord and brain\ldots \\ \midrule when is the new season of wentworth coming out & 19 June 2018 & \ldots In a similar manner, a 12-episode fourth season was announced before the airing of the third season on 27 February 2015. It began airing from 10 May 2016. Cormack confirmed a fifth season had been commissioned on 19 July. The twelve-part series premiered on 4 April 2017. On 9 May 2017, Showcase announced that the series has been renewed for a sixth season, which premiered on \textbf{19 June 2018}. A seventh season was commissioned in April 2018, before the sixth-season premiere, with filming commencing the following week and a premiere set for 2019\ldots \\ \midrule who challenged the aristotelian model of a geocentric universe & Copernicus & \ldots ("On the Revolutions of the Heavenly Spheres"), which posited that the Earth and the other planets instead revolved around the Sun. The geocentric system was still held for many years afterwards, as at the time the Copernican system did not offer better predictions than the geocentric system, and it posed problems for both natural philosophy and scripture. The Copernican system was no more accurate than Ptolemy\'s system, because it still used circular orbits. This was not altered until Johannes Kepler postulated that they were elliptical (Kepler\'s first law of planetary motion). \ldots \\ \bottomrule \end{tabularx} \caption{Examples of top-1 retrieved documents from the NQ test as outputted from the ICT + Supervised retriever. If the answer exists in the document, it is highlighted in bold.} \label{table:examples} \end{minipage} \end{table*} \section{Reproducibility Checklist} \subsection{For all reported experimental results} \begin{itemize} \item \textit{A clear description of the mathematical setting, algorithm, and/or model}: This is provided in the main paper in Sec.~\ref{sec:retriever} and Sec.~\ref{sec:end-to-end-training}. \item \textit{A link to a downloadable source code, with specification of all dependencies, including external libraries (recommended for camera ready, though welcome for initial submission)}: As mentioned previously, we have developed our codebase over the open-source Megatron-LM library (\url{https://github.com/NVIDIA/Megatron-LM}). Our implementations over this codebase are currently organized in different branches, that are better suited for walk-through with a git-based tool. To preserve anonymity and in good faith, we are submitting the source codes from one branch of our codebase, with the caution that the codebase doesn't contain an exhaustive README file. \item \textit{A description of computing infrastructure used}: We run experiments on Nvidia's Selene cluster where each node's specifications are: Number of CPUs: 256, Physical Memory: 2.2TB, GPU model: 8 x Nvidia A100, GPU architecture and memory: Ampere/80GB, Arch: x86\_64, and Disk size: 10TB. \item \textit{The average runtime for each model or algorithm, or estimated energy cost}: We provide the average runtime and compute used for training different models in Appendix~\ref{sec:training_details}. However, we want to highlight that our codes were not carefully optimized to minimize runtime or to make optimal use of the hardware resources. \item \textit{The number of parameters in each model}: We provide number of parameters in models in Sec.~\ref{sub:model_details}. \item \textit{Corresponding validation performance for each reported test result}: Validation set performance is currently not reported in the main paper. However, we followed rigorous experimentation protocol, and selected the best models by its performance on the validation set. If the program committee or reviewers require the validation set performance, we will include it in the final version of the paper. \item \textit{A clear definition of the specific evaluation measure or statistics used to report results}: Our evaluation metrics are standard and widely used by the question answering community. We provide their details in the main paper in Sec.~\ref{results-ret-training} and Sec.~\ref{sec:answer-extraction}. \end{itemize} \subsection{For all results involving multiple experiments, such as hyperparameter search} \begin{itemize} \item \textit{The exact number of training and evaluation runs:} We provide training details for all models in Appendix~\ref{sec:training_details}. Specifically, for the finetuning experiments, we train the models until convergence, which is $80$ epochs for retriever models and $10$ epochs for answer extraction models. We evaluate the model after each epoch on the validation set and save the best checkpoint according to their performance on the corresponding evaluation metric. \item \textit{Hyperparameter configurations for best-performing models}: We provide the hyperparameter settings in Appendix~\ref{sec:training_details}. \item \textit{The bounds for each hyperparameter}: As described in Appendix~\ref{sec:training_details}, our model and training setting uses standard hyperparameters such as different dropouts $\in [0, 1)$, warmup ratio of optimizer $\in [0.01, 0.05]$, weight regularization $\in [0, 1]$, and learning rate $\in [1e^{-4}, 1e^{-5}]$. The model hyperparameters includes model dimensions $d \in \{768, 1024\}$, number of layers $\in \{12, 24\}$. \item \textit{The method of choosing hyperparameter values (e.g., uniform sampling, manual tuning, etc.) and the criterion used to select among them (e.g., accuracy)}: We performed manual hyperparameter tuning. We also performed tuning of the number of warmup steps for the Adam optimizer. We selected the best hyperparameter using performance on the validation set. \item \textit{Summary statistics of the results (e.g. mean, variance, error bars, etc.)}: All of our experiments are compute expensive large-scale runs utilizing a lot of resources such as CPUs, GPUs and take time ranging from tens of hours to several days. Therefore, due to computational and time constraints performing multiple runs for each experiment was not feasible. Therefore, we adopted the approach of using the same seed value (1234) for all the training runs including both pre-training and finetuning experiments. \end{itemize} \subsection{For all datasets used} \begin{itemize} \item \textit{Details of train/validation/test splits}: We use the standard training / dev / test splits whose details are provided in Sec.~\ref{sec:exp-setup}. \item \textit{Relevant statistics such as number of examples and label distributions}: We provide dataset statistics details in Table~\ref{tab:dataset_stats}. \item \textit{An explanation of any data that were excluded, and all pre-processing steps}: We include the relevant details in Sec.~\ref{sec:exp-setup}. \item \textit{For natural language data, the name of the language(s)}: Our datasets are in English language. \item \textit{A link to a downloadable version of the dataset or simulation environment}: Both the datasets of NQ and TriviaQA are open-source and widely used by the community. NQ is available at: \url{https://ai.google.com/research/NaturalQuestions/download}. TriviaQA is available at: \url{http://nlp.cs.washington.edu/triviaqa/}. We make use of the NQ, TriviaQA, and Wikipedia datasets as open-sourced by the DPR authors~\cite{karpukhin2020dense} here: \url{https://github.com/facebookresearch/DPR/blob/master/data/download_data.py}. \item \textit{For new data collected, a complete description of the data collection process, such as instructions to annotators and methods for quality control}: This is not applicable to this work. \end{itemize} \section*{Broader Impact and Ethics Statement} To understand the ethical context of our work on open-domain question answering, it is important to consider the real-world use cases and potential individuals who may interact with systems developed based on our proposed methods. The potential real-world applications could be search engines or virtual assistants, where our techniques can improve the question-answering ability. However, it is worthwhile to mention that our trained systems can not be deployed off-the-shelf for such applications, given that our models were trained on the Natural Questions and TriviaQA datasets with the goal of matching the specific training data distribution. Real-world applications building on our work should be re-trained using a custom training dataset that is relevant to the kind of queries that originates in practice. Our system represents a prototype model for answering questions over Wikipedia and can easily be extended to be used in sensitive contexts such as legal or health-care settings. However, extensive and robust quality assurance testing will be needed as our system was not designed to meet those criteria. More generally, there is the possibility of social biases which could be introduced by the training data. Since we did not control or regularize our model to remove such biases, we would urge the users to undertake the necessary quality-assurance testing to evaluate and understand the extent to which such biases might be present. User should also understand how much these biases are impacting their trained system and to make modifications to their training data and procedures accordingly. \section{Conclusion} \label{sec:conclusion} We propose approaches to improve the retrieval accuracy of the dual-encoder model for the OpenQA task. We first perform a systematic investigation of the importance of pre-training with ICT and masked salient spans tasks for supervised training of the retriever. We then present two approaches for end-to-end training of the reader and retriever components in OpenQA. In one approach, the reader considers each retrieved document individually while in the other approach where the reader considers all the retrieved documents jointly. Overall, these methods help achieve state-of-the-art results on both retrieval and answer extraction. \section{Experimental Setup} \label{sec:exp-setup} In this section, we describe the datasets and model settings. For reproducibility, we provide training details and list the hyperparameters in Appendix~\ref{sec:training_details}. \subsection{OpenQA Datasets} We perform experiments using two widely used QA datasets whose details are provided below and their statistics are shown in Table~\ref{tab:dataset_stats}. \paragraph{Natural Questions (NQ):} This corpus consists of real questions asked from the Google search engine along with their long and short answer annotations from the top-ranked Wikipedia pages~\cite{Kwiatkowski2019natural}. Following prior work~\cite{karpukhin2020dense}, we use the same subset of the short answer questions in our experiments, as it is more suited for OpenQA. \paragraph{TriviaQA:} This corpus consists of a collection of trivia questions and their answers scraped from multiple sources in the Web~\cite{joshi2017triviaqa}. \paragraph{Evidence:} Following~\cite{karpukhin2020dense}, we make use of their released preprocessed English Wikipedia dump from December 2018 as the source of evidence documents. Overall, there are $21,015,324$ documents, each $100$ words long. \begin{table}[t] \centering \small \begin{tabular}{@{}l c c c c@{}} \toprule \textbf{Dataset} & \textbf{\ Train} & \textbf{Filtered Train} & \textbf{Dev} & \textbf{Test} \\ \midrule NQ & 79,168 & 58,880 & 8,757 & \phantom{0}3,610 \\ TriviaQA & 78,785 & 60,413 & 8,837 & 11,313 \\ \bottomrule \end{tabular} \vspace{-6pt} \caption{OpenQA dataset statistics. The training set is used for end-to-end training, while the filtered version is used for retriever training. The filtered set ignores those examples where the document retrieved from evidence does not align with the ground-truth document. } \label{tab:dataset_stats} \vspace{-6pt} \end{table} \subsection{Model Details} \label{sub:model_details} We use two models of different sizes, {\it base} and {\it large}, for the experiments. The base configuration consists of $12$ layers, $768$-d hidden size, and $12$ attention heads. The BERT-base contains $110$M parameters while the T5-base contains $220$M parameters. The large configuration consists of $24$ layers, $1024$-d hidden size, and $16$ attention heads. The BERT-large contains $330$M parameters while the T5-large contains $770$M parameters. \section{Introduction} The task of open-domain question answering (OpenQA) consists of finding \emph{answers} to the information-seeking \emph{questions} using a large knowledge source such as Wikipedia. This knowledge source is also referred to as \emph{evidence} and it typically contains millions of documents. Most approaches for OpenQA consist of a two-stage pipeline~\cite{chen2017reading,chen2018neural}. In the first stage, given a question, a \emph{retriever} module identifies the most relevant documents, which is often a very small subset of the evidence known as \emph{context documents}. Traditionally, approaches based on document ranking such as BM25~\cite{Robertson2009bm25} have been used for the retriever. In the second stage, these relevant documents are given as input to the \emph{reader} module, which understands them and extracts the answer for the question (Figure~\ref{fig:openqa-intro}). \begin{figure}[t] \centering \includegraphics[max width=0.5\textwidth, scale=0.9]{fig/intro2.pdf} \vspace{-8pt} \caption{An example illustrating OpenQA pipeline.} \label{fig:openqa-intro} \vspace{-7pt} \end{figure} The main drawback of the BM25 method is that it is not trainable and hence it can't be adapted to tasks involving open-retrieval. Recent work has addressed this limitation by building upon advances in self-supervised learning, such as BERT~\cite{devlin2019bert}. These approaches model both the retriever and reader using neural networks, allowing the retriever to be trained using task-specific datasets~\cite{lee-etal-2019-latent,guu2020realm}. Typically, the retriever model consists of a \emph{dual-encoder} architecture~\cite{bromley1994signature}, where one encoder processes the question and the other encoder processes the context document. Prior work has investigated both unsupervised and supervised approaches to train the retriever. Unsupervised approaches include separately training the retriever with Inverse Cloze Task (ICT)~\cite{lee-etal-2019-latent} or training the retriever and reader jointly by predicting masked salient spans (REALM)~\cite{guu2020realm}, while supervised approaches such as Dense Passage Retrieval (DPR)~\cite{karpukhin2020dense} train the retriever using human-annotated sets of question and context pairs. However, there is no study that investigates the comparative advantages of using these two styles of training when the retrieval task is challenging, \emph{i.e.}, when the evidence contains millions of documents. It is unclear if the unsupervised approaches can further help to improve the performance of \emph{strong} supervised approaches, and, if so, under what conditions. A core focus of this work is systematically studying these aspects of retriever training. We propose a unified approach to train the retriever: unsupervised pre-training followed by supervised finetuning. We also investigate key design choices---such as relevance score scaling and longer training---and showcase their effectiveness. Our results demonstrate that the proposed approach obtains substantial accuracy gains when evaluated on benchmark OpenQA datasets. Extensive experiments also highlight the relative importance of different pre-training strategies, revealing important trade-offs when varying the amount of supervised data available to train the retriever. Furthermore, motivated by recent work~\cite{guu2020realm,lewis2020pre}, we also explore two approaches for end-to-end supervised training of the reader and retriever components. In the first approach, the reader considers each retrieved document separately while in the second approach, the reader takes as input all the retrieved documents together. We compare the effectiveness of these approaches on both retrieval accuracy and answer extraction. We show that the first approach leads to an improved retrieval performance, while the second approach results in an improved answer extraction. With end-to-end training, we outperform previous best models to obtain new state-of-the-art results on retrieval accuracy and answer extraction. We also perform experiments by scaling the model size to a large configuration for both retriever and reader and observe consistent improvements, compared with smaller models. In summary, the contributions of this work are: \vspace{-2mm} \begin{itemize}[noitemsep,leftmargin=*] \item We demonstrate that our proposed method of \emph{unsupervised pre-training} of the retriever with ICT followed by \emph{supervised finetuning} leads to absolute gains of more than 2 points in the top-20 retrieval accuracy over the previous best result on Natural Questions and TriviaQA datasets. \item We show that \emph{masked salient spans}-based pre-training of the retriever is more effective when the supervised dataset sizes are small. \item Our \emph{end-to-end} training approach obtains new state-of-the-art performance on retrieval accuracy. On Natural Questions, our top-20 accuracy is $84$, which is a $5$ points gain over DPR results. \item We achieve competitive results on \emph{answer extraction} with gains of more than $3$ points over recent models such as REALM~\cite{guu2020realm} and RAG~\cite{Lewis2020Retrieval}. \item We \emph{scale up} end-to-end training to \emph{large models} and show \emph{consistent gains} in performance. \end{itemize} The rest of the paper is organized as follows. Sec.~\ref{sec:retriever} and \ref{sec:end-to-end-training} explain the retriever model and end-to-end training, respectively. Sec.~\ref{sec:exp-setup}-\ref{sec:answer-extraction} describe the experimental details with the results. Sec.~\ref{sec:related-work} reviews the related work followed by conclusion in Sec.~\ref{sec:conclusion}. \section{Neural Retriever} \label{sec:retriever} In this section, we first describe the retriever architecture and then discuss different approaches to train it, including our proposed approach. \subsection{Background} Given a collection of documents in the evidence $\mathcal{Z}=\{z_1, \cdots, z_m\}$ and a question $q$, the task of the retriever is to select a relevant subset of documents for the question. To do this, the retriever performs a ranking of the evidence documents conditioned on the question and outputs the top-ranked documents. The retriever model consists of two modules: a question encoder ($f_Q$) and a context encoder ($f_Z$). Such a model is often referred to as a \emph{dual-encoder model}~\cite{bromley1994signature}. Here, we detail the training methodology of the dual-encoder model given a questions ($q$) and context documents ($z_i$) from $\mathcal{Z}$. First, we compute the \emph{relevance score} between the question and context. We define the relevance score to be the dot-product between the question and context representations \begin{equation} s(q, z_i; \phi) = f_Q(q)^\top f_Z(z_i) \end{equation} where $f_Q(q) \in \mathbb{R}^d$ and $f_Z(z) \in \mathbb{R}^d$ denote the question and context encoders, respectively, which are parameterized by $\phi = [\phi_Q, \phi_Z]$. We model the $f_Q$ and $f_Z$ using BERT-style transformer networks~\cite{devlin2019bert,vaswani2017attention}. We consider the hidden states of the first token of the sequence (i.e.\ [CLS] token) as the encoder's output. The probability of a context document $z_i$ being relevant to the question $q$ is calculated as \begin{equation} \label{eq:ret-sim} p(z_i \mid q, \mathcal{Z}; \phi) = \frac{\exp(s(q, z_i; \phi)/\tau)} {\sum_{j=1}^{|\mathcal{Z}|} \exp(s(q, z_j; \phi)/\tau)} \end{equation} where $\tau$ is a scaling factor. While previous work had used the setting of $\tau=1$, in this work, we set $\tau=\sqrt{d}$. Bigger scaling factor helps in better optimization when the model hidden size ($d$) is large. We refer to this as \emph{relevance score scaling}. To train the retriever, we maximize the log-likelihood computed from Eq.~\ref{eq:ret-sim}. In practice, as the evidence set consists of millions of documents, the normalization term would be expensive to compute. Hence, we approximate the denominator of the above equation by using the context documents in the batch as negative examples, a technique that has shown to perform well in practice~\cite{pmlrchen20j}. \subsection{Training} In this section, we discuss different approaches to train the retriever. In all the approaches, we initialize the parameters of both the question and context encoders using BERT weights as implemented in Megatron-LM~\cite{shoeybi2019megatron}. We also experimented with random initialization but it vastly underperformed BERT initialization. \subsubsection{Supervised Training} \label{methods:supervised} In the supervised setting, \emph{human-annotated} questions, answers, and sometimes context are provided. If the context is not included, then a common approach is to use distant supervision~\cite{mintz2009distant} to obtain the context document. Specifically, we select the top-ranked document using BM25~\cite{Robertson2009bm25} from the evidence that contains the answer as the context. We also select other top-ranked documents that do not contain the answer as additional \emph{hard} negative examples. This approach to train neural retriever was popularized by~\cite{karpukhin2020dense}. \subsubsection{Unsupervised Training} \label{subsec:unsup-ret-train} \paragraph{Inverse Cloze Task (ICT):} In this setup, we do not consider the human-annotated question-context pairs. Instead, the retriever is trained in an unsupervised manner. Specifically, a randomly sampled sentence from a paragraph is considered as the query while other sentences as the context. This approach was first proposed by~\cite{lee-etal-2019-latent}. \paragraph{Masked salient spans training:} ~\cite{guu2020realm} showcased that the ICT initialized retriever can be further improved by training it with an objective where the reader predicts the masked salient spans such as named entities conditioned on the retrieved documents. In this work, we adopt the same approach. However, unlike~\cite{guu2020realm} who use BERT for the reader, we use a generative language model based on T5~\cite{raffel2020t5}. \subsection{Proposed Approach: Unsupervised Pre-training and Supervised Finetuning} \label{proposed-approach} To improve the retriever training, we propose the approach of unsupervised pre-training of the retriever followed by supervised finetuning. In this approach, we first pre-train the retriever weights with ICT training or masked salient spans training (Sec.~\ref{subsec:unsup-ret-train}). After pre-training, we finetune the retriever with supervised training (Sec.~\ref{methods:supervised}). \section{End-to-End Retriever and Reader Training} \label{sec:end-to-end-training} \begin{figure*}[t] \centering \includegraphics[max width=1.0\textwidth, scale=0.9]{fig/openqa-small.pdf} \hspace{-2cm} \vspace{-5pt} \caption{A schematic diagram illustrating end-to-end supervised training of the retriever and reader components.} \label{fig:end-to-end-training} \vspace{-6pt} \end{figure*} In this section, we explore two \emph{supervised training} approaches to end-to-end train the reader and retriever components from the task-specific data. In the first approach, the reader considers each retrieved document separately (Sec.~\ref{sim-weighted_likelihood}) while in the second approach, the reader takes as input all retrieved documents together (Sec.~\ref{inter-attention}). These approaches are designed such that when predicting the answer conditioned on the question, the learning process improves both the reader and retriever. \paragraph{Background and notation:} In end-to-end training, the trainable components consists of the retriever ($\phi$) and reader ($\theta$) parameters. For retriever, we use the dual-encoder architecture and train it as discussed previously in Sec.~\ref{proposed-approach}. Our reader is a \emph{generative model} designed according to the sequence-to-sequence modeling paradigm~\cite{ilya2014sequence}. Specifically, we use pre-trained T5 as the reader. The inputs to the training process are \emph{questions} ($q$) and its \emph{answers} ($a$), both in string form. Given a question, first the retriever obtains the \emph{k relevant} context documents ($\mathcal{K}$) from the evidence ($\mathcal{Z}$) as \begin{equation} \mathcal{K} = \argsort_{z_i \in \mathcal{Z}} s(q, z_i; \phi)[:k] \end{equation} The reader then takes the question and one or more context documents ($z_i$) as input to predict the answer, the likelihood of which is defined as \begin{equation} p(a \mid q, z_i; \theta) = \prod_{j=1}^{N} p\left(a_j \mid a_{1:j-1}, q, z_i; \theta\right), \end{equation} where $N$ is the number of answer tokens. Next, we describe the two proposed approaches. A block diagram illustrating the end-to-end training process is shown in Figure~\ref{fig:end-to-end-training}. \subsection{Approach 1: Individual Top-k} \label{sim-weighted_likelihood} In this approach, similar to~\cite{guu2020realm}, the reader's likelihood is first computed conditioned on the question and each retrieved document. The marginal likelihood is defined as the weighted average of the \emph{individual} likelihoods as \begin{equation} \label{eq:indiv-topk} p(a \mid q; \theta,\phi) = \sum_{z_i \in \mathcal{K}} p(a \mid q, z_i; \theta) p(z_i \mid q, \mathcal{Z}; \phi), \end{equation} where $p(z_i \mid q, \mathcal{Z}; \phi)$ is computed using Eq.~\ref{eq:ret-sim}. However, the normalization is done over $\mathcal{K}$ instead of $\mathcal{Z}$. The final loss is defined as the negative marginal log-likelihood \begin{equation} \label{eq:loss} \mathcal{L}(q, a) = -\log p(a \mid q; \theta,\phi). \end{equation} We note that the RAG model~\cite{Lewis2020Retrieval} also proposed a similar approach, but there are two main differences. The first is that while we update all the parameters of the retriever (both the query and context encoders), RAG just updates the query encoder. The second is that we use T5 model as the reader while RAG uses BART model~\cite{lewis2020bart}. These enhancements help us obtain substantial gains over the RAG model, which we will discuss in Sec.~\ref{sec:answer-extraction}. \subsection{Approach 2: Joint Top-k} \label{inter-attention} In this approach, similar to~\cite{lewis2020pre}, the likelihood is defined as the reader's likelihood conditioned on the question, \emph{all} the retrieved documents, and the retrieval score \begin{equation} \label{eq:joint-topk} p(a \mid q; \theta,\phi) = p(a \mid q, z_{1:k},p(z \mid q, \mathcal{Z}; \phi); \theta). \end{equation} As the T5 reader consists of separate encoder and decoder modules, it provides the flexibility to customize the input or output of the encoder. We concatenate each retrieved document with the question and feed them as input to the encoder, which computes their hidden representations. Next, we stack the hidden representations of all the retrieved documents, which the decoder \emph{jointly} attends to during the encoder-decoder attention, thus allowing a more powerful form of information aggregation from multiple retrieved documents. We also add retriever similarity score to bias the encoder-decoder attention as it helps facilitate end-to-end training and enables the reader to pay higher attention to the relevant documents. The interaction score during the encoder-decoder attention is computed as \begin{equation} \text{attn}(q, a, z_{1:k}) \propto Q(a)^\top K(z_{1:k}, q) + \lambda p(z \mid q; \phi), \end{equation} where $Q$ is the query vector computed from decoder's input, $K$ is the key vector computed from encoder's output, and $\lambda$ is a trainable parameter. Final loss is defined according to Eq.~\ref{eq:loss}. We further note that a similar approach for OpenQA was proposed in~\cite{izacard2020leveraging} but it only optimizes the reader model and didn't perform end-to-end training of the retriever. \section{Related Work} \label{sec:related-work} \cite{yih-etal-2011-learning} proposed a discriminative approach to train a retriever by learning dense representations of query and context documents based on word frequency. However, this approach was data-hungry and not scalable. Recently,~\cite{lee-etal-2019-latent,karpukhin2020dense} address this by leveraging pre-trained BERT weights~\cite{devlin2019bert} to train a dual-encoder retriever by using smaller amounts of question-context pairs. In particular,~\cite{lee-etal-2019-latent} first pre-train the retriever in an unsupervised manner using ICT and then jointly train the retriever and reader for OpenQA. On the other hand,~\cite{karpukhin2020dense} perform supervised training of the retriever using hard-negative examples, yielding impressive results on several retrieval benchmarks. To improve the retrieval accuracy of the dual-encoder model,~\cite{Chang2020Pre-training} explore several paragraph-level pre-training strategies including the application of ICT. They demonstrated the effectiveness of pre-training over sparse-retrieval approaches such as BM25. Their evidence consisted of the training documents that was further increased to $1$M documents for OpenQA. Our work differs from them in several ways. First, our OpenQA setup is more challenging as the evidence consists of $21$M documents. Second, we pre-train with two strategies consisting of ICT and masked salient-spans and finetune using strong supervised methods, which leads to much improved results. Third, we further update the retriever with end-to-end training leveraging question-answer pairs, which further improves the retrieval accuracy leading to new state-of-the-art results. A new line of work investigates task-specific pre-training of language models. For example,~\cite{guu2020realm} predicts masked salient spans consisting of named entities to pre-train the reader and retriever components for OpenQA. Similarly,~\cite{lewis2020pre} perform cross-lingual pre-training where the objective is to predict a sequence using its paraphrases in different languages, demonstrating improved zero-shot performance in document translation tasks. \section{Results: Retriever Training} \label{results-ret-training} \begin{table}[t] \centering \small \begin{tabular}{@{}l c c c c@{}} \toprule \textbf{Setting} & \textbf{Top-1} & \textbf{Top-5} & \textbf{Top-20} & \textbf{Top-100} \\ \midrule \multicolumn{5}{c}{\textit{Base Configuration}}\\ \midrule \lbrack CLS\rbrack, 40 epochs & 32.6 & 60.1 & 76.4 & 85.9 \\ + score scaling & 34.1 & 60.9 & 77.6 & 85.9 \\ + 80 epochs & 36.7 & 62.2 & 77.4 & {\bf 86.0} \\ + 1 hard negative & {\bf 48.6} & {\bf 74.5} & {\bf 79.0} & 85.8 \\ \midrule DPR (Official) & -- & 67.1 & 78.4 & 85.4 \\ \bottomrule \end{tabular} \vspace{-6pt} \caption{Effect of different factors on the supervised training of retriever when evaluated on NQ test set.} \label{tab:score-scaling-gnq} \vspace{-6pt} \end{table} \begin{table*}[t] \small \centering \begin{tabular}{@{}l c c c c c c c c@{}} \toprule \textbf{Model} & \multicolumn{4}{c}{\textbf{NQ}} & \multicolumn{4}{c}{\textbf{TriviaQA}} \\ \midrule & \textbf{Top-1} & \textbf{Top-5} & \textbf{Top-20} & \textbf{Top-100} & \textbf{Top-1} & \textbf{Top-5} & \textbf{Top-20} & \textbf{Top-100} \\ \midrule \multicolumn{9}{c}{\textit{Base Configuration}}\\ \midrule BERT (zero-shot) & \phantom{0}0.9 & \phantom{0}3.9 & \phantom{0}9.4 & 20.3 & \phantom{0}0.6 & \phantom{0}2.8 & \phantom{0}7.2 & 17.8 \\ ICT (zero-shot) & 12.6 & 32.3 & 50.6 & 66.8 & 19.2 & 40.2 & 57.5 & 73.6 \\ Masked salient spans (zero-shot) & 20.0 & 41.7 & 59.8 & 74.9 & 31.7 & 53.3 & 68.2 & 79.4 \\ BERT + Supervised & 48.6 & 68.8 & 79.0 & 85.8 & 57.5 & 72.2 & 80.0 & 85.1 \\ ICT + Supervised & 48.4 & {\bf 72.1} & 81.8 & {\bf 88.0} & 58.4 & 73.9 & 81.7 & 86.3 \\ Masked salient spans + Supervised & {\bf 50.3} & 71.9 & {\bf 82.1} & 87.8 & {\bf 60.6} & {\bf 74.8} & {\bf 81.8} & {\bf 86.6} \\ \midrule \multicolumn{9}{c}{\textit{Large Configuration}}\\ \midrule ICT (zero-shot) & 13.0 & 31.8 & 49.3 & 66.1 & 20.1 & 41.6 & 58.5 & 74.1 \\ BERT + Supervised & 51.4 & 71.0 & 81.0 & 87.2 & 60.4 & 74.5 & 81.4 & 86.0 \\ ICT + Supervised & {\bf 52.4} & {\bf 72.7} & {\bf 82.6} & {\bf 88.3} & {\bf 61.9} & {\bf 76.2} & {\bf 82.9} & {\bf 87.1} \\ \bottomrule \end{tabular} \vspace{-6pt} \caption{Effect of unsupervised pre-training on retrieval accuracy when evaluated on NQ and TriviaQA test sets. } \label{tab:ret-init} \vspace{-6pt} \end{table*} In this section, we compare different approaches to train the retriever. Retrieval accuracy is evaluated using the top-k metric ($k \in \{1, 5, 20, 100\}$). \subsection{Effect of Relevance Score Scaling, Longer Training, and Hard Negatives} We explore the best training settings for \emph{supervised} training of the retriever. To do so, we perform a series of experiments on the NQ dataset starting with the training settings from the popular DPR model and then progressively improve it. DPR was initialized with BERT, trained for $40$ epochs, with a scaling factor of $1$, and utilized [CLS] token embeddings from the retriever. Our result with this setting is shown in Table~\ref{tab:score-scaling-gnq}. We then observe that incorporating relevance score scaling and longer training till $80$ epochs helps to improve the top-5 and top-20 accuracy by $1.5$-$2$ points. These results also signify that the original DPR model was significantly undertrained and not fully optimized. In addition to score scaling, we further include $1$ additional hard-negative example (similar to DPR) for each question-context pair and train the model for 80 epochs. Our results, in sync with the results of DPR, obtain substantial additional gains in performance. \emph{These findings highlight that relevance score scaling, longer training, and including a hard negative example are essential to improve the supervised retriever's accuracy}. These supervised training results can be considered as a very strong baseline. Hence, we employ these settings in subsequent experiments. \subsection{Effect of Retriever Initialization} \label{subsec:ret-init} We first characterize the zero-shot retriever's performance when its weights are initialized with either BERT or ICT or masked salient spans pre-training (Table~\ref{tab:ret-init}). As is understood that unsupervised language models do not perform well in information retrieval tasks~\cite{lee-etal-2019-latent}, evidently, BERT also leads to a poor retrieval accuracy. We note that ICT initialization is quite effective in providing a non-trivial zero-shot accuracy which is further improved by masked salient spans training by more than $8$ points. Both being unsupervised approaches demonstrate their utility in effectively bootstrapping the retriever almost from scratch. We next empirically analyze our proposed approach of pre-training with ICT and masked salient spans followed by supervised finetuning. We observe that it provides absolute improvements of $2$-$3$ points over the already strong supervised training results, with the gains being consistent across both the datasets. These results highlight that even after finetuning the retriever with thousands of labeled examples, it does not lead to catastrophic forgetting of the discriminative properties learned by the retriever during ICT and masked salient spans pre-training. Another merit is that being unsupervised, large text collections can be leveraged to pre-train the retriever, a considerable advantage over data-augmentation methods which rely on the availability of human-annotated question-context pairs. \emph{Furthermore, when comparing ICT with masked salient spans initialization, we note that their accuracy gains are roughly similar}. \subsection{Effect of Amount of Training Data} We study the effect on accuracy when the retriever is pre-trained with BERT, ICT, or masked salient spans and the amount of supervised training data is varied. We train the retriever with $1\%$, $2\%$, $5\%$, $10$-$50\%$, of NQ's training data and plot the top-20 accuracy in Figure~\ref{fig:vary-train-nq}. Results reveal that in the low-resource regime, \emph{masked salient spans pre-training is much more effective than ICT, consistently leading to large gains}. As the fraction of training data increases to beyond $40\%$ towards a high-resource setup, \emph{the gains from salient spans pre-training saturates to that of ICT}. We believe that these findings will have important implications for future research in OpenQA---with only a few hundred examples, performing expensive masked salient span training is beneficial while if the training data has thousands of examples, ICT is just as optimal as masked salient spans training. \begin{figure}[t] \centering \includegraphics[max width=0.5\textwidth, scale=0.9]{fig/cmp_top20.pdf} \vspace{-10pt} \caption{Effect of amount of training data on retrieval accuracy when evaluated on NQ test set.} \label{fig:vary-train-nq} \vspace{-6pt} \end{figure} \subsection{Effect of End-to-End Training} \label{subsec:joint-ret} \begin{table*}[t] \small \centering \begin{tabular}{@{}l c c c c c c c c c c@{}} \toprule \textbf{Model} & & & \multicolumn{4}{c}{\textbf{NQ}} & \multicolumn{4}{c}{\textbf{TriviaQA}} \\ \midrule & {\bf Q} & {\bf C} & \textbf{Top-1} & \textbf{Top-5} & \textbf{Top-20} & \textbf{Top-100} & \textbf{Top-1} & \textbf{Top-5} & \textbf{Top-20} & \textbf{Top-100} \\ \midrule \multicolumn{11}{c}{\textit{Base Configuration}}\\ \midrule DPR~\cite{karpukhin2020dense} & & & -- & 67.1 & 78.4 & 85.4 & -- & -- & 79.4 & 85.0 \\ \midrule ICT + Supervised & & & 48.4 & 72.1 & 81.8 & 88.0 & 58.4 & 73.9 & 81.7 & 86.3 \\ Individual Top-k & \ding{51} & \ding{55} & 54.5 & 73.7 & 83.2 & 88.6 & 61.4 & 75.6 & 82.1 & 86.7 \\ Individual Top-k & \ding{51} & \ding{51} & {\bf 56.8} & {\bf 75.0} & {\bf 84.0} & {\bf 89.2} & {\bf 63.5} & {\bf 76.8} & {\bf 83.1} & {\bf 87.0} \\ Joint Top-k & \ding{51} & \ding{55} & 51.1 & 72.1 & 81.8 & 87.8 & 59.1 & 74.1 & 81.3 & 86.3 \\ \midrule \multicolumn{11}{c}{\textit{Large Configuration}}\\ \midrule ICT + Supervised & & & 52.4 & 72.7 & 82.6 & 88.3 & 61.9 & 76.2 & 82.9 & 87.1 \\ Individual Top-k & \ding{51} & \ding{51} & {\bf 57.5} & {\bf 76.2} & {\bf 84.8} & {\bf 89.8} & {\bf 66.4} & {\bf 78.7} & {\bf 84.1} & {\bf 87.8} \\ Joint Top-k & \ding{51} & \ding{55} & 53.7 & 73.3 & 83.2 & 88.0 & 61.2 & 75.9 & 82.7 & 87.0 \\ \bottomrule \end{tabular} \vspace{-6pt} \caption{Effect of end-to-end training using question-answer pairs on retrieval accuracy. {\bf Q} and {\bf C} signify if the query encoder and the context encoder are updated during training or not, respectively.} \label{tab:joint-train-ret} \vspace{-6pt} \end{table*} For end-to-end training, retriever weights are initialized with the previous best setting of ICT pre-training and supervised finetuning. The number of retrieved evidence documents for the reader is considered as a hyperparameter and is selected via performance on the dev set. The focus here is to analyze the effect on retrieval accuracy when updating the retriever weights using question-answer pairs in an end-to-end setting (Sec.~\ref{sec:end-to-end-training}). From the results in Table~\ref{tab:joint-train-ret}, we observe that for \emph{Individual Top-k}, when only the query encoder is updated, it tends to improve retrieval accuracy. In addition, when the context encoder is also updated, the retrieval accuracy improves to $75\%$ at top-5, a big gain of $8$ points over the previous best DPR retriever. Larger models further help to improve the performance leading to new state-of-the-art results. On the other hand, in \emph{Joint Top-k}, updating the query encoder just improves the top-1 score but does not really lead to much accuracy gains for higher top-k's. We also do not update the context encoder for \emph{Joint Top-k} as it did not result in improvements during our initial experiments. These results showcase that when the retriever is already well-initialized, the objective function of \emph{Individual Top-k} method is designed such that it significantly improves the retrieval accuracy while the \emph{Joint Top-k} method does not result in improvements. As we will show next, that the usefulness of this method lies in answer extraction. \subsection{Intuition for Retriever Score Scaling} \begin{table}[t] \centering \small \begin{tabular}{@{}l c c c c c@{}} \toprule \textbf{$\times \sqrt{d}$} & \textbf{Top-1} & \textbf{Top-5} & \textbf{Top-20} & \textbf{Top-100} & \textbf{Avg.} \\ \midrule \multicolumn{6}{c}{\textit{Base Configuration}}\\ \midrule 0.25 & 48.8 & 69.3 & 78.7 & 85.5 & 70.6 \\ 0.5 & 51.4 & 71.6 & 81.5 & 87.7 & 73.1 \\ 1 & 51.1 & 71.8 & 82.1 & 87.7 & \textbf{73.2} \\ 2 & 50.2 & 71.5 & 81.9 & 87.9 & 72.9 \\ 4 & 50.6 & 71.7 & 81.7 & 88.0 & 73.0 \\ \bottomrule \end{tabular} \vspace{-6pt} \caption{Effect of score scaling factor ($\tau$) on the retrieval accuracy when evaluated on the NQ test set. The first column denotes the multiple ($m$) that is multiplied by $\sqrt{d}$ to obtain $\tau$, i.e., $\tau = m \times \sqrt{d}$ in Equation \ref{eq:ret-sim}.} \label{tab:score-scaling-intuition} \vspace{-6pt} \end{table} Retrieval score scaling is used when computing the probability distribution of the retrieved documents according to Equation \ref{eq:ret-sim}, where the retrieval score is normalized by the scaling factor ($\tau$). To study the effect of $\tau$ on the retrieval accuracy, we perform an ablation study with different values of $\tau$ on the NQ retrieval task, whose results can be seen in Table~\ref{tab:score-scaling-intuition}. More specifically, we choose different values of $\tau$ as a multiple of $\sqrt{d}$, where $d$ is the hidden size of the model. Our results indicate that the choice of $\tau=\sqrt{d}$ works well in practice. Here, we briefly explain the intuition regarding the usage of the scaling factor. In our preliminary experiments on retriever training and end-to-end training without the scaling factor, we observed that a few of the top-k document’s similarity score with the query was very high that in turn led to it being assigned a high retrieval probability score. This high score was leading to a skewed probability distribution with most of the mass being centered over the top-1 or top-2 retrieved documents. A larger value of scaling factor results in a more even distribution of probability mass over the top-k documents, which in turn leads to better results in both retrieval accuracy and in the end-to-end training. \section{Results: Answer Extraction} \label{sec:answer-extraction} We next present the results of end-to-end training on answer extraction. To train the model, retriever weights are initialized with ICT pre-training and supervised finetuning while the reader is initialized with pre-trained T5 weights. The number of retrieved evidence documents for the reader is tuned on the dev set. Results are reported using the conventional Exact Match (EM) metric. \subsection{Individual Top-k Approach} \begin{table}[t] \small \centering \begin{tabular}{l c c} \toprule \textbf{Model} & \textbf{NQ} & \textbf{TriviaQA} \\ \midrule \multicolumn{3}{c}{\textit{Base Configuration}} \\ \midrule ORQA~\cite{lee-etal-2019-latent} & 33.3 & 45.0 \\ REALM~\cite{guu2020realm} & 40.4 & -- \\ DPR~\cite{karpukhin2020dense} & 41.5 & 56.8 \\ Individual Top-k & {\bf 45.9} & 56.3 \\ \midrule \multicolumn{3}{c}{\textit{Large Configuration}} \\ \midrule RAG~\cite{Lewis2020Retrieval} & 44.5 & 56.8 \\ Individual Top-k & {\bf 48.1} & {\bf 59.6} \\ \bottomrule \end{tabular} \vspace{-6pt} \caption{Answer extraction results using \emph{Individual Top-k} approach. The grouping under base and large configurations is based on the size of the reader model.} \label{tab:indiv-topk-ans} \vspace{-6pt} \end{table} \begin{figure}[t] \centering \includegraphics[max width=0.5\textwidth, scale=0.95]{fig/indiv_topk.pdf} \vspace{-8pt} \caption{Effect of increasing top-k documents on answer generation for \emph{Individual Top-k} approach.} \vspace{-6pt} \label{fig:indiv-topk-varyk-nq} \end{figure} We compare our results as presented in Table~\ref{tab:indiv-topk-ans} with the recent related approaches in OpenQA. For the base configuration on NQ, our model outperforms both REALM and DPR by more than $4$ points. For the large configuration, we compare with the RAG model~\cite{Lewis2020Retrieval}, where our approach outperforms it by $3.5$+ points on NQ and by $2.8$ points on TriviaQA. \emph{Our improved results are because of a more accurate initial retriever, stronger reader, and updating both the query and context encoders during training}. Our analysis in Figure~\ref{fig:indiv-topk-varyk-nq} reveals that updating the context encoder improves the results for both the base and large configurations. Quite surprisingly, we also observe that the performance of \emph{Individual Top-k} approach is sensitive to the number of top-k documents and can also decrease with an increase in top-k documents. We leave an in-depth investigation of this as a future work. \subsection{Joint Top-k Approach} We compare our results with the recent Fusion-in-Decoder (FiD) approach~\cite{izacard2020leveraging} that also performs joint encoder-decoder attention. It consists of DPR as the retriever and T5 as the reader, which are initialized with their open-source weights. However, unlike our approach, FiD just finetunes the reader weights. Our results in Table~\ref{tab:joint-topk-ans} show that for the base configuration, Joint Top-k outperforms the FiD model by 1 point on NQ, highlighting the significance of end-to-end training. For the large configuration, we obtain a gain of 0.7 points on TriviaQA. \begin{table}[t] \small \centering \begin{tabular}{l c c} \toprule \textbf{Model} & \textbf{NQ} & \textbf{TriviaQA} \\ \midrule \multicolumn{3}{c}{\textit{Base Configuration}} \\ \midrule FiD~\cite{izacard2020leveraging} & 48.2 & 65.0 \\ Joint Top-k & {\bf 49.2} & 64.8 \\ \midrule \multicolumn{3}{c}{\textit{Large Configuration}} \\ \midrule FiD~\cite{izacard2020leveraging} & 51.4 & 67.6 \\ Joint Top-k & {\bf 51.4} & {\bf 68.3} \\ \bottomrule \end{tabular} \vspace{-6pt} \caption{Results on answer extraction using \emph{Joint Top-k} approach. } \label{tab:joint-topk-ans} \vspace{-6pt} \end{table} Our analysis in Figure~\ref{fig:joint-topk-varyk-nq} portrays that the EM scores improve with more retrieved documents. This highlights that in contrast to \emph{Individual Top-k}, the \emph{Joint Top-k} better aggregates the information contained in the retrieved documents. This Figure also illustrates the effect of similarity enriched attention on answer extraction for the base configuration. For values of top-k=5, 10, and 25, using retrieval-similarity enriched encoder-decoder attention, we consistently observe a gain of 0.8-1 EM points (comparing orange plot and blue plot in Figure~\ref{fig:joint-topk-varyk-nq}), while there is a smaller gain when top-k=50. This signifies that with more retrieved documents, the utility of end-to-end training tends to diminish, thus explaining the lower gains observed in retrieval performance for \emph{Joint Top-k} in Table~\ref{tab:joint-train-ret}. \subsection{Overall Comparison} Based on the discussions in Sec.~\ref{subsec:joint-ret} and Sec.~\ref{sec:answer-extraction}, we remark that end-to-end training using the two approaches has a complementary effect on the retrieval accuracy and answer extraction. While the \emph{Individual Top-k} approach helps to significantly improve the retrieval performance, the \emph{Joint Top-k} approach is more useful for answer extraction. \begin{figure}[!t] \centering \includegraphics[max width=0.5\textwidth, scale=0.95]{fig/joint_topk.pdf} \vspace{-8pt} \caption{Effect of increasing top-k documents on answer generation for \emph{Joint Top-k} approach.} \label{fig:joint-topk-varyk-nq} \vspace{-6pt} \end{figure}
{'timestamp': '2021-06-03T02:10:38', 'yymm': '2101', 'arxiv_id': '2101.00408', 'language': 'en', 'url': 'https://arxiv.org/abs/2101.00408'}
arxiv
\section{A two-phase algorithm for skill estimation} \label{sec:main-alg} \input{sections/performance} \input{sections/belief_update} \input{sections/init_distr} \input{sections/skill_drift} \input{sections/properties} \input{sections/experiments} \input{sections/conclusions} \section*{Acknowledgements} The authors are indebted to Daniel Sleator and Danica J. Sutherland for initial discussions that helped inspire this work, and to Nikita Gaevoy for the open-source improved TrueSkill upon which our implementation is based. Experiments in this paper were funded by a Google Cloud Research Grant. The second author is supported by a VMWare Fellowship and the Natural Sciences and Engineering Research Council of Canada. \looseness=-1 \section*{Appendix} \begingroup \def\ref{thm:uniq-max}{\ref{lem:decrease}} \begin{lemma} If $f_i$ is continuously differentiable and log-concave, then the functions $l_i,d_i,v_i$ are continuous, strictly decreasing, and \[l_i(p) < d_i(p) < v_i(p) \text{ for all }p.\] \end{lemma} \addtocounter{theorem}{-1} \endgroup \begin{proof} Continuity of $F_i,f_i,f'_i$ implies that of $l_i,d_i,v_i$. It's known~\cite{concave} that log-concavity of $f_i$ implies log-concavity of both $F_i$ and $1-F_i$. As a result, $l_i$, $d_i$, and $v_i$ are derivatives of strictly concave functions; therefore, they are strictly decreasing. In particular, each of \[v'_i(p) = \frac{f'_i(p)}{F_i(p)} - \frac{f_i(p)^2}{F_i(p)^2},\quad l'_i(p) = \frac{-f'_i(p)}{1-F_i(p)} - \frac{f_i(p)^2}{(1-F_i(p))^2},\] are negative for all $p$, so we conclude that \begin{align*} d_i(p) - v_i(p) = \frac{f'_i(p)}{f_i(p)} - \frac{f_i(p)}{F_i(p)} &= \frac{F_i(p)}{f_i(p)} v'_i(p) < 0, \\l_i(p) - d_i(p) = -\frac{f'_i(p)}{f_i(p)} -\frac{f_i(p)}{1-F_i(p)} &= \frac{1-F_i(p)}{f_i(p)} l'_i(p) < 0. \end{align*} \end{proof} \begingroup \def\ref{thm:uniq-max}{\ref{thm:uniq-max}} \begin{theorem} Suppose that for all $j$, $f_j$ is continuously differentiable and log-concave. Then the unique maximizer of $\Pr(P_i=p\mid E^L_i,E^W_i)$ is given by the unique zero of \[Q_i(p) = \sum_{j \succ i} l_j(p) + \sum_{j \sim i} d_j(p) + \sum_{j \prec i} v_j(p).\] \end{theorem} \addtocounter{theorem}{-1} \endgroup \begin{proof} First, we rank the players by their buckets according to $\floor{P_j/\epsilon}$, and take the limiting probabilities as $\epsilon\rightarrow 0$: \begin{align*} \Pr(\floor{\frac{P_j}\epsilon} > \floor{\frac{p}\epsilon}) &= \Pr(p_j \ge \epsilon\floor{\frac{p}\epsilon} + \epsilon) \\&= 1 - F_j(\epsilon\floor{\frac{p}\epsilon} + \epsilon) \rightarrow 1 - F_j(p), \\\Pr(\floor{\frac{P_j}\epsilon} < \floor{\frac{p}\epsilon}) &= \Pr(p_j < \epsilon\floor{\frac{p}\epsilon}) \\&= F_j(\epsilon\floor{\frac{p}\epsilon}) \rightarrow F_j(p), \\\frac 1\epsilon \Pr(\floor{\frac{P_j}\epsilon} = \floor{\frac{p}\epsilon}) &= \frac 1\epsilon \Pr(\epsilon\floor{\frac{p}\epsilon} \le P_j < \epsilon\floor{\frac{p}\epsilon} + \epsilon) \\&= \frac 1\epsilon\left( F_j(\epsilon\floor{\frac{p}\epsilon} + \epsilon) - F_j(\epsilon\floor{\frac{p}\epsilon}) \right) \rightarrow f_j(p). \end{align*} Let $L_{jp}^\epsilon$, $W_{jp}^\epsilon$, and $D_{jp}^\epsilon$ be shorthand for the events $\floor{\frac{P_j}\epsilon} > \floor{\frac{p}\epsilon}$, $\floor{\frac{P_j}\epsilon} < \floor{\frac{p}\epsilon}$, and $\floor{\frac{P_j}\epsilon} = \floor{\frac{p}\epsilon}$. respectively. These correspond to a player who performs at $p$ losing, winning, and drawing against $j$, respectively, when outcomes are determined by $\epsilon$-buckets. Then, \begin{align*} \Pr(E^W_i,E^L_i\mid P_i=p) &= \lim_{\epsilon\rightarrow 0} \prod_{j \succ i} \Pr(L_{jp}^\epsilon) \prod_{j \prec i} \Pr(W_{jp}^\epsilon) \prod_{j \sim i, j\ne i} \frac{\Pr(D_{jp}^\epsilon)}\epsilon \\&= \prod_{j \succ i} (1 - F_j(p)) \prod_{j \prec i} F_j(p) \prod_{j \sim i, j\ne i} f_j(p), \\\Pr(P_i=p \mid E^L_i,E^W_i) &\propto f_i(p) \Pr(E^L_i,E^W_i\mid P_i=p) \\&= \prod_{j \succ i} (1 - F_j(p)) \prod_{j \prec i} F_j(p) \prod_{j \sim i} f_j(p), \\\frac{\mathrm{d}}{\mathrm{d}p}\ln \Pr(P_i=p \mid E^L_i,& E^W_i) = \sum_{j \succ i} l_j(p) + \sum_{j \prec i} v_j(p) + \sum_{j \sim i} d_j(p) = Q_i(p). \end{align*} Since \Cref{lem:decrease} tells us that $Q_i$ is strictly decreasing, it only remains to show that it has a zero. If the zero exists, it must be unique and it will be the unique maximum of $\Pr(P_i=p \mid E^L_i,E^W_i)$. To start, we want to prove the existence of $p^*$ such that $Q_i(p^*) < 0$. Note that it's not possible to have $f'_j(p) \ge 0$ for all $p$, as in that case the density would integrate to either zero or infinity. Thus, for each $j$ such that $j\sim i$, we can choose $p_j$ such that $f'_j(p_j) < 0$, and so $d_j(p_j) < 0$. Let $\alpha = -\sum_{j\sim i} d_j(p_j) > 0$. Let $n = |\{j:\,j \prec i\}|$. For each $j$ such that $j \prec i$, since $\lim_{p\rightarrow\infty}v_j(p) = 0/1 = 0$, we can choose $p_j$ such that $v_j(p_j) < \alpha/n$. Let $p^* = \max_{j\preceq i} p_j$. Then, \[ \sum_{j \succ i} l_j(p^*) \le 0, \quad \sum_{j \sim i} d_j(p^*) \le -\alpha, \quad \sum_{j \prec i} v_j(p^*) < \alpha. \] Therefore, \begin{align*} Q_i(p^*) &= \sum_{j \succ i} l_j(p^*) + \sum_{j \sim i} d_j(p^*) + \sum_{j \prec i} v_j(p^*) \\&< 0 - \alpha + \alpha = 0. \end{align*} By a symmetric argument, there also exists some $q^*$ for which $Q_i(q^*) > 0$. By the intermediate value theorem with $Q_i$ continuous, there exists $p\in (q^*,p^*)$ such that $Q_i(p) = 0$, as desired. \looseness=-1 \end{proof} \subsection{Belief update} \label{sec:belief} Having estimated $P_{i,t}$ in the first phase, the second phase is rather simple. Ignoring normalizing constants, \Cref{eq:new-obj} tells us that the pdf of the skill posterior can be obtained as the pointwise product of the pdfs of the skill prior and the performance model. When both factors are differentiable and log-concave, then so is their product. Its maximum is the new rating $\mu_{i,t}$; let's see how to compute it for the same two specializations of our model. \paragraph{Gaussian skill prior and performance model} When the skill prior and performance model are Gaussian with known means and variances, multiplying their pdfs yields another known Gaussian. Hence, the posterior is compactly represented by its mean $\mu_{i,t}$, which coincides with the MAP and rating; and its variance $\sigma_{i,t}^2$, which is our \textbf{uncertainty} regarding the player's skill. \paragraph{Logistic performance model} When the performance model is non-Gaussian, the multiplication does not simplify so easily. By \Cref{eq:new-obj}, each round contributes an additional factor to the belief distribution. In general, we allow it to consist of a collection of simple log-concave factors, one for each round in which player $i$ has participated. Denote the participation history by \[{\mathcal{H}}_{i,t} := \{k\in\{1,\ldots,t\}:i\in\mathcal P_k\}.\] Since each player can be considered in isolation, we'll omit the subscript $i$. Specializing to the logistic setting, each $k\in{\mathcal{H}}_t$ contributes a logistic factor to the posterior, with mean $p_k$ and variance $\beta_k^2$. We still use a Gaussian initial prior, with mean and variance denoted by $p_0$ and $\beta_0^2$, respectively. Postponing the discussion of skill evolution to \Cref{sec:skill-drift}, for the moment we assume that $S_k=S_0$ for all $k$. The posterior pdf, up to normalization, is then \begin{align} &\pi_0(s) \prod_{k\in{\mathcal{H}}_t} \Pr(P_k=p_k \mid S_k=s) \nonumber \\&\propto \exp\left( -\frac{(s-p_0)^2}{2\beta_0^2} \right) \label{eq:posterior} \prod_{k\in{\mathcal{H}}_t} \sech^{2}\left( \frac\pi{\sqrt{12}} \frac{s-p_k} {\beta_k} \right). \end{align} Maximizing the posterior density amounts to minimizing its negative logarithm. Up to a constant offset, this is given by \begin{align*} L(s) &:= L_2\left(\frac{s-p_0}{\beta_0}\right) + \sum_{k\in{\mathcal{H}}_t} L_R\left(\frac{s-p_k}{\beta_k}\right), \\\text{where }L_2(x) &:= \frac 12 x^2\text{ and } L_R(x) := 2\ln\left(\cosh \frac{\pi x}{\sqrt{12}}\right). \end{align*} \begin{equation} \label{eq:loss} \text{Thus, }L'(s) = \frac{s-p_0}{\beta_0^2} + \sum_{k\in{\mathcal{H}}_t} \frac{\pi}{\beta_k\sqrt{3}} \tanh \frac{(s-p_k)\pi}{\beta_k\sqrt{12}}. \end{equation} $L'$ is continuous and strictly increasing in $s$, so its zero is unique: it is the MAP $\mu_t$. Similar to what we did in the first phase, we can solve for $\mu_t$ with either binary search or Newton's method. We pause to make an important observation. From \Cref{eq:loss}, the rating carries a rather intuitive interpretation: Gaussian factors in $L$ become $L_2$ penalty terms, whereas logistic factors take on a more interesting form as $L_R$ terms. From \Cref{fig:l2-lr-plot}, we see that the $L_R$ term behaves quadratically near the origin, but linearly at the extremities, effectively interpolating between $L_2$ and $L_1$ over a scale of magnitude $\beta_k$ It is well-known that minimizing a sum of $L_2$ terms pushes the argument towards a weighted mean, while minimizing a sum of $L_1$ terms pushes the argument towards a weighted median. With $L_R$ terms, the net effect is that $\mu_t$ acts like a robust average of the historical performances $p_k$. Specifically, one can check that \[\mu_t = \frac{\sum_k w_k p_k}{\sum_k w_k}, \text{ where } w_0 := \frac{1}{\beta_0^2} \text{ and }\] \begin{equation} \label{eq:average} w_k := \frac{\pi}{(\mu_t-p_k)\beta_k\sqrt{3}}\tanh\frac{(\mu_t-p_k)\pi}{\beta_k\sqrt{12}} \text{ for }k\in{\mathcal{H}}_t. \end{equation} $w_k$ is close to $1/\beta_k^2$ for typical performances, but can be up to $\pi^2/6$ times more as $|\mu_t-p_k| \rightarrow 0$, or vanish as $|\mu_t-p_k| \rightarrow\infty$. This feature is due to the thicker tails of the logistic distribution, as compared to the Gaussian, resulting in an algorithm that resists drastic rating changes in the presence of a few unusually good or bad performances. We'll formally state this \emph{robustness} property in \Cref{thm:robust}. \paragraph{Estimating skill uncertainty} While there is no easy way to compute the variance of a posterior in the form of \Cref{eq:posterior}, it will be useful to have some estimate $\sigma_t^2$ of uncertainty. There is a simple formula in the case where all factors are Gaussian. Since moment-matched logistic and normal distributions are relatively close (c.f. \Cref{fig:l2-lr-plot}), we apply the same formula: \begin{equation} \label{eq:variance} \frac{1}{\sigma_t^2} := \sum_{k\in\{0\}\cup{\mathcal{H}}_t}\frac{1}{\beta_k^2}. \end{equation} \section{Conclusions} This paper introduces the Elo-MMR rating system, which is in part a generalization of the two-player Glicko system, allowing an unbounded number of players. By developing a Bayesian model and taking the limit as the number of participants goes to infinity, we obtained simple, human-interpretable rating update formulas. Furthermore, we saw that the algorithm is asymptotically fast, embarrassingly parallel, robust to extreme performances, and satisfies the important \emph{aligned incentives} property. To our knowledge, our system is the first to rigorously prove all these properties in a setting with more than two individually ranked players. In terms of practical performance, we saw that it outperforms existing industry systems in both prediction accuracy and computation speed. This work can be extended in several directions. First, the choices we made in modeling ties, pseudodiffusions, and opponent subsampling are by no means the only possibilities consistent with our Bayesian model of skills and performances. Second, one may obtain better results by fitting the performance and skill evolution models to application-specific data. Another useful extension would be to team competitions. While it's no longer straightforward to infer precise estimates of an individual's performance, Elo-MM$\chi$ can simply be applied at the team level. To make this useful in settings where players may form new teams in each round, we must model teams in terms of their individual members. In the case where a team's performance is modeled as the sum of its members' independent Gaussian contributions, elementary facts about multivariate Gaussian distributions enable posterior skill inferences at the individual level. Generalizing this approach remains an open challenge. Over the past decade, online competition communities such as Codeforces have grown exponentially. As such, considerable work has gone into engineering scalable and reliable rating systems. Unfortunately, many of these systems have not been rigorously analyzed in the academic community. We hope that our paper and open-source release will open new explorations in this area. \section{Experiments} \label{sec:experiments} In this section, we compare various rating systems on real-world datasets, mined from several sources that will be described in \Cref{sec:datasets}. The metrics are runtime and predictive accuracy, as described in \Cref{sec:metrics}. We compare Elo-MM$\chi$ and Elo-MMR($\rho$) against the industry-tested rating systems of Codeforces and TopCoder. For a fairer comparison, we hand-coded efficient versions of all four algorithms in the safe subset of Rust, parellelized using the Rayon crate; as such, the Rust compiler verifies that they contain no data races~\cite{stone2017rayon}. Our implementation of Elo-MMR($\rho$) makes use of the optimizations in \Cref{sec:runtime}, bounding both the number of sampled opponents and the history length by 500. In addition, we test the improved TrueSkill algorithm of \cite{NS10}, basing our code on an open-source implementation of the same algorithm. The inherent seqentiality of its message-passing procedure prevented us from parallelizing it. \paragraph{Hyperparameter search} To ensure fair comparisons, we ran a separate grid search for each triple of algorithm, dataset, and metric, over all of the algorithm's hyperparameters. The hyperparameter set that performed best on the first 10\% of the dataset, was then used to test the algorithm on the remaining 90\% of the dataset. The experiments were run on a 2.0 GHz 24-core Skylake machine with 24 GB of memory. Implementations of all rating systems, hyperparameters, datasets, and additional processing used in our experiments can be found at \url{https://github.com/EbTech/EloR/}. \subsection{Datasets} \label{sec:datasets} \begin{table}[t] \begin{tabular}{l|l|l} \hline \textbf{Dataset} & \textbf{\# contests} & \textbf{avg. \# participants / contest} \\ \hline Codeforces & 1087 & 2999 \\ TopCoder & 2023 & 403 \\ Reddit & 1000 & 20 \\ Synthetic & 50 & 2500 \\ \hline \end{tabular} \caption{Summary of test datasets.} \label{tab:dataset-summary} \vspace{-1.2em} \end{table} Due to the scarcity of public domain datasets for rating systems, we mined three datasets to analyze the effectiveness of our system. The datasets were mined using data from each source website's inception up to October 12th, 2020. We also created a synthetic dataset to test our system's performance when the data generating process matches our theoretical model. Summary statistics of the datasets are presented in \Cref{tab:dataset-summary}. \paragraph{Codeforces contest history} This dataset contains the current entire history of rated contests ever run on CodeForces.com, the dominant platform for online programming competitions. The CodeForces platform has over 850K users, over 300K of whom are rated, and has hosted over 1000 contests to date. Each contest has a couple thousand competitors on average. A typical contest takes 2 to 3 hours and contains 5 to 8 problems. Players are ranked by total points, with more points typically awarded for tougher problems and for early solves. They may also attempt to ``hack'' one another's submissions for bonus points, identifying test cases that break their solutions. \looseness=-1 \paragraph{TopCoder contest history} This dataset contains the current entire history of algorithm contests ever run on the TopCoder.com. TopCoder is a predecessor to Codeforces, with over 1.4 million total users and a long history as a pioneering platform for programming contests. It hosts a variety of contest types, including over 2000 algorithm contests to date. The scoring system is similar to Codeforces, but its rounds are shorter: typically 75 minutes with 3 problems. \paragraph{SubRedditSimulator threads} This dataset contains data scraped from the current top-1000 most upvoted threads on the website \url{reddit.com/r/SubredditSimulator/}. Reddit is a social news aggregation website with over 300 million users. The site itself is broken down into sub-sites called subreddits. Users then post and comment to the subreddits, where the posts and comments receive votes from other users. In the subreddit SubredditSimulator, users are language generation bots trained on text from other subreddits. Automated posts are made by these bots to SubredditSimulator every 3 minutes, and real users of Reddit vote on the best bot. Each post (and its associated comments) can thus be interpreted as a round of competition between the bots who commented. \paragraph{Synthetic data} This dataset contains 10K players, with skills and performances generated according to the Gaussian generative model in \Cref{sec:bayes_model}. Players' initial skills are drawn i.i.d. with mean $1500$ and variance $300$. Players compete in all rounds, and are ranked according to independent performances with variance $200$. Between rounds, we add i.i.d. Gaussian increments with variance $35$ to each of their skills. \subsection{Evaluation metrics} \label{sec:metrics} To compare the different algorithms, we define two measures of predictive accuracy. Each metric will be defined on individual contestants in each round, and then averaged: \[\mathrm{\bf aggregate(metric)} := \frac{\sum_t \sum_{i\in\mathcal P_t} \mathrm{\bf metric}(i,t)}{\sum_t |\mathcal P_t|}.\] \paragraph{Pair inversion metric~\cite{HMG06}} Our first metric computes the fraction of opponents against whom our ratings predict the correct pairwise result, defined as the higher-rated player either winning or tying: \[\mathrm{\bf pair\_inversion}(i,t) := \frac{\text{\# correctly predicted matchups}}{|\mathcal P_t|-1} \times 100\%.\] This metric was used in the evaluation of TrueSkill~\cite{HMG06}. \paragraph{Rank deviation} Our second metric compares the rankings with the total ordering that would be obtained by sorting players according to their prior rating. The penalty is proportional to how much these ranks differ for player $i$: \[\mathrm{\bf rank\_deviation}(i,t) := \frac{|\text{actual\_rank} - \text{predicted\_rank}|}{|\mathcal P_t|-1} \times 100\%.\] In the event of ties, among the ranks within the tied range, we use the one that comes closest to the rating-based prediction. \subsection{Empirical results} \begin{table*} \begin{tabular}{l|ll|ll|ll|ll|ll} \hline \multirow{2}{*}{\textbf{Dataset}} & \multicolumn{2}{l|}{\textbf{Codeforces}} & \multicolumn{2}{l|}{\textbf{TopCoder}} & \multicolumn{2}{l|}{\textbf{TrueSkill}} & \multicolumn{2}{l|}{\textbf{Elo-MM$\boldsymbol\chi$}} & \multicolumn{2}{l}{\textbf{Elo-MMR($\boldsymbol\rho$)}} \\ \cline{2-11} & pair inv. & rank dev. & pair inv. & rank dev. & pair inv. & rank dev. & pair inv. & rank dev. & pair inv. & rank dev. \\ \hline Codeforces & 78.3\% & 14.9\% & 78.5\% & 15.1\% & 61.7\% & 25.4\% & 78.5\% & 14.8\% & {\bf 78.6}\% & {\bf 14.7}\% \\ TopCoder & 72.6\% & 18.5\% & 72.3\% & 18.7\% & 68.7\% & 20.9\% & 73.0\% & 18.3\% & {\bf 73.1}\% & {\bf 18.2}\% \\ Reddit & 61.5\% & 27.3\% & 61.4\% & 27.4\% & 61.5\% & {\bf 27.2}\% & 61.6\% & 27.3\% & {\bf 61.6\%} & 27.3\% \\ Synthetic & {\bf 81.7\%} & 12.9\% & {\bf 81.7}\% & {\bf 12.8}\% & 81.3\% & 13.1\% & {\bf 81.7}\% & {\bf 12.8}\% & {\bf 81.7\%} & {\bf 12.8\%} \\ \hline \end{tabular} \caption{Performance of each rating system on the pairwise inversion and rank deviation metrics. Bolded entries denote the best performances (highest pair inv. or lowest rank dev.) on each metric and dataset.} \label{tbl:metric-results} \vspace{-1.2em} \end{table*} \begin{table} \begin{tabular}{l|lllll} \hline \textbf{Dataset} & \textbf{CF} & \textbf{TC} & \textbf{TS} & \textbf{Elo-MM$\boldsymbol\chi$} & \textbf{Elo-MMR($\boldsymbol\rho$)} \\ \hline Codeforces & 212.9 & 72.5 & 67.2 & {\bf 31.4} & 35.4\\ TopCoder & 9.60 & {\bf 4.25} & 16.8 & 7.00 & 7.52\\ Reddit & 1.19 & 1.14 & {\bf 0.44} & 1.14 & 1.42 \\ Synthetic & 3.26 & 1.00 & 2.93 & {\bf 0.81} & 0.85 \\ \hline \end{tabular} \caption{Total compute time over entire dataset, in seconds.} \label{tbl:time-results} \vspace{-1.2em} \end{table} Recall that Elo-MM$\chi$ has a Gaussian performance model, matching the modeling assumptions of TopCoder and TrueSkill. Elo-MMR($\rho$), on the other hand, has a logistic performance model, matching the modeling assumptions of Codeforces and Glicko. While $\rho$ was included in the hyperparameter search, in practice we found that all values between $0$ and $1$ produce very similar results. To ensure that errors due to the unknown skills of new players don't dominate our metrics, we excluded players who had competed in less than 5 total contests. In most of the datasets, this reduced the performance of our method relative to the others, as our method seems to converge more accurately. Despite this, we see in \Cref{tbl:metric-results} that both versions of Elo-MMR outperform the other rating systems in both the pairwise inversion metric and the ranking deviation metric. \looseness=-1 We highlight a few key observations. First, significant performance gains are observed on the Codeforces and TopCoder datasets, despite these platforms' rating systems having been designed specifically for their needs. Our gains are smallest on the synthetic dataset, for which all algorithms perform similarly. This might be in part due to the close correspondence between the generative process and the assumptions of these rating systems. Furthermore, the synthetic players compete in all rounds, enabling the system to converge to near-optimal ratings for every player. Finally, the improved TrueSkill performed well below our expectations, despite our best efforts to improve it; we suspect that the message-passing algorithm breaks down in contests with a large number of distinct ranks. To our knowledge, we are the first to present experiments with TrueSkill on contests where the number of distinct ranks is in the hundreds or thousands. In preliminary experiments, TrueSkill and Elo-MMR score about equally when the number of ranks is less than about 60. Now, we turn our attention to \Cref{tbl:time-results}, which showcases the computational efficiency of Elo-MMR. On smaller datasets, it performs comparably to the Codeforces and TopCoder algorithms. However, the latter suffer from a quadratic time dependency on the number of contestants; as a result, Elo-MMR outperforms them by almost an order of magnitude on the larger Codeforces dataset. Finally, in comparisons between the two Elo-MMR variants, we note that while Elo-MMR($\rho$) is more accurate, Elo-MM$\chi$ is always faster. This has to do with the skill drift modeling described in \Cref{sec:skill-drift}, as every update in Elo-MMR($\rho$) must process $O(\log\frac 1\epsilon)$ terms of a player's competition history. \subsection{Initial Skill Distributions} \section{Introduction} Competitions, in the form of sports, games, and examinations, have been with us since antiquity. Many competitions grade performances along a numerical scale, such as a score on a test or a completion time in a race. In the case of a college admissions exam or a track race, scores are standardized so that a given score on two different occasions carries the same meaning. However, in events that feature novelty, subjectivity, or close interaction, standardization is difficult. The Spartan Races, completed by millions of runners, feature a variety of obstacles placed on hiking trails around the world~\cite{Spartan}. Rock climbing, a sport to be added to the 2020 Olympics, likewise has routes set specifically for each competition. DanceSport, gymnastics, and figure skating competitions have a panel of judges who rank contestants against one another; these subjective scores are known to be noisy~\cite{DanceSport}. Most board games feature considerable inter-player interaction. In all these cases, scores can only be used to compare and rank participants at the same event. Players, spectators, and contest organizers who are interested in comparing players' skill levels across different competitions will need to aggregate the entire history of such rankings. A strong player, then, is one who consistently wins against weaker players. To quantify skill, we need a \emph{rating system}. \looseness=-1 Good rating systems are difficult to create, as they must balance several mutually constraining objectives. First and foremost, the rating system must be accurate, in that ratings provide useful predictors of contest outcomes. Second, the ratings must be efficient to compute: in video game applications, rating systems are predominantly used for matchmaking in massively multiplayer online games (such as Halo, CounterStrike, League of Legends, etc.)~\cite{HMG06, MCZ18, Y14}. These games have hundreds of millions of players playing tens of millions of games per day, necessitating certain latency and memory requirements for the rating system~\cite{AL09}. Third, the rating system must align incentives. That is, players should not modify their performance to ``game'' the rating system. Rating systems that can be gamed often create disastrous consequences to player-base, more often than not leading to the loss of players from the game~\cite{pokemongo}. Finally, the ratings provided by the system must be human-interpretable: ratings are typically represented to players as a single number encapsulating their overall skill, and many players want to understand and predict how their performances affect their rating~\cite{G95}. Classically, rating systems were designed for two-player games. The famous Elo system~\cite{E61}, as well as its Bayesian successors Glicko and Glicko-2, have been widely applied to games such as Chess and Go~\cite{G95, G99, G12}. Both Glicko versions model each player's skill as a real random variable that evolves with time according to Brownian motion. Inference is done by entering these variables into the Bradley-Terry model, which predicts probabilities of game outcomes. Glicko-2 refines the Glicko system by adding a rating volatility parameter. Unfortunately, Glicko-2 is known to be flawed in practice, potentially incentivising players to lose. This was most notably exploited in the popular game of Pokemon Go~\cite{pokemongo}; see \Cref{sec:mono} for a discussion of this issue. The family of Elo-like methods just described only utilize the binary outcome of a match. In settings where a scoring system provides a more fine-grained measure of match performance, Kovalchik~\cite{K20} has shown variants of Elo that are able to take advantage of score information. For competitions consisting of several set tasks, such as academic olympiads, Fori{\v{s}}ek~\cite{forivsektheoretical} developed a model in which each task gives a different ``response'' to the player: the total response then predicts match outcomes. However, such systems are often highly application-dependent and hard to calibrate. \looseness=-1 Though Elo-like systems are widely used in two-player contests, one needn't look far to find competitions that involve much more than two players. Aside from the aforementioned sporting examples, there are video games such as CounterStrike and Halo, as well as academic olympiads: notably, programming contest platforms such as Codeforces, TopCoder, and Kaggle~\cite{Codeforces, TopCoder, Kaggle}. In these applications, the number of contestants can easily reach into the thousands. Some more recent works present interesting methods to deal with competitions between two teams \cite{HLW06, CJ16, LCFHH18, GFYLWTFC20}, but they do not present efficient extensions for settings in which players are sorted into more than two, let alone thousands, of distinct places In a many-player ranked competition, it is important to note that the pairwise match outcomes are not independent, as they would be in a series of 1v1 matches. Thus, TrueSkill~\cite{HMG06} and its variants~\cite{NS10, DHMG07, MCZ18} model a player's performance during each contest as a single random variable. The overall rankings are assumed to reveal the total order among these hidden performance variables, with various strategies used to model ties and teams. These TrueSkill algorithms are efficient in practice, successfully rating userbases that number well into the millions (the Halo series, for example, has over 60 million sales since 2001~\cite{Halo}). The main disadvantage of TrueSkill is its complexity: originally developed by Microsoft for the popular Halo video game, TrueSkill performs approximate belief propagation on a factor graph, which is iterated until convergence~\cite{HMG06}. Aside from being less human-interpretable, this complexity means that, to our knowledge, there are no proofs of key properties such as runtime and incentive alignment. Even when these properties are discussed~\cite{MCZ18}, no rigorous justification is provided. In addition, we are not aware of any work that extends TrueSkill to non-Gaussian performance models, which might be desirable to limit the influence of outlier performances (see \Cref{sec:robust}). It might be for these reasons that platforms such as Codeforces and TopCoder opted for their own custom rating systems. These systems are not published in academia and do not come with Bayesian justifications. However, they retain the formulaic simplicity of Elo and Glicko, extending them to settings with much more than two players. The Codeforces system includes ad hoc heuristics to distinguish top players, while curbing rampant inflation. TopCoder's formulas are more principled from a statistical perspective; however, it has a volatility parameter similar to Glicko-2, and hence suffers from similar exploits~\cite{forivsektheoretical}. Despite their flaws, these systems have been in place for over a decade, and have more recently gained adoption by additional platforms such as CodeChef and LeetCode~\cite{LeetCode, CodeChef}. \paragraph{Our contributions} In this paper, we describe the Elo-MMR rating system, obtained by a principled approximation of a Bayesian model very similar to TrueSkill. It is fast, embarrassingly parallel, and makes accurate predictions. Most interesting of all, its simplicity allows us to rigorously analyze its properties: the ``MMR'' in the name stands for ``Massive'', ``Monotonic'', and ``Robust''. ``Massive'' means that it supports any number of players with a runtime that scales linearly; ``monotonic'' means that it \emph{aligns incentives} so that a rating-maximizing player always wants to perform well; ``robust'' means that rating changes are bounded, with the bound being smaller for more consistent players than for volatile players. Robustness turns out to be a natural byproduct of accurately modeling performances with heavy-tailed distributions, such as the logistic. TrueSkill is believed to satisfy the first two properties, albeit without proof, but fails robustness. Codeforces only satisfies aligned incentives, and TopCoder only satisfies robustness. Experimentally, we show that Elo-MMR achieves state-of-the-art performance in terms of both prediction accuracy and runtime. In particular, we process the entire Codeforces database of over 300K rated users and 1000 contests in well under a minute, beating the existing Codeforces system by an order of magnitude while improving upon its accuracy. A difficulty we faced was the scarcity of efficient open-source rating system implementations. In an effort to aid researchers and practitioners alike, we provide open-source implementations of all rating systems, datasets, and additional processing used in our experiments at \url{https://github.com/EbTech/EloR/}. \paragraph{Organization} In \Cref{sec:bayes_model}, we formalize the details of our Bayesian model. We then show how to estimate player skill under this model in \Cref{sec:main-alg}, and develop some intuitions of the resulting formulas. As a further refinement, \Cref{sec:skill-drift} models skill evolutions from players training or atrophying between competitions. This modeling is quite tricky as we choose to retain players' momentum while ensuring it cannot be exploited for incentive-misaligned rating gains. \Cref{sec:properties} proves that the system as a whole satisfies several salient properties, the most critical of which is aligned incentives. Finally, we present experimental evaluations in \Cref{sec:experiments}. \section{A Bayesian Model for Massive Competitions} \label{sec:bayes_model} We now describe the setting formally, denoting random variables by capital letters. A series of competitive \textbf{rounds}, indexed by $t=1,2,3,\ldots$, take place sequentially in time. Each round has a set of participating \textbf{players} $\mathcal{P}_t$, which may in general overlap between rounds. A player's \textbf{skill} is likely to change with time, so we represent the skill of player $i$ at time $t$ by a real random variable $S_{i,t}$. In round $t$, each player $i\in \mathcal{P}_t$ competes at some \textbf{performance} level $P_{i,t}$, typically close to their current skill $S_{i,t}$. The deviations $\{P_{i,t}-S_{i,t}\}_{i\in\mathcal{P}_t}$ are assumed to be i.i.d. and independent of $\{S_{i,t}\}_{i\in\mathcal{P}_t}$. Performances are not observed directly; instead, a ranking gives the relative order among all performances $\{P_{i,t}\}_{i\in\mathcal{P}_t}$. In particular, ties are modelled to occur when performances are exactly equal, a zero-probability event when their distributions are continuous.\footnote{ The relevant limiting procedure is to treat performances within $\epsilon$-width buckets as ties, and letting $\epsilon\rightarrow 0$. This technicality appears in the proof of \Cref{thm:uniq-max}.} This ranking constitutes the observational \textbf{evidence} $E_t$ for our Bayesian updates. The rating system seeks to estimate the skill $S_{i,t}$ of every player at the present time $t$, given the historical round rankings $E_{\le t} := \{ E_1,\ldots,E_t \}$. We overload the notation $\Pr$ for both probabilities and probability densities: the latter interpretation applies to zero-probability events, such as in $\Pr(S_{i,t} = s)$. We also use colons as shorthand for collections of variables differing only in a subscript: for instance, $P_{:,t}:=\{P_{i,t}\}_{i\in\mathcal{P}_t}$. The joint distribution described by our Bayesian model factorizes as follows: \begin{align} &\Pr(S_{:,:}, P_{:,:}, E_:) \label{eq:model} \\&= \prod_i \Pr(S_{i,0}) \prod_{i,t} \Pr(S_{i,t}\mid S_{i,t-1}) \prod_{i,t} \Pr(P_{i,t}\mid S_{i,t}) \prod_t \Pr(E_t\mid P_{:,t}), \nonumber \end{align} \vspace{-1.5em} \begin{align*} \text{where } \Pr(S_{i,0}) &\text{ is the initial skill prior,} \\\Pr(S_{i,t}\mid S_{i,t-1}) &\text{ is the skill evolution model (\Cref{sec:skill-drift}),} \\\Pr(P_{i,t}\mid S_{i,t}) &\text{ is the performance model, and} \\\Pr(E_t\mid P_{:,t}) &\text{ is the evidence model.} \end{align*} For the first three factors, we will specify log-concave distributions (see \Cref{def:log-concave}). The evidence model, on the other hand, is a deterministic indicator. It equals one when $E_t$ is consistent with the relative ordering among $\{P_{i,t}\}_{i\in\mathcal{P}_t}$, and zero otherwise. Finally, our model assumes that the number of participants $|\mathcal{P}_t|$ is large. The main idea behind our algorithm is that, in sufficiently massive competitions, from the evidence $E_t$ we can infer very precise estimates for $\{P_{i,t}\}_{i\in\mathcal{P}_t}$. Hence, we can treat these performances as if they were observed directly. That is, suppose we have the skill prior at round $t$: \begin{equation} \label{eq:pi-s} \pi_{i,t}(s) := \Pr(S_{i,t} = s \mid P_{i,<t}). \end{equation} Now, we observe $E_t$. By \Cref{eq:model}, it is conditionally independent of $S_{i,t}$, given $P_{i,\le t}$. By the law of total probability, \begin{align*} &\Pr(S_{i,t}=s \mid P_{i,<t},\,E_t) \\&= \int \Pr(S_{i,t}=s \mid P_{i,<t},\,P_{i,t}=p) \Pr(P_{i,t}=p \mid P_{i,<t},\,E_t) \, \mathrm{d}p \\&\rightarrow \Pr(S_{i,t}=s \mid P_{i,\le t}) \quad\text{almost surely as }|\mathcal P_t|\rightarrow\infty. \end{align*} The integral is intractable in general, since the performance posterior $\Pr(P_{i,t}=p \mid P_{i,<t},\,E_t)$ depends not only on player $i$, but also on our belief regarding the skills of all $j\in\mathcal{P}_t$. However, in the limit of infinite participants, Doob's consistency theorem \cite{F63} implies that it concentrates at the true value $P_{i,t}$. Since our posteriors are continuous, the convergence holds for all $s$ simultaneously. Indeed, we don't even need the full evidence $E_t$. Let $E^L_{i,t} = \{j\in\mathcal{P}:P_{j,t}>P_{i,t}\}$ be the set of players against whom $i$ lost, and $E^W_{i,t} = \{j\in\mathcal{P}:P_{j,t}<P_{i,t}\}$ be the set of players against whom $i$ won. That is, we only see who wins, draws, and loses against $i$. $P_{i,t}$ remains identifiable using only $(E^L_{i,t}, E^W_{i,t})$, which will be more convenient for our purposes. Passing to the limit $|\mathcal{P}_t|\rightarrow\infty$ serves to justify some common simplifications made by algorithms such as TrueSkill: since conditioning on $P_{i,\le t}$ makes the skills of different players independent of one another, it becomes accurate to model them as such. In addition to simplifying derivations, this fact ensures that a player's posterior is unaffected by rounds in which they are not a participant, arguably a desirable property in its own right. Furthermore, $P_{i,\le t}$ being a sufficient statistic for skill prediction renders any additional information, such as domain-specific raw scores, redundant. Finally, a word on the rate of convergence. Suppose we want our estimate to be within $\epsilon$ of $P_{i,t}$, with probability at least $1-\delta$. By asymptotic normality of the posterior~\cite{F63}, it suffices to have $O(\frac 1{\epsilon^2}\sqrt{\log \frac 1\delta})$ participants. When the initial prior, performance model, and evolution model are all Gaussian, treating $P_{i,t}$ as certain is the \emph{only} simplifying approximation we will make; that is, in the limit $|\mathcal{P}_t|\rightarrow\infty$, our method performs \emph{exact} inference on \Cref{eq:model}. In the following sections, we focus some attention on generalizing the performance model to non-Gaussian log-concave families, parametrized by location and scale. We will use the logistic distribution as a running example and see that it induces robustness; however, our framework is agnostic to the specific distributions used The \textbf{rating} $\mu_{i,t}$ of player $i$ after round $t$ should be a statistic that summarizes their posterior distribution: we'll use the maximum a posteriori (MAP) estimate, obtained by setting $s$ to maximize the posterior $\Pr(S_{i,t}=s \mid P_{i,\le t})$. By Bayes' rule, \begin{equation} \label{eq:new-obj} \mu_{i,t} := \argmax_{s} \pi_{i,t}(s) \Pr(P_{i,t} \mid S_{i,t}=s). \end{equation} This objective suggests a two-phase algorithm to update each player $i\in\mathcal{P}_t$ at round $t$. In phase one, we estimate $P_{i,t}$ from $(E^L_{i,t}, E^W_{i,t})$. By Doob's consistency theorem, our estimate is extremely precise when $|\mathcal{P}_t|$ is large, so we assume it to be exact. In phase two, we update our posterior for $S_{i,t}$ and the rating $\mu_{i,t}$ according to \Cref{eq:new-obj}. We will occasionally make use of the \textbf{prior rating}, defined as \begin{equation*} \mu_{i,t}^\pi := \argmax_{s} \pi_{i,t}(s). \end{equation*} \subsection{Performance estimation} \label{sec:performance} In this section, we describe the first phase of Elo-MMR. For notational convenience, we assume all probability expressions to be conditioned on the \textbf{prior context} $P_{i,< t}$, and omit the subscript $t$. Our prior belief on each player's skill $S_i$ implies a prior distribution on $P_i$. Let's denote its probability density function (pdf) by \looseness=-1 \begin{equation} \label{eq:perf-prior} f_i(p) := \Pr(P_i = p) = \int \pi_i(s) \Pr(P_i = p \mid S_i=s) \,\mathrm{d}s, \end{equation} where $\pi_i(s)$ was defined in \Cref{eq:pi-s}. Let \[F_i(p) := \Pr(P_i\le p) = \int_{-\infty}^p f_i(x) \,\mathrm{d}x,\] be the corresponding cumulative distribution function (cdf). For the purpose of analysis, we'll also define the following ``loss'', ``draw'', and ``victory'' functions: \begin{align*} l_i(p) &:= \frac{\mathrm{d}}{\mathrm{d}p}\ln(1-F_i(p)) = \frac{-f_i(p)}{1 - F_i(p)}, \\d_i(p) &:= \frac{\mathrm{d}}{\mathrm{d}p}\ln f_i(p) = \frac{f'_i(p)}{f_i(p)}, \\v_i(p) &:= \frac{\mathrm{d}}{\mathrm{d}p}\ln F_i(p) = \frac{f_i(p)}{F_i(p)}. \end{align*} Evidently, $l_i(p) < 0 < v_i(p)$. Now we define what it means for the deviation $P_i - S_i$ to be log-concave. \begin{definition} \label{def:log-concave} An absolutely continuous random variable on a convex domain is \textbf{log-concave} if its probability density function $f$ is positive on its domain and satisfies \[f(\theta x + (1-\theta) y) > f(x)^\theta f(y)^{1-\theta},\;\forall\theta\in(0,1),x\neq y.\] \end{definition} We note that log-concave distributions appear widely, and include the Gaussian and logistic distributions used in Glicko, TrueSkill, and many others. We'll see inductively that our prior $\pi_i$ is log-concave at every round. Since log-concave densities are closed under convolution~\cite{concave}, the independent sum $P_i=S_i+(P_i-S_i)$ is also log-concave. The following lemma (proved in the appendix) makes log-concavity very convenient: \begin{lemma} \label{lem:decrease} If $f_i$ is continuously differentiable and log-concave, then the functions $l_i,d_i,v_i$ are continuous, strictly decreasing, and \[l_i(p) < d_i(p) < v_i(p) \text{ for all }p.\] \end{lemma} For the remainder of this section, we fix the analysis with respect to some player $i$. As argued in \Cref{sec:bayes_model}, $P_i$ concentrates very narrowly in the posterior. Hence, we can estimate $P_i$ by its MAP, choosing $p$ so as to maximize: \[\Pr(P_i=p\mid E^L_i,E^W_i) \propto f_i(p) \Pr(E^L_i,E^W_i\mid P_i=p).\] Define $j\succ i$, $j\prec i$, $j\sim i$ as shorthand for $j\in E^L_i$, $j\in E^W_i$, $j\in \mathcal P\setminus (E^L_i\cup E^W_i)$ (that is, $P_j>P_i$, $P_j<P_i$, $P_j=P_i$), respectively. The following theorem yields our MAP estimate: \begin{theorem} \label{thm:uniq-max} Suppose that for all $j$, $f_j$ is continuously differentiable and log-concave. Then the unique maximizer of $\Pr(P_i=p\mid E^L_i,E^W_i)$ is given by the unique zero of \[Q_i(p) := \sum_{j \succ i} l_j(p) + \sum_{j \sim i} d_j(p) + \sum_{j \prec i} v_j(p).\] \end{theorem} The proof is relegated to the appendix. Intuitively, we're saying that the performance is the balance point between appropriately weighted wins, draws, and losses. Let's look at two specializations of our general model, to serve as running examples in this paper. \paragraph{Gaussian performance model} If both $S_j$ and $P_j-S_j$ are assumed to be Gaussian with known means and variances, then their independent sum $P_j$ will also be a known Gaussian. It is analytic and log-concave, so \Cref{thm:uniq-max} applies. We substitute the well-known Gaussian pdf and cdf for $f_j$ and $F_j$, respectively. A simple binary search, or faster numerical techniques such as the Illinois algorithm or Newton's method, can be employed to solve for the maximizing $p$. \begin{figure} \centering \includegraphics[width=1.05\columnwidth]{l2-lr-plot.eps} \caption{$L_2$ versus $L_R$ for typical values (left). Gaussian versus logistic probability density functions (right).} \label{fig:l2-lr-plot} \end{figure} \paragraph{Logistic performance model} Now we assume the performance deviation $P_j-S_j$ has a logistic distribution with mean 0 and variance $\beta^2$. In general, the rating system administrator is free to set $\beta$ differently for each contest. Since shorter contests tend to be more variable, one reasonable choice might be to make $1/\beta^2$ proportional to the contest duration. Given the mean and variance of the skill prior, the independent sum $P_j = S_j + (P_j-S_j)$ would have the same mean, and a variance that's increased by $\beta^2$. Unfortunately, we'll see that the logistic performance model implies a form of skill prior from which it's tough to extract a mean and variance. Even if we could, the sum does not yield a simple distribution. For experienced players, we expect $S_j$ to contribute much less variance than $P_j-S_j$; thus, in our heuristic approximation, we take $P_j$ to have the same form of distribution as the latter. That is, we take $P_j$ to be logistic, centered at the prior rating $\mu^\pi_j = \argmax \pi_j$, with variance $\delta_j^2 = \sigma_j^2 + \beta^2$, where $\sigma_j$ will be given by \Cref{eq:variance}. This distribution is analytic and log-concave, so the same methods based on \Cref{thm:uniq-max} apply. Define the scale parameter $\bar\delta_j := \frac{\sqrt{3}}{\pi} \delta_j$. A logistic distribution with variance $\delta_j^2$ has cdf and pdf: \begin{align*} F_j(x) &= \frac { 1 } { 1 + e^{-(x-\mu^\pi_j)/\bar\delta_j} } = \frac 12 \left(1 + \tanh\frac{x-\mu^\pi_j}{2\bar\delta_j} \right), \\f_j(x) &= \frac { e^{(x-\mu^\pi_j)/\bar\delta_j} } { \bar\delta_j\left( 1 + e^{(x-\mu^\pi_j)/\bar\delta_j} \right)^2} = \frac { 1 } { 4\bar\delta_j} \sech^2\frac{x-\mu^\pi_j}{2\bar\delta_j}. \end{align*} The logistic distribution satisfies two very convenient relations: \begin{align*} F'_j(x) = f_j(x) &= F_j(x) (1 - F_j(x)) / \bar\delta_j, \\f'_j(x) &= f_j(x) (1 - 2F_j(x)) / \bar\delta_j, \end{align*} from which it follows that \[d_j(p) = \frac{1 - 2F_j(p)}{\bar\delta} = \frac{-F_j(p)}{\bar\delta} + \frac{1 - F_j(p)}{\bar\delta} = l_j(p) + v_j(p).\] In other words, a tie counts as the sum of a win and a loss. This can be compared to the approach (used in Elo, Glicko, TopCoder, and Codeforces) of treating each tie as half a win plus half a loss.\footnote{Elo-MMR, too, can be modified to split ties into half win plus half loss. It's easy to check that \Cref{lem:decrease} still holds if $d_j(p)$ is replaced by $w_l l_j(p) + w_v v_j(p)$ for some $w_l,w_v\in [0,1]$ with $|w_l-w_v|<1$. In particular, we can set $w_l=w_v=0.5$. The results in \Cref{sec:properties} won't be altered by this change.} Finally, putting everything together: \[Q_i(p) = \sum_{j \succeq i} l_j(p) + \sum_{j \preceq i} v_j(p) = \sum_{j \succeq i} \frac{-F_j(p)}{\bar\delta_j} + \sum_{j \preceq i} \frac{1 - F_j(p)}{\bar\delta_j}.\] Our estimate for $P_i$ is the zero of this expression. The terms on the right correspond to probabilities of winning and losing against each player $j$, weighted by $1/\bar\delta_j$. Accordingly, we can interpret $\sum_{j\in \mathcal{P}} (1-F_j(p))/\bar\delta_j$ as a weighted expected rank of a player whose performance is $p$. Similar to the performance computations in Codeforces and TopCoder, $P_i$ can thus be viewed as the performance level at which one's expected rank would equal $i$'s actual rank. \section{Theoretical Properties} \label{sec:properties} In this section, we see how the simplicity of the Elo-MMR formulas enables us to rigorously prove that the rating system aligns incentives, is robust, and is computationally efficient. \vspace{-.6em} \subsection{Aligned incentives} \label{sec:mono} To demonstrate the need for \emph{aligned incentives}, let's look at the consequences of violating this property in the TopCoder and Glicko-2 rating systems. These systems track a ``volatility'' for each player, which estimates the variance of their performances. A player whose recent performance history is more consistent would be assigned a lower volatility score, than one with wild swings in performance. The volatility acts as a multiplier on rating changes; thus, players with an extremely low or high performance will have their subsequent rating changes amplified. While it may seem like a good idea to boost changes for players whose ratings are poor predictors of their performance, this feature has an exploit. By intentionally performing at a weaker level, a player can amplify future increases to an extent that more than compensates for the immediate hit to their rating. A player may even ``farm'' volatility by alternating between very strong and very weak performances. After acquiring a sufficiently high volatility score, the strategic player exerts their honest maximum performance over a series of contests. The amplification eventually results in a rating that exceeds what would have been obtained via honest play. This type of exploit was discovered in both TopCoder competitions and the Pokemon Go video game~\cite{forivsektheoretical, pokemongo}. For a detailed example, see Table 5.3 of~\cite{forivsektheoretical}. Remarkably, Elo-MMR combines the best of both worlds: we'll see in \Cref{sec:robust} that, for $\rho\in (0,\infty)$, Elo-MMR($\rho$) also boosts changes to inconsistent players. And yet, as we'll prove in this section, no such strategic incentive exists in \emph{any} version of Elo-MMR. \looseness=-1 Recall that, for the purposes of the algorithm, the performance $p_i$ is defined to be the unique zero of the function $Q_i(p) := \sum_{j \succ i} l_j(p) + \sum_{j \sim i} d_j(p) + \sum_{j \prec i} v_j(p)$, whose terms $l_i,d_i,v_i$ are contributed by opponents against whom $i$ lost, drew, or won, respectively. Wins (losses) are always positive (negative) contributions to a player's performance score: \begin{lemma} \label{lem:mono-term} Adding a win term to $Q_i(\cdot)$, or replacing a tie term by a win term, always increases its zero. Conversely, adding a loss term, or replacing a tie term by a loss term, always decreases it. \end{lemma} \begin{proof} By \Cref{lem:decrease}, $Q_i(p)$ is decreasing in $p$. Thus, adding a positive term will increase its zero whereas adding a negative term will decrease it. The desired conclusion follows by noting that, for all $j$ and $p$, $v_j(p)$ and $v_j(p)-d_j(p)$ are positive, whereas $l_j(p)$ and $l_j(p)-d_j(p)$ are negative. \end{proof} While not needed for our main result, a similar argument shows that performance scores are monotonic across the round standings: \begin{theorem} If $i \succ j$ (that is, player $i$ beats $j$) in a given round, then player $i$ and $j$'s performance estimates satisfy $p_i > p_j$. \end{theorem} \begin{proof} If $i \succ j$ with $i,j$ adjacent in the rankings, then \[Q_i(p) - Q_j(p) = \sum_{k\sim i}(d_k(p) - l_k(p)) + \sum_{k\sim j}(v_k(p) - d_k(p)) > 0.\] for all $p$. Since $Q_i$ and $Q_j$ are decreasing functions, it follows that $p_i > p_j$. By induction, this result extends to the case where $i,j$ are not adjacent in the rankings. \end{proof} What matters for incentives is that performance scores be \emph{counterfactually} monotonic; meaning, if we were to alter the round standings, a strategic player will always prefer to place higher: \begin{lemma} \label{lem:mono-perf} In any given round, holding fixed the relative ranking of all players other than $i$ (and holding fixed all preceding rounds), the performance $p_i$ is a monotonic function of player i's prior rating and of player $i$'s rank in this round. \end{lemma} \begin{proof} Monotonicity in the rating follows directly from monotonicity of the self-tie term $d_i$ in $Q_i$. Since an upward shift in the rankings can only convert losses to ties to wins, monotonicity in contest rank follows from \Cref{lem:mono-term}. \end{proof} Having established the relationship between round rankings and performance scores, the next step is to prove that, even with hindsight, players will always prefer their performance scores to be as high as possible: \begin{lemma} \label{lem:mono-rate} Holding fixed the set of contest rounds in which a player has participated, their current rating is monotonic in each of their past performance scores. \end{lemma} \begin{proof} The player's rating is given by the zero of $L'$ in \Cref{eq:loss}. The pseudodiffusions of \Cref{sec:skill-drift} modify each of the $\beta_k$ in a manner that does not depend on any of the $p_k$, so they are fixed for our purposes. Hence, $L'$ is monotonically increasing in $s$ and decreasing in each of the $p_k$. Therefore, its zero is monotonically increasing in each of the $p_k$. This is almost what we wanted to prove, except that $p_0$ is not a performance. Nonetheless, it is a function of the performances: specifically, a weighted average of historical ratings which, using this same lemma as an inductive hypothesis, are themselves monotonic in past performances. By induction, the proof is complete. \end{proof} Finally, we conclude that the player's incentives are aligned with optimizing round rankings, or raw scores: \begin{theorem}[Aligned Incentives] \label{thm:mono} Holding fixed the set of contest rounds in which each player has participated, and the historical ratings and relative rankings of all players other than $i$, player $i$'s current rating is monotonic in each of their past rankings. \end{theorem} \begin{proof} Choose any contest round in player $i$'s history, and consider improving player $i$'s rank in that round while holding everything else fixed. It suffices to show that player $i$'s current rating would necessarily increase as a result. In the altered round, by \Cref{lem:mono-perf}, $p_i$ is increased; and by \Cref{lem:mono-rate}, player $i$'s post-round rating is increased. By \Cref{lem:mono-perf} again, this increases player $i$'s performance score in the following round. Proceeding inductively, we find that performance scores and ratings from this point onward are all increased. \end{proof} In the special cases of Elo-MM$\chi$ or Elo-MMR($\infty$), the rating system is ``memoryless'': the only data retained for each player are the current rating $\mu_{i,t}$ and uncertainty $\sigma_{i,t}$; detailed performance history is not saved. In this setting, we present a natural monotonicity theorem. A similar theorem was stated for the Codeforces system in \cite{Codeforces}, but no proofs were given. \begin{theorem}[Memoryless Monotonicity Theorem] In either the Elo-MM$\chi$ or Elo-MMR($\infty$) system, suppose $i$ and $j$ are two participants of round $t$. Suppose that the ratings and corresponding uncertainties satisfy $\mu_{i,t-1} \ge \mu_{j,t-1},\; \sigma_{i,t-1} = \sigma_{j,t-1}$. Then, $\sigma_{i,t} = \sigma_{j,t}$. Furthermore, if $i \succ j$ in round $t$, then $\mu_{i,t} > \mu_{j,t}$. On the other hand, if $j \succ i$ in round $t$, then $\mu_{j,t} - \mu_{j,t-1} > \mu_{i,t} - \mu_{i,t-1}$. \end{theorem} \begin{proof} The new contest round will add a rating perturbation with variance $\gamma_t^2$, followed by a new performance with variance $\beta_t^2$. As a result, \[\sigma_{i,t} = \left( \frac{1}{\sigma_{i,t-1}^2 + \gamma_t^2} + \frac{1}{\beta_t^2} \right)^{-\frac 12} = \left( \frac{1}{\sigma_{j,t-1}^2 + \gamma_t^2} + \frac{1}{\beta_t^2} \right)^{-\frac 12} = \sigma_{j,t}.\] The remaining conclusions are consequences of three properties: memorylessness, aligned incentives (\Cref{thm:mono}), and translation-invariance (ratings, skills, and performances are quantified on a common interval scale relative to one another). Since the Elo-MM$\chi$ or Elo-MMR($\infty$) systems are memoryless, we may replace the initial prior and performance histories of players with any alternate histories of our choosing, as long as our choice is compatible with their current rating and uncertainty. For example, both $i$ and $j$ can be considered to have participated in the same set of rounds, with $i$ always performing at $\mu_{i,t-1}$. and $j$ always performing at $\mu_{j,t-1}$. Round $t$ is unchanged. Suppose $i \succ j$. Since $i$'s historical performances are all equal or stronger than $j$'s, \Cref{thm:mono} implies $\mu_{i,t} > \mu_{j,t}$. Suppose $j \succ i$. By translation-invariance, if we shift each of $j$'s performances, up to round $t$ and including the initial prior, upward by $\mu_{i,t-1} - \mu_{j,t-1}$, the rating changes between rounds will be unaffected. Players $i$ and $j$ now have identical histories, except that we still have $j\succ i$ at round $t$. Therefore, $\mu_{j,t-1} = \mu_{i,t-1}$ and, by \Cref{thm:mono}, $\mu_{j,t} > \mu_{i,t}$. Subtracting the equation from the inequality proves the second conclusion. \end{proof} \subsection{Robust response} \label{sec:robust} Another desirable property in many settings is robustness: a player's rating should not change too much in response to any one contest, no matter how extreme their performance. The Codeforces and TrueSkill systems lack this property, allowing for unbounded rating changes. TopCoder achieves robustness by clamping any changes that exceed a cap, which is initially high for new players but decreases with experience. When $\rho>0$, Elo-MMR($\rho$) achieves robustness in a natural, smoother manner. It comes out of the interplay between Gaussian and logistic factors in the posterior; $\rho>0$ ensures that the Gaussian contribution doesn't vanish. Recall the notation used to describe the general posterior in \Cref{eq:posterior,eq:loss}, enhanced with the fractional multiplicities $\omega_k$ from \Cref{sec:pseudodiffusion}. \begin{theorem} \label{thm:robust} In the Elo-MMR($\rho$) rating system, let \[\Delta_{+} := \lim_{p_{t}\rightarrow+\infty} \mu_{t}-\mu_{t-1}, \quad \Delta_{-} := \lim_{p_{t}\rightarrow-\infty}\mu_{t-1}-\mu_{t}. \] Then, \[\frac{\pi}{\beta_t\sqrt 3} \left(\frac{1}{\beta_0^2} + \frac{\pi^2}{6}\sum_{k\in{\mathcal{H}}_{t-1}}\frac{\omega_k}{\beta_k^2} \right)^{-1} \le \Delta_{\pm} \le \frac{\pi\beta_0^2}{\beta_t\sqrt 3}.\] \end{theorem} \begin{proof} Using the fact that $0 < \frac{d}{dx}\tanh(x) \le 1$, differentiating \Cref{eq:loss} yields \[\frac{1}{\beta_0^2} \le L''(s) \le \frac{1}{\beta_0^2} + \frac{\pi^2}{6}\sum_{k\in{\mathcal{H}}_{t-1}}\frac{\omega_k}{\beta_k^2}.\] For every $s\in\mathbb R$, in the limit as $p_t\rightarrow\pm\infty$, the new term corresponding to the performance at round $t$ will increase $L'(s)$ by $\mp\frac{\pi}{\beta_t\sqrt 3}$. Since $\mu_{t-1}$ was a zero of $L'$ without this new term, we now have $L'(\mu_{t-1}) \rightarrow \mp\frac{\pi}{\beta_t\sqrt 3}.$ Dividing by the former inequalities yields the desired result. \end{proof} The proof reveals that the magnitude of $\Delta_{\pm}$ depends inversely on that of $L''$ in the vicinity of the current rating, which in turn is related to the derivative of the $\tanh$ terms. If a player's performances vary wildly, then most of the $\tanh$ terms will be in their tails, which contribute small derivatives, enabling larger rating changes. Conversely, the $\tanh$ terms of a player with a very consistent rating history will contribute large derivatives, so the bound on their rating change will be small. Thus, Elo-MMR($\rho$) naturally caps the rating change of all players, and puts a smaller cap on the rating change of consistent players. The cap will increase after an extreme performance, providing a similar ``momentum'' to the TopCoder and Glicko-2 systems, but without sacrificing aligned incentives (\Cref{thm:mono}). By comparing against \Cref{eq:variance}, we see that the lower bound in \Cref{thm:robust} is on the order of $\sigma_t^2/\beta_t$, while the upper bound is on the order of $\beta_0^2/\beta_t$. As a result, the momentum effect is more pronounced when $\beta_0$ is much larger than $\sigma_t$. Since the decay step increases $\beta_0$ while the transfer step decreases it, this occurs when the transfer rate $\rho$ is comparatively small. Thus, $\rho$ can be chosen in inverse proportion to the desired strength of momentum. \subsection{Runtime analysis and optimizations} \label{sec:runtime} Let's look at the computation time needed to process a round with participant set $\mathcal P$, where we again omit the round subscript. Each player $i$ has a participation history ${\mathcal{H}}_i$. Estimating $P_i$ entails finding the zero of a monotonic function with $O(|\mathcal P|)$ terms, and then obtaining the rating $\mu_i$ entails finding the zero of another monotonic function with $O(|{\mathcal{H}}_i|)$ terms. Using the Illinois or Newton methods, solving these equations to precision $\epsilon$ takes $O(\log\log\frac 1\epsilon)$ iterations. As a result, the total runtime needed to process one round of competition is \[O\left(\sum_{i\in\mathcal P}(|\mathcal P| + |{\mathcal{H}}_i|) \log\log\frac 1\epsilon\right).\] This complexity is more than adequate for Codeforces-style competitions with thousands of contestants and history lengths up to a few hundred. Indeed, we were able to process the entire history of Codeforces on a small laptop in less than half an hour. Nonetheless, it may be cost-prohibitive in truly massive settings, where $|\mathcal P|$ or $|{\mathcal{H}}_i|$ number in the millions. Fortunately, it turns out that both functions may be compressed down to a bounded number of terms, with negligible loss of precision. \paragraph{Adaptive subsampling} In \Cref{sec:bayes_model}, we used Doob's consistency theorem to argue that our estimate for $P_i$ is consistent. Specifically, we saw that $O(1/\epsilon^2)$ opponents are needed to get the typical error below $\epsilon$. Thus, we can subsample the set of opponents to include in the estimation, omitting the rest. Random sampling is one approach. A more efficient approach chooses a fixed number of opponents whose ratings are closest to that of player $i$, as these are more likely to provide informative match-ups. On the other hand, if the setting requires aligned incentives to hold exactly, then one must avoid choosing different opponents for each player. \paragraph{History compression} Similarly, it's possible to bound the number of stored factors in the posterior. Our skill-evolution algorithm decays the weights of old performances at an exponential rate. Thus, the contributions of all but the most recent $O(\log\frac 1\epsilon)$ terms are negligible. Rather than erase the older logistic terms outright, we recommend replacing them with moment-matched Gaussian terms, similar to the transfers in \Cref{sec:skill-drift} with $\kappa=0$. Since Gaussians compose easily, a single term can then summarize an arbitrarily long prefix of the history. Substituting $1/\epsilon^2$ and $\log\frac 1\epsilon$ for $|\mathcal{P}|$ and $|{\mathcal{H}}_i|$, respectively, the runtime of Elo-MMR with both optimizations becomes \[O\left(\frac {|\mathcal P|}{\epsilon^2} \log\log\frac 1\epsilon\right).\] Finally, we note that the algorithm is embarrassingly parallel, with each player able to solve its equations independently. The threads can read the same global data structures, so each additional thread only contributes $O(1)$ memory overhead. \section{Skill evolution over time} \label{sec:skill-drift} Factors such as training and resting will change a player's skill over time. If we model skill as a static variable, our system will eventually grow so confident in its estimate that it will refuse to admit substantial changes. To remedy this, we introduce a skill evolution model, so that in general $S_t \neq S_{t'}$ for $t \neq t'$. Now rather than simply being equal to the previous round's posterior, the skill prior at round $t$ is given by \begin{equation} \label{eq:drift} \pi_t(s) = \int \Pr(S_t = s \mid S_{t-1} = x) \Pr(S_{t-1} = x \mid P_{<t}) \,\mathrm{d}x. \end{equation} The factors in the integrand are the skill evolution model and the previous round's posterior, respectively. Following other Bayesian rating systems (e.g., Glicko, Glicko-2, and TrueSkill~\cite{G99, G12, HMG06}), we model the skill diffusions $S_t-S_{t-1}$ as independent zero-mean Gaussians. That is, $\Pr(S_t \mid S_{t-1}=x)$ is a Gaussian with mean $x$ and some variance $\gamma_t^2$. The Glicko system sets $\gamma_t^2$ proportionally to the time elapsed since the last update, corresponding to a continuous Brownian motion. Codeforces and TopCoder simply set $\gamma_t$ to a constant when a player participates, and zero otherwise, corresponding to changes that are in proportion to how often the player competes. Now we are ready to complete the two specializations of our rating system. \paragraph{Gaussian skill prior and performance model} If both the prior and performance distributions at round $t-1$ are Gaussian, then the posterior is also Gaussian. Adding an independent Gaussian diffusion to our posterior on $S_{t-1}$ yields a Gaussian prior on $S_t$. By induction, the skill belief distribution forever remains Gaussian. This Gaussian specialization of the Elo-MMR framework lacks the R for robustness (see \Cref{thm:robust}), so we call it Elo-MM$\chi$. \paragraph{Logistic performance model} After a player's first contest round, the posterior in \Cref{eq:posterior} becomes non-Gaussian, rendering the integral in \Cref{eq:drift} intractable. A very simple approach would be to replace the full posterior in \Cref{eq:posterior} by a Gaussian approximation with mean $\mu_t$ (equal to the posterior MAP) and variance $\sigma_t^2$ (given by \Cref{eq:variance}). As in the previous case, applying diffusions in the Gaussian setting is a simple matter of adding means and variances. With this approximation, no memory is kept of the individual performances $P_t$. Priors are simply Gaussian, while posterior densities are the product of two factors: the Gaussian prior, and a logistic factor corresponding to the latest performance. To ensure robustness (see \Cref{sec:robust}), $\mu_t$ is computed as the argmax of this posterior \emph{before} replacement by its Gaussian approximation. We call the rating system that takes this approach Elo-MMR($\infty$). As the name implies, it turns out to be a special case of Elo-MMR($\rho$). In the general setting with $\rho \in [0,\infty)$, we keep the full posterior from \Cref{eq:posterior}. Since we cannot tractably compute the effect of a Gaussian diffusion, we seek a heuristic derivation of the next round's prior, retaining a form similar to \Cref{eq:posterior} while satisfying many of the same properties as the intended diffusion. \subsection{Desirable properties of a ``pseudodiffusion''} \label{sec:desirable-props} We begin by listing some properties that our skill evolution algorithm, henceforth called a ``pseudodiffusion'', should satisfy. The first two properties are natural: \begin{itemize}[leftmargin=*] \item \emph{Aligned incentives.} First and foremost, the pseudodiffusion must not break the aligned incentives property of our rating system. That is, a rating-maximizing player should never be motivated to lose on purpose (\Cref{thm:mono}). \item \emph{Rating preservation.} The pseudodiffusion must not alter the $\argmax$ of the belief density. That is, the rating of a player should not change: $\mu^\pi_t = \mu_{t-1}$. \end{itemize} In addition, we borrow four properties of Gaussian diffusions: \begin{itemize}[leftmargin=*] \item \emph{Correct magnitude.} Pseudodiffusion with parameter $\gamma^2$ must increase the skill uncertainty, as measured by \Cref{eq:variance}, by $\gamma^2$. \item \emph{Composability.} Two pseudodiffusions applied in sequence, first with parameter $\gamma_1^2$ and then with $\gamma_2^2$, must have the same effect as a single pseudodiffusion with parameter $\gamma_1^2 + \gamma_2^2$. \item \emph{Zero diffusion.} In the limit as $\gamma \rightarrow 0$, the effect of pseudodiffusion must vanish, i.e., not alter the belief distribution. \item \emph{Zero uncertainty.} In the limit as $\sigma_{t-1}\rightarrow 0$ (i.e., when the previous rating $\mu_{t-1}$ is a perfect estimate of $S_{t-1}$), our belief on $S_t$ must become Gaussian with mean $\mu_{t-1}$ and variance $\gamma^2$. Finer-grained information regarding the prior history $P_{\le t}$ must be erased. \end{itemize} In particular, Elo-MMR($\infty$) fails the \emph{zero diffusion} property because it simplifies the belief distribution, even when $\gamma=0$. In the proof of \Cref{thm:diffuse-prop}, we'll see that Elo-MMR($0$) fails the \emph{zero uncertainty} property. Thus, it is in fact necessary to have $\rho$ strictly positive and finite. In \Cref{sec:robust}, we'll come to interpret $\rho$ as a kind of inverse momentum. \subsection{A heuristic pseudodiffusion algorithm} \label{sec:pseudodiffusion} Each factor in the posterior (see \Cref{eq:posterior}) has a parameter $\beta_k$. Define a factor's \textbf{weight} to be $w_k := 1/\beta_k^2$, which by \Cref{eq:variance} contributes to the \textbf{total weight} $\sum_k w_k=1/\sigma_t^2$. Here, unlike in \Cref{eq:average}, $w_k$ does not depend on $|\mu_t-p_k|$. The approximation step of Elo-MMR($\infty$) replaces all the logistic factors by a single Gaussian whose variance is chosen to ensure that the total weight is preserved. In addition, its mean is chosen to preserve the player's rating, given by the unique zero of \Cref{eq:loss}. Finally, the diffusion step of Elo-MMR($\infty$) increases the Gaussian's variance, and hence the player's skill uncertainty, by $\gamma_t^2$; this corresponds to a decay in the weight. To generalize the idea, we interleave the two steps in a continuous manner. The approximation step becomes a \textbf{transfer step}: rather than replace the logistic factors outright, we take away the same fraction from each of their weights, and place the sum of removed weights onto a new Gaussian factor. The diffusion step becomes a \textbf{decay step}, reducing each factor's weight by the same fraction, chosen such that the overall uncertainty is increased by $\gamma_t^2$. To make the idea precise, we generalize the posterior from \Cref{eq:posterior} with fractional \textbf{multiplicities} $\omega_k$, initially set to $1$ for each $k\in\{0\}\cup{\mathcal{H}}_t$. The $k$'th factor is raised to the power $\omega_k$; in \Cref{eq:loss,eq:variance}, the corresponding term is multiplied by $\omega_k$. In other words, the latter equation is replaced by \[\frac{1}{\sigma_t^2} := \sum_{k\in\{0\}\cup{\mathcal{H}}_t}w_k,\text{ where }w_k := \frac{\omega_k}{\beta_k^2}.\] For $\rho\in [0,\infty]$, the Elo-MMR($\rho$) algorithm continuously and simultaneously performs transfer and decay, with transfer proceeding at $\rho$ times the rate of decay. Holding $\beta_k$ fixed, changes to $\omega_k$ can be described in terms of changes to $w_k$: \begin{align*} \dot w_0 &= -r(t)w_0 + \rho r(t) \sum_{k\in{\mathcal{H}}_t} w_k, \\\dot w_k &= -(1+\rho)r(t)w_k \quad\text{for }k\in{\mathcal{H}}_t, \end{align*} where the arbitrary decay rate $r(t)$ can be eliminated by a change of variable $\mathrm{d}\tau = r(t)\mathrm{d}t$. After some time $\Delta\tau$, the total weight will have decayed by a factor $\kappa := e^{-\Delta\tau}$, resulting in the new weights: \begin{align*} w_0^{new} &= \kappa w_0 + \left(\kappa-\kappa^{1+\rho}\right)\sum_{k\in{\mathcal{H}}_t} w_k, \\w_k^{new} &= \kappa^{1+\rho}w_k \quad\text{for }k\in{\mathcal{H}}_t. \end{align*} In order for the uncertainty to increase from $\sigma_{t-1}^2$ to $\sigma_{t-1}^2+\gamma_t^2$, we must solve $\kappa/\sigma_{t-1}^2 = 1/(\sigma_{t-1}^2+\gamma_t^2)$ for the decay factor: \setlength{\floatsep}{0pt} \setlength{\textfloatsep}{1em} \begin{algorithm}[t] \caption{Elo-MMR($\rho,\beta, \gamma$)} \label{alg:main} \begin{algorithmic} \FORALL{rounds $t$} \FORALL{players $i\in\mathcal P_t$ in parallel} \IF{$i$ has never competed before} \STATE {$\mu_i, \sigma_i \gets \mu_{newcomer}, \sigma_{newcomer}$} \STATE {$p_i, w_i \gets [\mu_i], [1/\sigma_i^2]$} \ENDIF \STATE diffuse($i,\gamma,\rho$) \STATE $\mu^\pi_i, \delta_i \gets \mu_i,\sqrt{\sigma_i^2 + \beta^2}$ \ENDFOR \FORALL{$i\in\mathcal P_t$ in parallel} \STATE update($i,E_t,\beta$) \ENDFOR \ENDFOR \end{algorithmic} \end{algorithm} \begin{algorithm}[t] \caption{diffuse($i,\gamma,\rho$)} \label{alg:diffuse} \begin{algorithmic} \STATE $\kappa \gets (1+\gamma^2/\sigma_i^2)^{-1}$ \STATE $w_G, w_L \gets \kappa^\rho w_{i,0}, (1-\kappa^\rho) \sum_{k} w_{i,k}$ \STATE $p_{i,0} \gets (w_G p_{i,0} + w_L \mu_i) / (w_G+w_L)$ \STATE $w_{i,0} \gets \kappa (w_G+w_L)$ \FORALL{$k\ne 0$} \STATE $w_{i,k} \gets \kappa^{1+\rho}w_{i,k}$ \ENDFOR \STATE $\sigma_i \gets \sigma_i / \sqrt\kappa$ \end{algorithmic} \end{algorithm} \begin{algorithm}[t] \caption{update($i,E,\beta$)} \label{alg:update} \begin{algorithmic} \STATE $p \gets \mathrm{zero}\left(\sum_{j\preceq i}\frac{1}{\delta_j}\left( \tanh\frac {x - \mu^\pi_j} {2\bar\delta_j} - 1 \right) + \sum_{j\succeq i}\frac{1}{\delta_j}\left( \tanh\frac {x - \mu^\pi_j} {2\bar\delta_j} + 1 \right)\right)$ \STATE $p_i$.push($p$) \STATE $w_i$.push($1/\beta^2$) \STATE $\mu_i \gets \mathrm{zero}\left(w_{i,0}(x-p_{i,0}) + \sum_{k\ne 0} \frac{w_{i,k}\beta^2}{\bar\beta} \tanh \frac {x-p_{i,k}} {2\bar\beta}\right)$ \end{algorithmic} \end{algorithm} \[\kappa = \left(1 + \frac{\gamma_t^2}{\sigma_{t-1}^2}\right)^{-1}.\] In order for this operation to preserve ratings, the transferred weight must be centered at $\mu_{t-1}$; see \Cref{alg:diffuse} for details. \Cref{alg:main} details the full Elo-MMR($\rho$) rating system. The main loop runs whenever a round of competition takes place. First, new players are initialized with a Gaussian prior. Then, changes in player skill are modeled by \Cref{alg:diffuse}. Given the round rankings $E_t$, the first phase of \Cref{alg:update} solves an equation to estimate $P_t$. Finally, the second phase solves another equation for the rating $\mu_t$. The hyperparameters $\rho,\beta,\gamma$ are domain-dependent, and can be set by standard hyperparameter search techniques. For convenience, we assume $\beta$ and $\gamma$ are fixed and use the shorthand $\bar\beta_k := \frac{\sqrt{3}}{\pi} \beta_k$. \begin{theorem} \label{thm:diffuse-prop} \Cref{alg:diffuse} with $\rho\in(0,\infty)$ meets all of the properties listed in \Cref{sec:desirable-props}. \end{theorem} \begin{proof} We go through each of the six properties in order. \begin{itemize}[leftmargin=*] \item \emph{Aligned incentives.} This property will be stated in \Cref{thm:mono}. To ensure that its proof carries through, the relevant facts to note here are that the pseudodiffusion algorithm ignores the performances $p_k$, and centers the transferred Gaussian weight at the rating $\mu_{t-1}$, which is trivially monotonic in $\mu_{t-1}$. \item \emph{Rating preservation.} Recall that the rating is the unique zero of $L'$, defined in \Cref{eq:loss}. To see that this zero is preserved, note that the decay and transfer operations multiply $L'$ by constants ($\kappa$ and $\kappa^\rho$, respectively), before adding the new Gaussian term, whose contribution to $L'$ is zero at its center. \item \emph{Correct magnitude.} Follows from our derivation for $\kappa$. \item \emph{Composability.} Follows from \emph{correct magnitude} and the fact that every pseudodiffusion follows the same differential equations. \item \emph{Zero diffusion.} As $\gamma\rightarrow 0$, $\kappa\rightarrow 1$. Provided that $\rho<\infty$, we also have $\kappa^\rho\rightarrow 1$. Hence, for all $k\in\{0\}\cup{\mathcal{H}}_t$, $w_k^{new} \rightarrow w_k$. \item \emph{Zero uncertainty.} As $\sigma_{t-1}\rightarrow 0$, $\kappa\rightarrow 0$. The total weight decays from $1/\sigma_{t-1}^2$ to $\gamma^2$. Provided that $\rho > 0$, we also have $\kappa^\rho\rightarrow 0$, so these weights transfer in their entirety, leaving behind a Gaussian with mean $\mu_{t-1}$, variance $\gamma^2$, and no additional history. \qedhere \end{itemize} \end{proof}
{'timestamp': '2021-01-05T02:14:31', 'yymm': '2101', 'arxiv_id': '2101.00400', 'language': 'en', 'url': 'https://arxiv.org/abs/2101.00400'}
arxiv
\section{Introduction} \emph{Geometric network design} is a common and well-studied task in computational geometry and combinatorial optimization~\cite{MM17,Har-Peled11,Eppstein00,Mitchell04}. In this family of problems, we are given a set $\mathcal{P}$ of points in general position, and our task is to connect $\mathcal{P}$ into a (geometric) graph that has certain favorable properties. Not surprisingly, this general question has captivated the attention of researchers for a long time, and we can find a countless number of variants, depending on which restrictions we put on the graph that connects $\mathcal{P}$ and which criteria of this graph we would like to optimize. Typical graph classes of interest include matchings, paths, cycles, trees, or general \emph{plane} (\emph{noncrossing}) graphs, i.e., graphs, whose straight-line embedding on $\mathcal{P}$ does not contain any edge crossings. Typical quality criteria include the total edge length~\cite{MulzerR08,Arora98,Mitchell99,deBergChVKOv08}, the maximum length (bottleneck) edge~\cite{EfratIK01,Biniaz20}, the maximum degree~\cite{Chan04,AroraC04,PapadimitriouV84,FranckeH09}, the dilation~\cite{mulzer04minimum,NarasimhanSm07,Eppstein00}, or the stabbing number~\cite{MulzerOb20,Welzl92} of the graph. \ Many famous problems from computational geometry fall into this general setting. For example, if our goal is to minimize the total edge length, while restricting ourselves to paths, trees, or triangulations, respectively, we are faced with the venerable problems of finding an optimum TSP tour~\cite{Har-Peled11}, a Euclidean minimum spanning tree~\cite{deBergChVKOv08}, or a minimum weight triangulation~\cite{MulzerR08} for $\mathcal{P}$. These three examples also illustrate the wide variety of complexity aspects that we may encounter in geometric design problems: the Euclidean TSP problem is known to be NP-hard~\cite{Papadimitriou77}, but it admits a PTAS~\cite{Arora98,Mitchell99}. On the other hand, it is possible to find a Euclidean minimum spanning tree for $\mathcal{P}$ in polynomial time~\cite{deBergChVKOv08} (even though, curiously, the associated decision problem is not known to be solvable by a polynomial-time Turing machine). The minimum weight triangulation problem is also known to be NP-hard~\cite{MulzerR08}, but the existence of a PTAS is still open; however, a QPTAS is known~\cite{RemyS09}. In this work, we are interested in the interaction of two specific requirements for a geometric design problem, namely the two desires of obtaining a plane graph and of optimizing the total edge length. For the case that we want to \emph{minimize} the total edge length of the resulting graph, these two goals are often in perfect harmony: the shortest Euclidean TSP tour and the shortest Euclidean minimum spanning tree are automatically plane, as can be seem by a simple application of the triangle inequality. In contrast, if our goal is to \emph{maximize} the total edge length, while obtaining a plane graph, much less is known. This family of problems was studied by Alon, Rajagopalan, and Suri~\cite{AlonRS95}, who considered the problems of computing a longest plane matching, a longest plane Hamiltonian path, and a longest plane spanning tree for a planar point set $\mathcal{P}$ in general position. Alon et al.~\cite{AlonRS95} conjectured that these three problems are all NP-hard, but as far as we know, this is still open. The situation is similar for the problem of finding a \emph{maximum weight triangulation} for $\mathcal{P}$: here, we have neither an NP-hardness proof, nor a polynomial time algorithm~\cite{ChinQW04}. If we omit the planarity condition, then the problem of finding a longest Hamiltonian path (the \emph{geometric maximum TSP problem}) is known to be NP-hard in dimension three and above, while the two-dimensional case remains open~\cite{BarvinokFJTWW03}. On the other hand, we can find a longest (typically not plane) tree on $\mathcal{P}$ in polynomial time, using classic greedy algorithms~\cite{CLRS}. \subparagraph*{Longest plane spanning trees.} We focus on the specific problem of finding a longest plane (i.e. noncrossing) tree for a given set $\mathcal{P}$ of $n\ge 3$ points in the plane in general position (that is, no three points in $\mathcal{P}$ are collinear). Such a tree is necessarily spanning. The general position assumption was also used in previous work on this problem~\cite{AlonRS95,DBLP:journals/dcg/DumitrescuT10}. Without it, one should specify whether overlapping edges are allowed, an additional complication that we would like to avoid. If $\mathcal{P}$ is in convex position, then the longest plane tree for $\mathcal{P}$ can be found in polynomial time on a real RAM, by adapting standard dynamic programming methods for plane structures on convex point sets~\cite{Gilbert79,Klincsek80}. On the other hand, for an arbitrary point set $\mathcal{P}$, the problem is conjectured---but not known---to be NP-hard~\cite{AlonRS95}. For this reason, past research has focused on designing polynomial-time approximation algorithms. Typically, these algorithms proceed by constructing several ``simple'' spanning trees for $\mathcal{P}$ of small diameter and by arguing that at least one of these trees is sufficiently long. One of the first such results is due to Alon et al.~\cite{AlonRS95}. They showed that a longest star (a plane tree with diameter two) on $\mathcal{P}$ yields a $0.5$-approximation for the longest (not necessarily plane) spanning tree of $\mathcal{P}$. Alon et al.~\cite{AlonRS95} also argued that this bound is essentially tight for point sets that consist of two large clusters far away from each other. Dumitrescu and T\' oth~\cite{DBLP:journals/dcg/DumitrescuT10} refined this algorithm by adding two additional families of candidate trees, now with diameter four. They showed that at least one member of this extended range of candidates constitutes a $0.502$-approximation, which was further improved to $0.503$ by Biniaz et al.~\cite{biniaz_maximum_2019}. In all these results, the approximation factor is analyzed by comparing with the length of a longest (typically not plane) spanning tree. Such a tree may be up to $\pi/2>1.5$ times longer than a maximum length plane tree~\cite{AlonRS95}, as, for instance, witnessed by large point sets spaced uniformly over a circle. By comparing against a longest \emph{plane} tree, and by considering certain trees with diameter five in addition to stars, we could recently push the approximation factor to \(0.512\)~\cite{cabello2020better}. This was subsequently improved even further to $0.519$~\cite{biniaz2020improved}. \subparagraph*{Our results.} We study the interplay between the approximation factor and the diameter of the candidate trees. Our first result is a polynomial-time algorithm to find a tree that has diameter at most four and guarantees an approximation factor of roughly \(0.546\), a substantial improvement over the previous bounds. \begin{restatable}{theorem}{thmapproximation}\label{thm:approximation} For any finite point set $\mathcal{P}$ in general position (no three points collinear), we can compute in polynomial time a plane tree of Euclidean length at least $f\cdot |\Topt|$, where $|\Topt|$ denotes the length of a longest plane tree on $\mathcal{P}$ and $f> 0.5467$ is the fourth smallest real root of the polynomial \[P(x)=-80 + 128 x + 504 x^2 - 768 x^3 - 845 x^4 + 1096 x^5 + 256 x^6. \] \end{restatable} The algorithm ``guesses'' the longest edge of a longest plane tree and then constructs six certain trees -- four stars and two more trees that contain the guessed edge and have diameter at most four. We argue that one of these six trees is sufficiently long. The polynomial \(P(x)\) comes from optimizing the constants used in the proof. Our second result characterizes the longest plane tree for convex points sets. \begin{restatable}{theorem}{thmconvex}\label{thm:convex} If $\mathcal{P}$ is convex then every longest plane tree is a zigzagging caterpillar. \end{restatable} A \emph{caterpillar} is a tree $T$ that contains a path $S$, called \emph{spine}, so that every vertex of $T\setminus S$ is adjacent to a vertex in $S$. A tree $T$ that is straight-line embedded on a convex point set $\mathcal{P}$ is a \emph{zigzagging caterpillar} if its edges split the convex hull of $\mathcal{P}$ into faces that are all triangles. The converse of \cref{thm:convex} holds as well. \begin{restatable}{theorem}{thmcaterpillars}\label{thm:caterpillars} For any caterpillar $C$ there exists a convex point set $\mathcal{P}$ such that the unique longest tree for $\mathcal{P}$ is isomorphic to $C$. \end{restatable} In particular, the diameter of a (unique) longest plane tree can be arbitrarily large. As a consequence, we obtain an upper bound on the approximation factor $\bd(d)$ that can be achieved by a plane tree of diameter at most $d$. \begin{restatable}{theorem}{thmdiameterbound}\label{thm:diameter-bound} For each $d\ge 2$ there exists a convex point set $\mathcal{P}$ so that every plane tree of diameter at most $d$ on $\mathcal{P}$ is at most \[ \bd(d)\le 1- \frac{6}{(d+1)(d+2)(2d+3)} = 1-\Theta(1/d^3) \] times as long as the length $|\Topt|$ of a longest (general) plane tree on $\mathcal{P}$. \end{restatable} For small values of $d$ we have better bounds. For $d=2$ it is easy to see that $\bd(2)\le 1/2$: Put two groups of roughly half of the points sufficiently far from each other. For $d=3$ we can show $\bd(3)\le 5/6$. \begin{restatable}{theorem}{thmdiameterthreebound}\label{thm:diameter-3-bound} For every $\varepsilon>0$ there exists a convex point set such that each longest plane tree of diameter three is at most $(5/6)+\varepsilon$ times as long as each longest (general) plane tree. \end{restatable} Our third result are polynomial time algorithms for finding a longest plane tree among those of diameter at most three and among a special class of trees of diameter at most four. Note that in contrast to diameter two, the number of spanning trees of diameter at most three is exponential in the number of points. \begin{restatable}{theorem}{thmdp}\label{thm:dp} For any set $\mathcal{P}$ of $n$ points in general position, a longest plane tree of diameter at most three on $\mathcal{P}$ can be computed in $\mathcal{O}(n^4)$ time. \end{restatable} \begin{restatable}{theorem}{thmtristar}\label{thm:tristar} For any set $\mathcal{P}$ of points in general position and any three specified points on the boundary of the convex hull of \(\mathcal{P}\), we can compute in polynomial time the longest plane tree such that each edge is incident to at least one of the three specified points. \end{restatable} The algorithms are based on dynamic programming. Even though the length $|\Topt^3|$ of a longest plane tree of diameter at most three can be computed in polynomial time, we do not know the corresponding approximation factor $\bd(3)$. The best bounds we are aware of are $1/2\le \bd(3)\le 5/6$. The lower bound follows from~\cite{AlonRS95}, the upper bound is from~\cref{thm:diameter-3-bound}. We conjecture that $|\Topt^3|$ actually gives a better approximation factor than the tree constructed in~\cref{thm:approximation}---but we are unable to prove this. Finally, a natural way to design an algorithm for the longest plane spanning tree problem is the following local search heuristic~\cite{WilliamsonSh11}: start with an arbitrary plane tree $T$, and while it is possible, apply the following local improvement rule: if there are two edges $e$, $f$ on $\mathcal{P}$ such that $(T \setminus \{e\}) \cup \{f\}$ is a plane spanning tree for $\mathcal{P}$ that is longer than $T$, replace $e$ by $f$. Once no further local improvements are possible, output the current tree $T$. Our fourth result (see~\cref{thm:stuck}) shows that for some point sets, this algorithm fails to compute the optimum answer as it may ``get stuck'' in a local optimum. This suggests that a natural local search approach does not yield an optimal algorithm for the problem. \input{sec-preliminaries.tex} \input{sec-approximation.tex} \input{sec-caterpillars.tex} \input{sec-dp.tex} \input{sec-stuck.tex} \input{sec-discussion.tex} \section{An approximation factor \texorpdfstring{$f\doteq 0.5467$}{f=0.5467}}\label{sec:approximation} In this section we present a polynomial time algorithm that yields an $f$-approximation of the longest plane tree for $f\doteq 0.5467$. We furthermore show that the same algorithm yields a \(f=\frac{2}{3}\) approximation for flat point sets. The algorithm considers trees $T_{a,b}$, for $a,b\in\mathcal{P}$, that are defined as follows (see Figure~\ref{fig:approx-Tab}): Let $\mathcal{P}_a$ be the points of $\mathcal{P}$ closer to $a$ than to $b$ and let $\mathcal{P}_b=\mathcal{P}\setminus \mathcal{P}_a$. First, connect $a$ to every point in $\mathcal{P}_b$. Second, connect each point of $\mathcal{P}_a\setminus \{ a \}$ to some point of $\mathcal{P}_b$ without introducing crossings. One possible, systematic way to do the second step is the following: The rays $\overrightarrow{av}$ for $v\in \mathcal{P}_b$ together with the ray opposite to $\overrightarrow{ab}$ partition the plane into convex wedges with common apex $a$. Each such convex wedge $W$ contains a point $b_W\in \mathcal{P}_b$ on the bounding ray that forms the smaller (convex) angle with $\overrightarrow{ab}$. Within each wedge $W$ we can then connect all points of \(W\cap(\mathcal{P}_a\setminus \{ a \})\) to $b_W$. The construction gives a plane tree because we add stars within each convex wedge and the interiors of the wedges are pairwise disjoint. Note that $T_{a,b}$ and $T_{b,a}$ are different in general. Also, if $\mathcal{P}_a=\{a\}$, then $T_{a,b}=T_{b,a}$ is the star $S_a$. \begin{figure}[ht] \center \includegraphics[scale=1]{figures/lens-Tab.pdf} \caption{A tree $S_a$ and a tree $T_{a,b}$. } \label{fig:approx-Tab} \end{figure} Given the above definition of the trees $T_{a,b}$, consider the following (polynomial-time) algorithm that constructs a tree $\Talg$: \noindent\textbf{Algorithm} \texttt{AlgSimple($\mathcal{P}$)}: \begin{enumerate} \item For each point $a\in\mathcal{P}$, consider the star $S_a$. \item For every pair of points $a,b\in\mathcal{P}$, consider the tree $T_{a,b}$. \item Let $\Talg$ be the longest of those $n+n(n-1)=n^2$ trees. \item Output $\Talg$. \end{enumerate} Given multiple trees which all contain a common edge \(ab\) we device a way to compare the weights of the trees, by considering the edges separately. For this we direct all edges towards the edge \(ab\) and assign each point its unique outgoing edge. The edge \(ab\) remains undirected. Denote the length of the edge assigned to \(p \neq a,b\) in a fixed tree \(T\) by \(\ell_T(p)\). \defT_{\operatorname{cr}}{T_{\operatorname{cr}}} The main result of this section (\cref{thm:approximation}) states that for any point set $\mathcal{P}$ we have $|\Talg|> 0.5467 \cdot |\Topt|$. The proof is rather involved. To illustrate our approach, we first show a stronger result for a special case when the point set $\mathcal{P}$ is flat: namely that in those cases we have $|\Talg|\ge \frac23\cdot |T_{\operatorname{cr}}|$, where $T_{\operatorname{cr}}$ is the longest (possibly crossing) tree. The following observation shows that the constant \(\frac{2}{3}\) is tight: \begin{observation} There is an infinite family of point sets \(\mathcal{P}_1,\mathcal{P}_2, \dots \) where \(\mathcal{P}_n\) has \(n+1\) points and \begin{equation*} \lim_{n\to\infty} \frac{|\Topt|}{|T_{\operatorname{cr}}|} \leq \frac{2}{3} \end{equation*} \end{observation} \begin{proof} \begin{figure}[htb] \centering \includegraphics[page=1]{figures/thin-cor.pdf} \caption{The point set \(\mathcal{P}_n\) consisting of $n+1$ points with equally spaced $x$-coordinates $0,1,\dots,n$, with its best plane and crossing spanning trees.} \label{fig:thin-cor} \end{figure} The point set \(\mathcal{P}_n= p_0,\dots, p_{n}\) is a flat point set where all points lie evenly spaced on a convex arc with \(x\)-coordinates \(0,\dots, n\), as shown in \cref{fig:thin-cor}. Then the optimal plane tree is a star at either \(p_0\) or \(p_n\) and thus has length: \begin{equation*} |\Topt| = \sum_{i=1}^{n} i = \frac{(n+1)n}{2} \end{equation*} Whereas in the longest crossing spanning tree, the points \(p_1,\dots, p_{\lfloor{n/2}\rfloor}\) are connected to \(p_n\) and the rest is connected to \(p_0\) as shown on the right side in \cref{fig:thin-cor}. This gives a total length of \begin{equation*} |T_{\operatorname{cr}}| \geq 2 \sum_{i=\lceil n/2 \rceil}^{n-1} i + n - \left\lceil\frac{n}{2}\right\rceil \geq n^2 - \left\lceil\frac{n}{2}\right\rceil^2 \geq \frac{3n^2}{4} - \frac{1}{2} n - \frac{1}{4} \end{equation*} and we have \begin{equation*} \lim_{n\to\infty} \frac{|\Topt|}{|T_{\operatorname{cr}}|} \leq \lim_{n\to\infty} \frac{\frac{n^2}{2} +\frac{n}{2}}{\frac{3n^2}{4} - \frac{1}{2} n - \frac{1}{4}} = \frac{2}{3} \end{equation*} as claimed. \end{proof} \def\operatorname{cr}{\operatorname{cr}} \begin{theorem}\label{thm:approximation-flat} Suppose $\mathcal{P}$ is flat. Then $|\Talg|\ge \frac23 |T_{\operatorname{cr}}| \ge \frac23 |\Topt|$. \end{theorem} \begin{proof} Since $|T_{\operatorname{cr}}|\ge |\Topt|$, it suffices to prove the first inequality. Denote the diameter of $\mathcal{P}$ by $ab$ (see Figure~\ref{fig:thin}). Consider four trees $S_a$, $T_{a,b}$, $T_{b,a}$, $S_b$. It suffices to show that there is a \(\beta\) such that \[ (1/2 - \beta) |S_a| + \beta |T_{a,b}|+\beta |T_{b,a}| + (1/2 -\beta) |S_b| \ge \frac23 \cdot |T_{\operatorname{cr}}|. \] Here we fix \(\beta = \frac{1}{3}\) and equivalently show: \begin{equation*} \frac{|S_a| + 2 |T_{a,b}| + 2 |T_{b,a}| + |S_b|}{6} \geq \frac{2}{3} \cdot |T_{\operatorname{cr}}| \end{equation*} \begin{figure}[htb] \centering \includegraphics[page=1]{figures/thin.pdf} \caption{ By triangle inequality and symmetry we have \(\|pb\|+\|pp'\|\ge \|p'b\|=\|pa\|\). } \label{fig:thin} \end{figure} Note that all four trees on the left-hand side include edge $ab$ and since $ab$ is a diameter, we can without loss of generality assume that $T_{\operatorname{cr}}$ contains it too. Thus we can use the notation \(\ell_{T}(p)\) as defined above. Assume the following holds for all \(p \in \mathcal{P} \setminus \{a,b\}\), \begin{equation} \frac{ \ell_{S_a}(p) + 2\ell_{T_{a,b}}(p) +2\ell_{T_{b,a}}(p) + \ell_{S_b}(p) }{6} \ge \frac23\cdot \ell_{T_{\operatorname{cr}}}(p) \label{eq:flatapprox} \end{equation} then summing up over all points \(p\in \mathcal{P} \setminus \{a,b\}\) and adding \(\Vert ab \Vert\) to both sides yields the desired result. Without loss of generality, suppose that $\|pa\|\ge \|pb\|$ and let $p'$ be the reflection of $p$ about the perpendicular bisector of $ab$. Since $\mathcal{P}$ is flat, we have \(\ell_{T_{\operatorname{cr}}}(p)\le\max\{\|pa\|,\|pb\|\}=\|pa\|\). Moreover, \( \ell_{T_{b,a}}(p) \ge \|pp'\| /2\) and \(\ell_{T_{a,b}}(p) = \|pa\|\). Using the triangle inequality in $\triangle bpp'$, the left-hand side of (\ref{eq:flatapprox}) is thus at least \[ \frac{ \|pa\|+2\|pa\|+\|pp'\|+\|pb\| }{6} \ge \frac{\|bp'\|+3\|pa\|}{6} = \frac23\cdot \|pa\| \ge \frac23\cdot \ell_{T_{\operatorname{cr}}}(p) \] as desired. \end{proof} Now we use a similar approach to show the main theorem of this section: \thmapproximation* \begin{proof} We outline the proof strategy, referring to lemmas that will be proved later in this section. Without loss of generality, suppose $\mathcal{P}$ has diameter 2. Consider the longest edge $ab$ of $\Topt$ and denote its length by $2d$ (we have $d\le 1$). Let \(u\) and \(v\) be the points realizing the diameter. If $2d\le 1/f$, then we can show (\cref{lem:short}) that either $S_u$ or $S_v$ is long enough. Hence from now on, we can assume that $2df> 1$. Note that $\mathcal{P}$ lies inside the lens $D(a,2) \cap D(b,2)$; the points $a$ and $b$ are in the interior of the lens. Without loss of generality, suppose that $a=(-d,0)$ and $b=(d,0)$. We split the lens into the \emph{far region} and the \emph{truncated lens}, as follows and depicted in \cref{fig:approx-factor}. Let $s,s'$ be the points on the $y$-axis such that $\Vert sa \Vert=\Vert sb \Vert=\Vert s'a \Vert=\Vert s'b \Vert=2df$. We take $s$ to be the one above the $x$-axis. Since $2df> 1$, the circles $k=\partial D(s,\Vert sa\Vert )$ and $k'=\partial D(s',\Vert s'a \Vert)$ intersect the boundary of the lens. The \emph{far region} then consists of points in the lens above $k$ and of points below $k'$. Note that for the points $c$ in the far region the triangle $abc$ is acute-angled and its circumradius $R$ satisfies $R\ge 2df$. \begin{figure}[ht] \center \includegraphics{figures/lens-opt.pdf} \caption{The lens is split into the far region (green) and the truncated lens.} \label{fig:approx-factor} \end{figure} Next, we argue that if $\mathcal{P}$ contains a point $c$ in the far region, then one of the three stars $S_a$, $S_b$ or $S_c$ is long enough (\cref{lem:far}). For this, we can restrict our attention to the case when $c$ is above the $x$-axis. Finally, we argue that if all points of $\mathcal{P}$ lie in the truncated lens, then one of the trees $S_a$, $T_{a,b}$, $T_{b,a}$, $S_b$ is long enough. Consider those four trees and $\Topt$. For these five trees we can again use the notation \(\ell_T(p)\) as defined above. Given a real parameter $\beta\in(0,1/2)$, define by \[\operatorname{avg}(p,\beta)= (1/2-\beta)\cdot \ell_{S_a}(p) + \beta\cdot \ell_{T_{a,b}}(p) + \beta\cdot \ell_{T_{b,a}}(p) + (1/2-\beta)\cdot \ell_{S_b}(p)\] the weighted average of the lengths of the edges assigned to point $p$, over the four trees $S_a$, $T_{a,b}$, $T_{b,a}$, $S_b$. We aim to find $\beta\in(0,1/2)$ such that, for each point $p\ne a,b$, we have \begin{equation} \label{eqn:key} \operatorname{avg}(p,\beta) \ge f\cdot \ell_{\Topt}(p). \end{equation} In contrast to the proof to \cref{thm:approximation-flat} we have to work more to find a suitable \(\beta\). Below we will show that $\beta\doteq 0.1604$ works. Summing over $p\in\mathcal{P}\setminus \{ a,b \}$ and adding $\Vert ab\Vert$ to both sides, we then deduce that \[ (1/2-\beta)\cdot |S_a| + \beta\cdot |T_{a,b}| + \beta\cdot |T_{b,a}| + (1/2-\beta)\cdot |S_b| \ge f\cdot |\Topt|, \] thus at least one of the four trees $S_a$, $T_{a,b}$, $T_{b,a}$, $S_b$ has total length at least $f\cdot |\Topt|$. For proving the inequality (\ref{eqn:key}), we can without loss of generality assume that $p=(x,y)$ with $x,y\ge 0$. Let \(p_a\) be the point with \(x\)-coordinate \(-(2-d)\) on the ray \(pa\) and \(p_b\) be the point with \(x\)-coordinate \(2-d\) on the ray \(pb\). When the $x$-coordinate of $p$ is at least $d$, then the ray $pb$ does not intersect the vertical line with $x$-coordinate $2-d$ and we set $p_b=b$. Additionally, define \(p_u\) to be the furthest point from \(p\) on the portion of the boundary of the far region that is contained in the circle $k=\partial D(s,2df)$. The proof now proceeds in the following steps. \begin{itemize} \item We establish the upper bound \begin{align*} \ell_{\Topt}(p)&\le \min\bigl\{2d,\, \max\{\Vert pp_a\Vert, \Vert pp_b\Vert,\Vert pp_u\Vert \}\bigr\} &(\text{\cref{lem:topt}}) \end{align*} and thus only have to consider bounds for \(\Vert pp_a\Vert, \Vert pp_b\Vert\) and \(\Vert pp_u\Vert\). \item We show that the term $\Vert pp_b\Vert $ in the upper bound on $\ell_{\Topt}(p)$ can be ignored (Lemma~\ref{lem:right}). \item We establish a lower bound on $\operatorname{avg}(p,\beta)$ (\cref{lem:ab-construction}). \item We use the lower bound on $\operatorname{avg}(p,\beta)$ to identify constraints on $\beta$ such that \begin{align*} \operatorname{avg}(p,\beta) &\ge f\cdot \min\{2d,\Vert pp_a\Vert\} &(\text{\cref{lem:left}})\\ \operatorname{avg}(p,\beta)&\ge f\cdot \min\{2d,\Vert pp_u\Vert\}& (\text{\cref{lem:up}}) \end{align*} \end{itemize} This reduces the problem to showing that there exists a number $\beta$ that satisfies both the constraints coming from Lemma~\ref{lem:left} and Lemma~\ref{lem:up}. The most stringent constraints turn out to be those coming from Lemma~\ref{lem:up}, namely: \begin{equation}\label{eqn:f-constraints} \frac{2f-1}{2\sqrt{5-8f}-1} \le\beta\le 1-f\sqrt{4f^2-1}-2f^2. \end{equation} Straightforward algebra (\cref{lem:algebra}) shows that for our definition of $f$, the left-hand side and the right-hand side of (\ref{eqn:f-constraints}) are in fact equal, hence we can set $\beta\doteq 0.1604$ to be their joint value. (The value $f=5/8$ also makes the left and the right sides of (\ref{eqn:f-constraints}) equal, but it is not suitable because it gives $\beta<0$.) To summarize, for the value $f\doteq 0.5467$ defined in the statement of the Theorem, the value $\beta=1-f\sqrt{4f^2-1}-2f^2 \doteq 0.1604$ and for each point $p\neq a,b$, we have \begin{align*} \operatorname{avg}(p,\beta) &\ge f\cdot \max\bigl\{ \min\{2d,\Vert pp_a\Vert\},\, \min\{2d,\Vert pp_u\Vert\}\bigr\} \\ &\ge f\cdot \min\bigl\{ 2d,\, \max\{\Vert pp_a\Vert,\Vert pp_u\Vert\}\bigr\} \\ &\ge f\cdot \ell_{\Topt}(p) \end{align*} and the result follows. \end{proof} It remains to prove Lemmas~\ref{lem:short} to \ref{lem:algebra}. Unfortunately, the statements of those Lemmas rely on the notation already introduced in the proof of \cref{thm:approximation}. Thus, to follow the rest of this section, one has to understand the concepts and the notation introduced in the proof of \cref{thm:approximation}. \begin{lemma}\label{lem:short} Let $\mathcal{P}$ be a point set and the points $u$ and $v$ realize its diameter. Suppose that $\Vert uv\Vert=2$ and that each edge of the optimal tree $\Topt$ has length at most $1/f$. Then $\max\{|S_u|,|S_v|\}\ge f\cdot |\Topt|$. \end{lemma} \begin{proof} By the triangle inequality, for any point $p\in\mathcal{P}$ we have $\Vert pu\Vert +\Vert pv\Vert\ge \Vert uv\Vert$. Hence \[|S_u|+|S_v| = \sum_{p\in\mathcal{P}} \Vert pu\Vert +\Vert pv\Vert \ge n\cdot \Vert uv\Vert = 2n, \] implying that $\max\{|S_u|,|S_v|\}\ge n$. On the other hand, since each of the $n-1$ edges in $\Topt$ has length at most $1/f$, we get \[f\cdot |\Topt|\le f\cdot (n-1)\cdot \frac1f\le n \] and we are done. \end{proof} \begin{lemma}\label{lem:far} Let $ab$ (with $\Vert ab\Vert=2d$) be the longest edge of $\Topt$. If $\mathcal{P}$ contains a point \(c\) in the far region, then $\max\{|S_a|,|S_b|, |S_c|\}\ge f\cdot |\Topt|$. \end{lemma} \begin{proof} By the definition of the far region, the triangle $abc$ is acute-angled and its circumradius $R$ satisfies $R\ge 2df$. Let $g$ be the center of mass of the pointset $\mathcal{P}_0\equiv \mathcal{P}\setminus\{a,b,c\}$. (Such a point set may have points below and above the $x$-axis, but that does not affect the argument.) Then for any point $v$ in the plane we have $\ds{vg}=\frac1{|\mathcal{P}_0|} \sum_{p\in\mathcal{P}_0} \ds{vp}$. \begin{figure}[ht] \center \includegraphics{figures/lens-lem-green.pdf} \caption{Lemma~\ref{lem:far}. In the illustration, $\mathcal{P}_0$ consists of 6 points and we can take $v=a$. The point through three circles is the center of the circle through $a,b,c$.} \label{fig:green} \end{figure} Since the triangle $abc$ is acute-angled, there exists a vertex $v\in\{a,b,c\}$ of the triangle such that $\Vert vg\Vert\ge R$. Triangle inequality then gives \[\sum_{p\in \mathcal{P}_0} \Vert vp\Vert \ge |\mathcal{P}_0|\cdot \Vert vg\Vert\ge (n-3)\cdot R. \] Together with $\Vert va\Vert+\Vert vb\Vert+\Vert vc\Vert \ge 2R$ which holds for any acute-angled triangle, this yields \[|S_v|\ge (n-3)R+2R= (n-1)\cdot R\ge (n-1)\cdot 2df \ge f\cdot |\Topt|, \] where in the last inequality we used that each edge of $\Topt$ has length at most $2d$. \end{proof} Recall that \(ab\) is the longest edge of \(\Topt\), that we assumed $a=(-d,0)$, $b=(d,0)$ and that $2df>1$. Note that the point \(s\) has coordinates \(s=(0,\sqrt{(2df)^2-d^2})\). We also noted that the two circle \(k=D(s,\Vert sa \Vert)\) always intersect the lens $D(a,2)\cap D(b,2)$. Consider the two intersection points of \(k\) with the boundary of the lens with largest \(y\)-coordinate and call them \(u\) and \(v\), where $u$ is to the left of $v$. Refer to \cref{fig:approx-factor} or \cref{fig:topt} for an illustration. For each point $p=(x,y)$ in the truncated lens with $x,y\ge 0$, recall that we have defined the following points: \begin{itemize} \item $p_a$ is the point on the ray $pa$ whose $x$-coordinate equals $-(2-d)$; \item $p_b$ is the point on the ray $pb$ whose $x$-coordinate equals $2-d$, if $x(p)<d$, and $p_b=b$ if $x(p)\ge d$. \item $p_u$ is the the point on the arc of $k$ from $u$ to $v$ that is furthest from $p$. Thus, if the line through $sp$ intersects the arc of $k$ from $u$ to $v$, then $p_u$ is that intersection point, otherwise $p_u=u$. \end{itemize} \begin{figure} \centering \includegraphics{figures/lens-lem-topt.pdf} \caption{ For $p\in E$ we have $\ell_{\Topt}(p)\le 2d$, for $p \in N$ we have $\ell_{\Topt}(p)\le \max\{\Vert pp_a\Vert,\Vert pu\Vert \}$ and for $p \in S$ we have $\ell_{\Topt}(p)\le \max\{\Vert pp_a\Vert,\Vert pp_u\Vert\}$.} \label{fig:topt} \end{figure} \begin{lemma}\label{lem:topt} For each point $p=(x,y)$ in the truncated lens with $x,y\ge 0$ we have \[ \ell_{\Topt}(p)\le \min\{2d, \max\{\Vert pp_a\Vert,\Vert pp_b\Vert,\Vert pp_u\Vert\}\}. \] \end{lemma} \begin{proof} As \(p\) lies in the first quadrant, we only have to consider the truncated lens in this quadrant. Let \(l\) and \(r\) be the left and right most points of \(D(a,2) \cap D(b,2)\). Thus $r=(2-d,0)$ and $l=(d-2,0)$. For the following we further subdivide the truncated lens into regions; again see \cref{fig:topt} for an illustration. First of all we denote the region inside the truncated lens but outside of \(D(l, 2d)\) by \(E\). The remainder of the truncated lens we divide into the part \(N\) above the line \(us\) and the part \(S\) below that line. Note that if $p$ lies in \(E\) then $\Vert pp_a\Vert\ge \Vert pl\Vert\ge 2d$, hence the right-hand side equals $2d$. Since the left-hand side is at most $2d$ by assumption, the claim is true. \begin{figure}[ht] \center \includegraphics[page=2]{figures/lens-lem-topt.pdf} \caption{The point $p_f$ lies on the arc $ul$. The set of points $p$ such that $\Vert pp_f\Vert> \max\{ \Vert pl\Vert,\Vert pu\Vert \}$ forms a convex wedge with vertex $b$ fully contained in the fourth quadrant. } \label{fig:topt_case5} \end{figure} So from now on we can assume that $p\in N\cup S$. This directly implies that $p_b\neq b$ and $x(p_b)=2-d$. Let $p_f$ be the point within the truncated lens furthest from $p$. Clearly, $p_f$ lies on the boundary of the truncated lens. Since $\ell_{\Topt(p)}\le 2d$ by assumption, it suffices to show that $\Vert pp_f\Vert\le \max\{\Vert pp_a\Vert,\Vert pp_b\Vert,\Vert pp_u\Vert\}$. Let $t$ be the top-most point of the truncated lens. We distinguish 5 cases: \begin{enumerate} \item $p_f$ lies in the third quadrant: Then $\Vert pp_f\Vert \le \Vert pp_a\Vert$. \item $p_f$ lies in the fourth quadrant: Then $\Vert pp_f\Vert\le \Vert pp_b\Vert$. \item $p_f$ lies in the first quadrant: Consider the reflection $p_f'$ of $p_f$ about the $y$-axis. Since $x\ge 0$ we have $\Vert pp_f'\Vert\ge \Vert pp_f\Vert$, and the inequality is strict when $x>0$. Thus, when $x>0$, this case cannot occur, and when $x=0$, it reduces to the case where $p_f$ belongs to the second quadrant. \item $p_f$ lies in the second quadrant: \begin{enumerate} \item $p_f$ lies on the arc $tu$ (\cref{fig:topt}): If $p$ lies in \(N\) then for any $q$ on the arc $tu$ we have $\Vert pq\Vert\le \Vert pu\Vert =\Vert pp_u\Vert$, thus also $\Vert pp_f\Vert\le \Vert pp_u\Vert$. If $p$ lies in \(S\) then, by triangle inequality, $\Vert pp_f\Vert\le \Vert ps\Vert+\Vert sp_f\Vert=\Vert ps\Vert+2df = \Vert pp_u\Vert$. \item\label{item:arc-ul} $p_f$ lies on the arc $ul$: We claim that $\Vert pp_f\Vert\le \max\{ \Vert pl\Vert,\Vert pu\Vert \}$. Indeed, the perpendicular bisectors of segments $p_fl$ and $p_fu$ intersect at $b$ and thus the points for which the claim fails all lie in a convex wedge with vertex $b$ that is fully contained in the fourth quadrant, see \cref{fig:topt_case5}. Since $\Vert pl\Vert\le \Vert pp_a\Vert$ and $\Vert pu\Vert \le \Vert pp_u\Vert$, we get $\Vert pp_f\Vert\le \max\{\Vert pp_a\Vert, \Vert pp_u\Vert\}$.\qedhere \end{enumerate} \end{enumerate} \end{proof} \begin{lemma}\label{lem:right} Let $p=(x,y)$ be any point in the truncated lens with $x,y\ge 0$. If $\Vert pp_a\Vert\le 2d$, then $\Vert pp_b\Vert\le \Vert pp_a\Vert$. \end{lemma} \begin{proof} We present a straightforward algebraic proof (we are not aware of a purely geometric proof). The case $x=0$ is clear because of symmetry; in that case $\Vert pp_b\Vert = \Vert pp_a\Vert$. Thus, we only consider the case $x>0$. Since $\Vert pp_a\Vert\le 2d$, we must have $x< d$, and therefore $p_b$ has $x$-coordinate $2-d$ (and $p_b\neq b$). \begin{figure}[ht] \center \includegraphics[scale=0.9]{figures/lens-lem-right.pdf} \caption{The situation for \cref{lem:right}. } \end{figure} From similar triangles and a Pythagorean theorem we have $\Vert pp_a\Vert=\Vert pa\Vert\cdot \frac{2-d+x}{d+x}$ and $\Vert pa\Vert^2=(d+x)^2+y^2$. Therefore the assumption $\Vert pp_a\Vert^2\le (2d)^2$ can be equivalently rewritten as \begin{align}\label{eqn:ppa} (y^2+(d+x)^2)\cdot\frac{(2-d+x)^2}{(d+x)^2}&\le 4d^2 \nonumber \\ y^2 &\le \frac{(4d^2-(2-d+x)^2)(d+x)^2}{(2-d+x)^2}. \end{align} Similarly as with $\Vert pp_a\Vert^2$, we express $\Vert pp_b\Vert^2$ as \begin{equation}\Vert pp_b\Vert^2 = (y^2+(d-x)^2)\cdot\frac{(2-d-x)^2}{(d+x)^2} \end{equation} and rewrite our goal $\Vert pp_b\Vert^2\le \Vert pp_a\Vert^2$ as \begin{align*} (y^2+(d-x)^2)\cdot\frac{(2-d-x)^2}{(d-x)^2} &\le (y^2+(d+x)^2)\cdot\frac{(2-d+x)^2}{(d+x)^2} \\ y^2\cdot \frac{(2-d-x)^2(d+x)^2 - (2-d+x)^2(d-x)^2}{(d+x)^2(d-x)^2} &\le (2-d+x)^2 - (2-d-x)^2, \\ \end{align*} which, upon expanding the parentheses and dividing by $4x>0$ transforms into the goal \[y^2\cdot \frac{2(1-d)(2d-d^2-x^2)}{(d+x)^2(d-x)^2} \le 2-d. \] We plug in the upper bound on $y^2$ from (\ref{eqn:ppa}), cancel the term $(d+x)^2$, and clear the denominators. This leaves us with proving \[ (4d^2-(2-d+x)^2) \cdot 2(1-d)(2d-d^2-x^2) \le (2-d+x)^2 \cdot (2-d) (d-x)^2 \] which, upon expanding the parentheses, reduces to \begin{equation}\label{eqn:pol} 0\le (16 d - 32 d^2 + 8 d^3 + 16 d^4 - 7 d^5) + x^2(- 8 d+ 16 d^2 - 10 d^3) + d x^4. \end{equation} For any fixed $d>0$, the right-hand side $Q(d,x^2)$ is a quadratic function of $x^2$ with positive coefficient $d>0$ by the leading term $(x^2)^2$, hence the minimum of $Q(d,x^2)$ is attained when \[ x^2=\frac{8d-16d^2+10d^3}{2d} = 4-8d+5d^2. \] Plugging $x^2=4-8d+5d^2$ into (\ref{eqn:pol}) and expanding the parentheses for the last one time we are left to prove \begin{align*} 0 &\le 32d^2-96d^3+96d^4-32d^5\\ 0&\le 32d^2(1-d)^3 \end{align*} which is true since $d\le 1$. \end{proof} \begin{lemma}\label{lem:ab-construction} Let $p=(x,y)$ be any point in the plane with $x,y \ge 0$ and let $\beta\in(0,1/2)$ be a real number. Then \[\operatorname{avg}(p,\beta) \ge \frac{d\cdot (1-\beta)+x\cdot 2\beta}{d+x}\cdot \Vert pa\Vert. \] \end{lemma} \begin{proof} Unpacking the definition we have \[\operatorname{avg}(p,\beta) \ge (1/2-\beta)\cdot \Vert pa\Vert + \beta\cdot \Vert pa\Vert + \beta\cdot x + (1/2-\beta)\cdot \Vert pb\Vert. \] \begin{figure}[ht] \center \includegraphics{figures/lens-lem-ab.pdf} \caption{Mirroring \(p\) along the \(y\)-axis in \cref{lem:ab-construction}. } \label{fig:ab} \end{figure} Let $p'=(-x,y)$ be the reflection of $p$ about the $y$ axis (see \cref{fig:ab}). The triangle inequality $\Vert p'p\Vert+\Vert pb\Vert\ge \Vert p'b\Vert =\Vert pa\Vert$ leads to $\beta\cdot x= \frac12\beta\cdot \Vert p'p\Vert \ge \frac12\beta\cdot (\Vert pa\Vert - \Vert pb\Vert)$, and we obtain \[\operatorname{avg}(p,\beta)\ge \frac12\cdot \Vert pa\Vert + \frac12\beta\cdot \Vert pa\Vert + \left(\frac12-\frac32\beta\right)\cdot \Vert pb\Vert. \] Next we claim that $\Vert pb\Vert\ge \frac{d-x}{d+x}\cdot \Vert pa\Vert$: Indeed, upon squaring, using the Pythagorean theorem and clearing the denominators this becomes $y^2\cdot 4dx\ge 0$ which is true. Using this bound on the term containing $\Vert pb\Vert$ we finally get the desired \[\operatorname{avg}(p,\beta)\ge \frac{(1+\beta)(d+x) + (1-3\beta)(d-x)}{2(d+x)} \cdot \Vert pa\Vert = \frac{(1-\beta)\cdot d + 2\beta\cdot x}{d+x} \cdot \Vert pa\Vert. \qedhere \] \end{proof} \begin{lemma}\label{lem:left} Let $p=(x,y)$ be any point in the lens with $x,y\ge 0$. Suppose \[ \frac{2f-1}{5-8f} \le \beta \le \frac12\cdot f. \] Then $\operatorname{avg}(p,\beta)\ge f\cdot \min\{2d,\Vert pp_a\Vert\}$. \end{lemma} \begin{proof} It suffices to show that: \begin{enumerate} \item If $x\ge 3d-2$, then $\operatorname{avg}(p,\beta)\ge f\cdot 2d$. \item If $x\le 3d-2$, then $\operatorname{avg}(p,\beta)\ge f\cdot \Vert pp_a\Vert$. \end{enumerate} We consider those two cases independently. \begin{enumerate} \item\label{item:first} Using Lemma~\ref{lem:ab-construction} and the inequalities $\Vert pa\Vert\ge d+x$ and $x\ge 3d-2$, we rewrite \[\operatorname{avg}(p,\beta)\ge \frac{d\cdot (1-\beta)+x\cdot 2\beta}{d+x}\cdot \Vert pa\Vert \ge d-d\beta +(3d-2)\cdot2\beta = \beta(5d-4)+d. \] Hence it suffices to prove $\beta\cdot (5d-4)\ge d(2f-1)$. Using the lower bound on $\beta$ and $4\le 8df$ we get \[\beta\cdot (5d-4) \ge \beta\cdot (5d-8df) \ge\frac{2f-1}{5-8f}\cdot d\cdot (5-8f) = d(2f-1)\] as desired. Note that $2f-1$ and $5-8f$ are both positive. \item We have $\Vert pp_a\Vert=\Vert pa\Vert\cdot \frac{2-d+x}{d+x}$. Using Lemma~\ref{lem:ab-construction} it suffices to prove \begin{align*} d(1-\beta)+x\cdot 2\beta &\ge f(2-d+x) \\ d(1-\beta) -f(2-d) &\ge x(f-2\beta). \end{align*} Since $f\ge 2\beta$ by assumption, the right-hand side is increasing in $x$ and we can plug in $3d-2$ for $x$. This leaves us with proving the inequality \begin{align*} d(1-\beta) -f(2-d) &\ge (3d-2)(f-2\beta)\\ \beta\cdot (5d-4) &\ge d(2f-1), \end{align*} which is the same inequality as in the first case.\qedhere \end{enumerate} \end{proof} \begin{lemma}\label{lem:up} Let $p=(x,y)$ be any point in the lens with $x,y\ge 0$. Suppose that $\beta< \frac{151}{304}\cdot f$, that $\frac12 \le f\le \frac{19}{32}$ and that \begin{equation*} \frac{2f-1}{2\sqrt{5-8f}-1} \le \beta \le 1-f\sqrt{4f^2-1}-2f^2. \end{equation*} Then \begin{equation*} \operatorname{avg}(p,\beta)\ge f\cdot \min\{2d,\Vert pp_u\Vert\}.\label{eq:lemup} \end{equation*} \end{lemma} \begin{proof} Because of the lower bound for \(\operatorname{avg}(p,\beta)\) in \cref{lem:ab-construction}, to show the statement it suffices to show that \begin{equation} \frac{d\cdot (1-\beta)+x\cdot 2\beta}{d+x}\cdot \Vert pa\Vert \geq f\cdot \min\{2d, \Vert pp_u \Vert\}. \label{eq:lemup2} \end{equation} We will consider the two cases \(y\leq y(u)\) and \(y> y(u)\) separately. \paragraph*{Case 1: $y\leq y(u)$} Define \(\lambda =\frac{d\cdot (1-\beta)+x\cdot 2\beta}{d+x} \cdot \Vert pa \Vert\). We have to show that $\lambda \geq f\cdot \min\{2d, \Vert pp_u \Vert\}$. Note that \(\lambda\) is an increasing function of $y$ because $\Vert pa \Vert$ is also increasing with $y$. On the other hand, \(\Vert pp_u \Vert\) is a decreasing function of \(y\) for \( y\le y(u) \): If $p_u\ne u$, then $\Vert pp_u\Vert=\Vert ps\Vert+2df$ is decreasing in $y$, and if $p_u=u$ then \( \Vert pp_u\Vert = \Vert pu\Vert \) decreases when $y$ increases (for $y\le y(u)$). It follows that $\min\{2d, \Vert pp_u \Vert\}$ is a decreasing function of $y$ for $y\le y(u)$. As $\min\{2d, \Vert pp_u \Vert\}$ is decreasing and \(\lambda\) is increasing in \(y\), for $y\le y(u)$, to handle our current case it suffices to show (\ref{eq:lemup2}) for \(y=0\). Now we have \(\Vert pa\Vert = d+x\), so we can rewrite \(\lambda\) as \(\lambda_0 =d \cdot (1-\beta) + x \cdot 2 \beta\), which is positive. Let $q=(q_x,0), q_x\ge0$ be the point on the $x$-axis such that $\Vert qs\Vert=2d(1-f)$. This means that for $p=q$ we have $\Vert pp_u\Vert\le \Vert ps\Vert+\Vert sp_u\Vert=2d$ (see Figure~\ref{fig:up}). We further split between cases depending on whether $0\leq x \leq q_x$ or $x> q_x$. \begin{figure}[ht] \center \includegraphics{figures/lens-lem-up.pdf} \caption{Lemma~\ref{lem:up}. } \label{fig:up} \end{figure} \begin{description} \item[Case 1a:] $0\leq x \leq q_x$. We will show that in this case $\lambda_0 \geq f\cdot \Vert pp_u\Vert$. The Pythagorean theorem gives \[f\cdot \Vert pp_u\Vert\le f\cdot\Vert ps\Vert + f\cdot \Vert sp_u\Vert=f\sqrt{x^2+(2df)^2-d^2} + 2df^2 \] Therefore, substituting $\lambda_0$, it suffices to show \begin{align} d \cdot (1-\beta) + x \cdot 2 \beta &\geq f\sqrt{x^2+(2df)^2-d^2} + 2df^2. \label{eq:case1a} \end{align} When $\beta< \frac{151}{304}\cdot f$ and $f\le \frac{19}{32}$, the term $d \cdot (1-\beta) - 2df^2$ is positive and the last inequality is equivalent to \begin{align*} 0 &\geq f^2 \cdot (x^2+(2df)^2-d^2) - (d \cdot (1-\beta) + x \cdot 2 \beta - 2df^2)^2 \end{align*} The right-hand side is a quadratic function of $x$ with positive coefficient $f^2-4\beta^2$ by the leading term, hence it suffices to check the inequality (\ref{eq:case1a}) for $x\in\{0,q_x\}$. For $x=0$, we need to check that $d(1-\beta)\ge f(\sqrt{d^2(4f^2-1)} + 2df)$, which reduces precisely to the assumption \begin{equation*} \beta\le 1- f\sqrt{4f^2-1} - 2f^2. \end{equation*} For $x=q_x$, the Pythagorean theorem gives $(q_x)^2=(2d(1-f))^2 + d^2 - (2df)^2 = d^2\cdot (5-8f)$, hence $q_x=d\sqrt{5-8f}$. The point $q$ has been selected so that $\Vert ps\Vert+\Vert sp_u\Vert=2d$, and therefore the right side of (\ref{eq:case1a}) is $2df$. We thus have to verify that \begin{align} d(1-\beta)+d\sqrt{5-8f}\cdot 2\beta &\ge f\cdot 2d \label{eq:case1aa}\\ \beta\cdot (2\sqrt{5-8f} -1) &\ge 2f-1.\nonumber \end{align} Since $f\le 19/32$, the term in the parentheses on the left-hand side is positive, and after dividing we obtain precisely the assumption. \item[Case 1b:] $q_x <x$. In this case we show that $\lambda_0 \geq f\cdot 2d$. Since the term $\lambda_0$ is increasing in \(x\) and $2d$ is constant, we only need to show that $\lambda_0 \geq f\cdot 2d$ for $x=q_x$. However, this was already shown in the previous case; see (\ref{eq:case1aa}). \end{description} \paragraph*{Case 2: $y> y(p_u)$} In this case we have \(\Vert pp_u\Vert = \Vert pu\Vert \leq \Vert uv\Vert\). Furthermore, because $4df>2d$, the intersection of the line supporting $bs$ with the circle $k$ is outside the lens. That intersection point has $x$-coordinate $-d$ because of symmetry with respect to $s$, and since $u$ is above it, we have $x(u)\ge -d$ as well as $x\le d$. So we have \(\min\{2d, \Vert p p_u\Vert\} = \Vert pp_u\Vert\). This means that to show (\ref{eq:lemup2}) we have to show \begin{align*} \frac{d(1-\beta)+2x\beta}{d+x} \cdot \Vert pa\Vert & \geq f\cdot\Vert pp_u\Vert. \end{align*} As \(p\) lies above the horizontal line through \( u \), we get \(\Vert pa\Vert \geq \Vert pp_u\Vert\), thus it suffices to show \begin{align*} \frac{d(1-\beta)+2x\beta}{d+x} & \geq f\\ d-d\beta + 2x\beta & \geq fd + fx\\ d(1-(\beta+f)) & \geq x(f-2\beta)\\ x & \leq d\cdot \frac{1-(\beta+f)}{f-2\beta} \end{align*} As we know \(x\leq d\) this is true for \begin{align*} \frac{1-(\beta+f)}{f-2\beta} & \geq 1\\ 1-(\beta +f) & \geq f-2\beta\\ \beta &\geq 2f-1, \end{align*} where in the last step we used that $f>2\beta$. The last condition is a looser bound than the left side of the statement of the lemma as \(f\geq \frac{1}{2}\) and therefore \(2\cdot \sqrt{5-8f}-1 \leq 1\). \qedhere \end{proof} \begin{lemma}\label{lem:algebra} The positive solutions of \[ \frac{2x-1}{2\sqrt{5-8x}-1} = 1-x\sqrt{4x^2-1}-2x^2 \] are $x=\tfrac 58$ and the fourth smallest root of \[ -80 + 128 x + 504 x^2 - 768 x^3 - 845 x^4 + 1096 x^5 + 256 x^6. \] \end{lemma} \begin{proof} We provide a sketch of how to solve it ``by hand''. One can also use advanced software for algebraic manipulation. Setting the polynomials $q_1(x)=4x^2-1$ and $q_2(x)=5-8x$, and multiplying both sides of the equation by the denominator on the left-hand side, we are left with the equation \begin{align*} 2x-2x^2 &= x \sqrt{q_1(x)} - (2-4x^2) \sqrt{q_2(x)} - 2x\sqrt{q_1(x)q_2(x)}\\ 2x-2x^2 + 2x\sqrt{q_1(x)q_2(x)} &= x \sqrt{q_1(x)} - (2-4x^2) \sqrt{q_2(x)}. \end{align*} Squaring both sides, which may introduce additional roots, we get, for some polynomials $q_3(\,),\dots, q_6(\,)$, the equation \begin{align*} q_3(x) + q_4(x) \sqrt{q_1(x)q_2(x)} &= q_5(x) + q_6(x) \sqrt{q_1(x)q_2(x)}\\ q_3(x) -q_5(x) &= \bigl( q_6(x)-q_4(x)\bigr) \sqrt{q_1(x)q_2(x)}. \end{align*} Squaring both sides gain, which may introduce additional solutions, we get the polynomial \[ 8 (x-\tfrac 58) (-80 + 128 x + 504 x^2 - 768 x^3 - 845 x^4 + 1096 x^5 + 256 x^6) =0 \] This polynomial has 7 real roots that can be approximated numerically. The smallest three roots of this polynomial are negative ($x\doteq -4.82037$, $x\doteq -0.657898$ and $x\doteq -0.523446$). The fourth smallest root, $x\doteq 0.546723$, is a solution to the original equation. The fifth and sixth roots are $x\doteq 0.577526$ and $x\doteq 0.596211$, which are not solutions to the original equation. The largest root of the polynomial is $x=\tfrac 58 $, which is also a solution to the original equation. \end{proof} \section{Convex and flat convex point sets}\label{sec:caterpillars} In this section we present two results for convex point sets. First, we show that if $\mathcal{P}$ is a convex point set then the longest plane tree is a caterpillar (see~\cref{thm:convex}) and that any caterpillar could be the unique longest plane tree (see~\cref{thm:caterpillars}). Second, by looking at suitable flat convex sets we prove upper bounds on the approximation factor $\bd(d)$ achieved by the longest plane tree among those with diameter at most $d$. \subsection{Convex sets and caterpillars}\label{sec:convex} We say that a tree $C$ is a \textit{caterpillar} if it contains a path $P$ such that each node $v\in C$ not lying on $P$ is adjacent to a node on $P$. Equivalently, a tree is a caterpillar if its edges can be listed in such an order that every two consecutive edges in the list share an endpoint. \begin{figure}[ht] \center \includegraphics{figures/flat-zigzag.pdf} \caption{Left: A tree $T_1$ that spans $\mathcal{P}$ but it is not a caterpillar. Middle: A tree $T_2$ that is a caterpillar but it is not zigzagging. Right: A tree $T_3$ that is a zigzagging caterpillar -- the dual tree $T_3^\star$ is a path. } \label{fig:zigzag} \end{figure} Throughout this section we consider trees that span a given convex point set $\mathcal{P}$. We say that (a drawing of) such a tree $T$ is a \textit{zigzagging caterpillar} if $T$ is a caterpillar and the dual graph $T^\star$ of $T$ is a path. Here a \textit{dual graph} $T^\star$ is defined as follows: Let $C$ be a smooth closed curve passing through all points of $\mathcal{P}$. The curve bounds a convex region and the $n-1$ edges of $T$ split that region into $n$ subregions. The graph $T^\star$ has a node for each such subregion and two nodes are connected if their subregions share an edge of $T$ (see~\cref{fig:zigzag}). First we prove that the longest plane tree of any convex set is a zigzagging caterpillar. \thmconvex* \begin{proof} Let $\Topt$ be a longest plane tree. We prove that $\Topt^\star$ is a path by contradiction. \begin{figure}[h] \center \includegraphics{figures/flat-convex.pdf} \caption{Left: A convex point set with a (fake) longest plane tree $\Topt$ (black) and the dual graph $\Topt^\star$ (blue). Right: If $\Topt^\star$ has a node of degree 3 or more, a longer tree can be constructed by replacing one dotted edge of $\Topt$ by a longer edge (of the same color). } \label{fig:convex} \end{figure} Suppose a node $v$ of $\Topt^\star$ has degree at least 3 and let $ab$, $bc$, $cd$ be three corresponding edges of $\Topt$ (see~\cref{fig:convex}). Since the quadrilateral $abcd$ is convex, by triangle inequality we have $\Vert ab\Vert +\Vert cd\Vert <\Vert ac\Vert +\Vert bd\Vert $. Hence either $\Vert ab\Vert <\Vert ac\Vert $ or $\Vert cd\Vert <\Vert bd\Vert $ (or both). Since $T_1=\Topt\cup \{ac\}\setminus\{ab\}$ and $T_2=\Topt\cup \{bd\}\setminus\{cd\}$ are both plane trees, at least one of them is longer than $\Topt$, a contradiction. \qedhere \end{proof} \def\operatorname{Cov}{\operatorname{Cov}} Conversely, for each caterpillar $C$ we will construct a convex set $\mathcal{P}_C$ whose longest plane tree is isomorphic to $C$. In fact, $\mathcal{P}_C$ will be not only convex but also a ``flat arc''. Formally, we say that a set $\mathcal{P}$ of $n=m+1$ points $a_i=(x_i,y_i)$ satisfying $x_1<\dots<x_{m+1}$ is a \textit{flat arc} if it is flat (that is, the absolute values of all $y$-coordinates are negligible) and the points $a_1,\dots,a_{m+1}$ all lie on the convex hull of $\mathcal{P}$ in this order. We call the sequence $G(\mathcal{P})=\{g_i\}_{i=1}^m=\{| x_{i+1}-x_i| \}_{i=1}^m$ the (horizontal) \textit{gap sequence}. Lastly, given a tree $T$ spanning a flat arc $\mathcal{P}$, we define its \textit{cover sequence} $\operatorname{Cov}(T)=\{c_i\}_{i=1}^m$ to be a list storing the number of times each gap is ``covered''. Formally, $c_i$ is the number of edges of $T$ that contain a point whose $x$-coordinate lies within the open interval $(x_i,x_{i+1})$, see~\cref{fig:flat-convex-2}. Note that the gap sequence and the cover sequence determine the length of the tree because $|T|= \sum_{i=1}^m c_i\cdot g_i$. \begin{figure}[h] \center \includegraphics[scale=0.8]{figures/flat-gaps-covers.pdf} \caption{Given a flat arc $\mathcal{P}$ of $n=m+1$ points, we denote by $G(\mathcal{P})=\{g_i\}_{i=1}^m$ its gap sequence. Given a tree $T$ spanning $\mathcal{P}$, we denote by $\operatorname{Cov}(T)=\{c_i\}_{i=1}^m$ its cover sequence. Later we show that the longest plane tree $\Topt$ of a flat arc $\mathcal{P}$ is a zigzagging caterpillar containing the edge $a_1a_{m+1}$ and that its cover sequence $\operatorname{Cov}(\Topt)$ is a unimodal (single-peaked) permutation of $\{1,2,\dots,m\}$.} \label{fig:flat-convex-2} \end{figure} Before we prove that any caterpillar can be the longest tree of a flat arc, we first show that the cover sequences of zigzagging caterpillars are unimodal (single-peaked) permutations. \begin{lemma}\label{lem:unimodal} Consider a flat arc $\mathcal{P}=\{a_1,\dots,a_{m+1}\}$ and a zigzagging caterpillar $T$ containing the edge $a_1a_{m+1}$. Then the cover sequence $\operatorname{Cov}(T)$ of $T$ is a unimodal permutation of $\{1,2,\dots,m\}$. \end{lemma} \begin{proof} By induction on $m$. The case $m=1$ is clear. Fix $m\ge 2$. By the definition of a zigzagging caterpillar, the dual graph $T^\star$ of $T$ is a path. Since $a_1a_{m+1}$ is an edge of $T$, either $a_1a_m$ or $a_2a_{m-1}$ is an edge of $T$ too. Without loss of generality assume $a_1a_m$ is an edge of $T$. Then $T\setminus\{a_1a_{m+1}\}$ is a zigzagging caterpillar on $m$ points $a_1,\dots,a_m$ containing the edge $a_1a_m$, hence by induction its cover sequence is a unimodal permutation of $\{1,2,\dots,m-1\}$. Adding the omitted edge $a_1a_{m+1}$ adds 1 to each of the $m-1$ elements and appends a 1 to the list, giving rise to a unimodal permutation of $\{1,2,\dots,m\}$. This completes the proof. \end{proof} Now we are ready to prove that any caterpillar, including a path, can be the longest plane tree of some flat arc. \thmcaterpillars* \begin{proof} We will define a flat arc $\mathcal{P}_C$ such that the unique longest tree $\Topt$ of $\mathcal{P}_C$ is isomorphic to $C$. Consider a flat arc $\mathcal{P}=\{a_1,\dots,a_{m+1}\}$, with a yet unspecified gap sequence $\{g_i\}_{i=1}^m$. Take the caterpillar $C$ and let $T$ be its drawing onto $\mathcal{P}$ that contains the edge $a_1a_{m+1}$ and is zigzagging (it is easy to see that such a drawing always exists). By~\cref{lem:unimodal} its cover sequence $\operatorname{Cov}(T)=\{c_i\}_{i=1}^m$ is a unimodal permutation of $\{1,2,\dots,m\}$. The total length $|T|$ of $T$ can be expressed as $|T|=\sum_{i=1}^m c_i\cdot g_i$. Now we specify the gap sequence: For $i=1,\dots,m$ set $g_i=c_i$. It is easy to see that this sequence defines a plane tree $T$; see \cref{fig:flat-convex-2}. It suffices to show that $T$ coincides with the longest plane tree $\Topt$ of $\mathcal{P}$. By~\cref{thm:convex}, $\Topt$ must be a zigzagging caterpillar. Moreover, note that $a_1a_{m+1}$ is an edge of $\Topt$: Indeed, assume otherwise. Since $a_1a_{m+1}$ does not cross any other edge, adding it to $\Topt$ produces a plane graph with a single cycle. Since all edges of $\Topt$ are shorter than $a_1a_{m+1}$, omitting any other edge from that cycle creates a longer plane tree, a contradiction. Thus we can apply~\cref{lem:unimodal} to $\Topt$ and learn that the cover sequence of $\Topt$ is some unimodal permutation $\pi$ of $\{1,2,\dots,m\}$ and that its total length $|\Topt|$ can be written as $|\Topt|=\sum_{i=1}^m \pi_i\cdot g_i$. Since $c_i$ and $g_i$ match, by rearrangement inequality we have \begin{equation} |\Topt|=\sum_{i=1}^m \pi_i\cdot g_i \le \sum_{i=1}^m c_i\cdot g_i = |T| ~~~ \text{with equality only if $\pi_i=c_i$ for each $i$.}\label{eq:rearrangement} \end{equation} Therefore $\Topt=T$ and we are done. \end{proof} \subsection{Upper bounds on \texorpdfstring{$\bd(d)$}{bd(d)}} The algorithms for approximating $|\Topt|$ often produce trees with small diameter. Given an integer $d\ge 2$ and a point set $\mathcal{P}$, let \( \Td{d}(\mathcal{P})\) be a longest plane tree spanning $\mathcal{P}$ among those whose diameter is at most $d$. One can then ask what is the approximation ratio \[\bd(d) = \inf_{\mathcal{P}} \frac{ |\Td{d}(\mathcal{P})| }{ |\Topt (\mathcal{P})|} \] achieved by such a tree. As before, we drop the dependency on $\mathcal{P}$ in the notation and just use $\Td{d}$ and $\Topt$. When $d=2$, this reduces to asking about the performance of stars. A result due to Alon, Rajagopalan and Suri~\cite[Theorem 4.1]{AlonRS95} can be restated as $\bd(2)=1/2$. Below we show a crude upper bound on $\bd(d)$ for general $d$ and then a specific upper bound tailored to the case $d=3$. Note that \cref{thm:dp} shows that $|\Td{3}|$ can be computed in polynomial time. Our proofs in this section use the notions of flat arc, gap sequence and cover sequence defined in~\cref{sec:convex}. \thmdiameterbound* \begin{proof} Consider a flat arc on $d+2$ points with gap sequence $G=(1,3,5,\dots,d+1,\dots,6,4,2)$. Since $G$ is unimodal, arguing as in the proof of \cref{thm:caterpillars} we obtain that $\Topt$ is the zigzagging caterpillar whose cover sequence is the same unimodal permutation, i.e.\ a path consisting of $d+1$ edges (and diameter $d+1$). Moreover, this path is the only optimal plane tree spanning the flat arc because of \cref{thm:convex} and the rearrangement inequality; see the argument leading to (\ref{eq:rearrangement}) in the proof of \cref{thm:caterpillars}. Therefore, for any other plane spanning tree $T\ne\Topt$, be it a zigzagging caterpillar or not, must have a length that is an integer less than $|\Topt|$. Using that $|\Topt|=\sum_{i=1}^{d+1} i^2= \frac16(d+1)(d+2)(2d+3)= \frac13d^3+o(d^3)$ we obtain \[ \bd(d)\le \frac{|\Topt| - 1}{|\Topt|} = 1- \frac{6}{(d+1)(d+2)(2d+3)}. \qedhere \] \end{proof} When $d=3$,~\cref{thm:diameter-bound} gives $\bd(3)\le 29/30$. By tailoring the point set size, the gap sequence $\{g_i\}_{i=1}^m$, and by considering flat convex sets that are not arcs we improve the bound to $\bd(3)\le 5/6$. \thmdiameterthreebound* \begin{proof} Consider a flat point set $\mathcal{P}_{4k+2}$ consisting of two flat arcs symmetric with respect to a horizontal line, each with a gap sequence \[(\underbrace{1,\dots,1}_{k\times}, \ 2k+1,\ \underbrace{1,\dots,1}_{k\times}). \] In other words, $\mathcal{P}_{4k+2}$ consists of two diametrically opposite points, four unit-spaced arcs of $k$ points each, and a large gap of length $2k+1$ in the middle (see~\cref{fig:diameter-3}). \begin{figure}[h] \center \includegraphics{figures/flat-diameter-3.pdf} \caption{An illustration of the point set $\mathcal{P}_{4k+2}$ when $k=3$ with a tree $T_L$ (red).} \label{fig:diameter-3} \end{figure} On one hand, straightforward counting gives $|\Topt|\ge |T_L|=12k^2+6k+1$, where $T_L$ is the tree depicted in~\cref{fig:diameter-3}. On the other hand, we claim that any tree $T$ with diameter at most $3$ has length at most $10k^2+6k+1$. Thus \[ \bd(3)\le \frac{10k^2+6k+1}{12k^2+6k+1}, \] which tends to $5/6$ as $k\to\infty$. In the rest of this proof we will show that the longest tree \(T\) among those with diameter at most \(3\) on $\mathcal{P}_{4k+2}$ has length at most \(10k^2+6k+1\). First, note that as \(T\) has diameter at most \(3\) it is either a star or it has a cut edge \(ab\) whose removal decomposes \(T\) into a star rooted at \(a\) and a star rooted at \(b\). To add the lengths of the edges of the tree, we will often split the edges across the large gap into two parts: one part contained within the left or the right part and with maximum length $k$, and one part going across the large gap, with a length between $2k+1$ and $2k+1+k=3k+1$. If $T$ is a star, then without loss of generality we can assume that its root $a$ is to the left of the large gap. Denote the distance from the large gap to $a$ by $i$ (we have $0\le i\le k$). Straightforward algebra (see~\cref{fig:flatstar}) then gives \begin{align*} |S_a| &= (k-i)^2+i(i+1) \ +\ (2k+1)\cdot (i+2k+1) \ +\ k^2 \\ &\le k(k+1) \ +\ (2k+1)(3k+1)\ +\ k^2 \\ &= 8k^2 + 6k +1. \end{align*} \begin{figure}[h] \center \includegraphics[page=2]{figures/flat-star.pdf} \caption{The longest star for \(\mathcal{P}_{4k+2}\) is short. } \label{fig:flatstar} \end{figure} Now suppose $T$ has diameter $3$ and denote its cut edge by $ab$. If $ab$ is vertical then $|T|=|S_a|$ and the above bound applies. In the remaining cases, without loss of generality we can assume that $a$ is to the left of $b$. The line $ab$ then splits the remaining points of $\mathcal{P}_{4k+2}$ into two arcs -- one above $ab$ and the other one below it. We claim that in the longest tree with diameter $3$, the points of one arc are either all connected to $a$ or all to $b$: For the sake of contradiction, fix an arc and suppose \(c\) is the rightmost point connected to \(a\). Then by the choice of \(c\) everything right of it is connected to \(b\) and by convexity everything to the left of \(c\) is connected to \(a\). Let \(\ell\) be the vertical line through the midpoint of \(ab\). If \(c\) lies to the left of \(\ell\), moving \(c\) to the left increases the length of the tree as the distance to \(b\) for all points left of \(\ell\) is larger than the distance to \(a\). Otherwise, moving it to the right increases the length of the tree. Thus we either have \(c=a\) or \(c=b\) as claimed. \begin{figure} \center \includegraphics{figures/flat-uniform2.pdf} \caption{Points on one side of $ab$ are either all connected to $a$ or all to $b$. } \label{fig:flatunif2} \end{figure} Since $\mathcal{P}_{4k+2}$ is centrally symmetric and we have already dealt with the case when $T$ is a star, we can without loss of generality assume that all points above $ab$ are connected to $a$ and all points below $ab$ are connected to $b$. Now suppose that $a$ is below the diameter line $\ell'$ of $\mathcal{P}_{4k+2}$ and consider the reflection $a'\in\mathcal{P}_{4k+2}$ of $a$ about $\ell'$. Then the tree $T'$ with cut edge $a'b$ is longer than $T$, since in $T'$ the points to the left of $aa'$ are connected to $b$ rather than to $a$ and all the other edges have the same length (see~\cref{fig:diam3bound:first}). Hence we can assume that $a$ lies above $\ell'$ (or on it). Similarly, $b$ lies below $\ell'$ or on it. \begin{figure} \centering \includegraphics{figures/flat-abelow.pdf} \caption{Flipping \(a\) to \(a'\) increases the total length.} \label{fig:diam3bound:first} \end{figure} It remains to distinguish two cases based on whether $a$ and $b$ lie on different sides of the large gap or not. Either way, denote the distance from the gap to $a$ and $b$ by $i$ and $j$, respectively. In the first case, considering the subdivision of the edges as sketched in \cref{fig:flatboundcase1}, straightforward algebra gives: \begin{figure} \centering \begin{subfigure}[t]{0.49 \textwidth} \includegraphics{figures/flat-situtations.pdf} \caption{Decomposition of the edges for case 1.} \label{fig:flatboundcase1} \end{subfigure} \begin{subfigure}[t]{0.49 \textwidth} \includegraphics[page=2]{figures/flat-situtations.pdf} \caption{Decomposition of the edges for case 2.} \label{fig:flatboundcase2} \end{subfigure} \caption{Decomposition of the edges for the upper bounds.} \end{figure} \begin{align*} |T| &= k^2 \ +\ (2k-j)(i+2k+1) \ +\ (i+2k+1+j) \ +\ (2k-i)(2k+1+j) \ +\ k^2 \\ &= 10k^2+6k+1 -2ij \le 10k^2+6k+1 \end{align*} with equality if and only if either $a$ or $b$ (or both) lie on the boundary of the large gap. In the second case, since $a$ is to the left of $b$ we have $i>j$ and similar algebra, see \cref{fig:flatboundcase2}, gives \[|T| = (k^2-2kj+i+2ij) \ +\ (2k+1)(2k+1+i) \ +\ k^2. \] Since the right-hand side is increasing in $i$ and $i\le k$, we get \[|T|\le (k^2+k) + (2k+1)(3k+1) + k^2 = 8k^2 + 6k+1 \] which is less than the claimed upper bound $10k^2+6k+1$ by a margin. \end{proof} \section{Conclusions} We leave several open questions: \begin{enumerate} \item What is the correct approximation factor of the algorithm \texttt{AlgSimple($\mathcal{P}$)} presented in \cref{sec:approximation}? While each single lemma in \cref{sec:approximation} is tight for some case, it is hard to believe that the whole analysis, leading to the approximation factor $f\doteq 0.5467$, is tight. We conjecture that the algorithm has a better approximation guarantee. \item What is the approximation factor $\bd(3)$ achieved by the polynomial time algorithm that outputs the longest plane tree with diameter 3? By~\cref{thm:diameter-3-bound} it is at most $5/6$ (and by~\cite{AlonRS95} it is at least $1/2$). \item For a fixed diameter $d\ge 4$, is there a polynomial-time algorithm that outputs the longest plane tree with diameter at most $d$? By~\cref{thm:dp} we know the answer is yes when $d=3$. And \cref{thm:tristar} gives a positive answer for special classes of trees with diameter \(4\). Note that a hypothetical polynomial-time approximation scheme (PTAS) has to consider trees of unbounded diameter because of \cref{thm:diameter-bound}. It is compatible with our current knowledge that computing an optimal plane tree of diameter, say, $\mathcal{O}(1/\varepsilon)$ would give a PTAS. \item Is the general problem of finding the longest plane tree in P? A similar question can be asked for several other plane objects, such as paths, cycles, matchings, perfect matchings, or triangulations. The computational complexity in all cases is open. \end{enumerate} \section{Polynomial time algorithms for special cases}\label{sec:dp} In \cref{subsec:dpbistar} we show that the longest plane tree of diameter at most $3$ can be computed in polynomial time. Such a tree may be relevant in providing an approximation algorithm with a better approximation factor, but its computation is not trivial, even in the case of flat point sets. In \cref{sec:diam4} we show how to compute in polynomial time a longest plane tree among those of the following form: all the points are connected to three distinguished points on the boundary of the convex hull. Again, such a tree may play an important role in designing future approximation algorithms, as intuitively it seems to be better than the three stars considered in our previous approximation algorithm, when there is a point in the far region. \subsection{Finding the longest tree of diameter 3}\label{subsec:dpbistar} For any two points \(a,b\) of $\mathcal{P}$, a \emph{bistar rooted} at \(a\) and \(b\) is a tree that contains the edge $ab$ and where each point in \(\mathcal{P} \setminus \{ a,b\} \) is connected to either $a$ or $b$. Note that stars are also bistars. In this section we prove the following theorem. \thmdp* \begin{proof} Note that each bistar has diameter at most 3. Conversely, each tree with diameter three has one edge \(uv\) where each point \(p\in \mathcal{P}\) has distance at most \(1\) to either \(u\) or \(v\). It follows that all trees with diameter at most three are bistars. In \cref{lem:bestbistar} we show that for any two fixed points \(a\), \(b\), the longest plane bistar rooted at \(a\) and \(b\) can be computed in time \(\mathcal{O}(n^2)\). By iterating over all possible pairs of roots and taking the longest such plane bistar, we find the longest plane spanning tree with diameter at most \(3\) in time \(\mathcal{O}(n^4)\). \end{proof} We now describe the algorithm used to find the longest plane bistar rooted at two fixed points \(a\) and \(b\). Without loss of generality we can assume that the points \(a\) and \(b\) lie on a horizontal line with $a$ to the left of $b$. Furthermore, as we can compute the best plane bistar above and below the line through \(a\) and \(b\) independently, we can assume that all other points lie above this horizontal line. In order to solve this problem by dynamic programming, we consider a suitable subproblem. \begin{figure} \centering \includegraphics[page=1]{figures/dp_bistar.pdf} \caption{Two examples of valid pairs $p,q$ with their quadrilaterals $Q(p,q)$ shaded.} \label{fig:dp_bistar_subproblem} \end{figure} The subproblems considered in the dynamic program are indexed by an ordered pair $p,q$ of different points of $\mathcal{P}$ such that the edges $ap$ and $bq$ do not cross. A pair $p,q$ satisfying these condition is a \emph{valid pair}. For each valid pair $p,q$, note that the segments $ap$, $pq$, $qb$ and $ba$ form a simple (possibly non-convex) polygon. Let $Q(p,q)$ be the portion of this polygon below the horizontal line $y=\min \{y(p),y(q)\}$, as shown in \cref{fig:dp_bistar_subproblem}. We define the value \(Z(p,q)\) to be the length of the longest plane bistar rooted at \(a\) and \(b\) on the points in the interior of $Q(p,q)$, without counting $\Vert ab\Vert$. If there are no points of $\mathcal{P}$ within the quadrilateral $Q(p,q)$, we set \(Z(p,q) = 0\). Consider the case when the quadrilateral $Q(p,q)$ contains some points, and let \(k_{p,q}\) be the highest point of $\mathcal{P}$ inside of $Q(p,q)$. Then we might connect \(k_{p,q}\) either to \(a\) or to \(b\). By connecting it to \(a\), we force all points in the triangle \(L_{p,q}\) defined by the edges \(ap\) and \(ak_{p,q}\) and the line $y=y(k_{p,q})$, to be connected to \(a\). Similarly, when connecting \(k_{p,q}\) to \(b\), we enforce the triangle \(R_{p,q}\) defined by \(bq\), \(bk_{p,q}\) and the line $y=y(k_{p,q})$. See \cref{fig:dp_bistar_recurrence} for an illustration. In the former case we are left with the subproblem defined by the valid pair $k_{p,q},q$, while in the latter case we are left with the subproblem defined by the valid pair $p,k_{p,q}$. Formally, for each valid pair $p,q$ we have the following recurrence: \begin{align*} Z(p,q)=\begin{cases} 0 & \text{if no point of $\mathcal{P}$ is in $Q(p,q)$,}\\ \max \begin{cases} Z(k_{p,q},q)+ \Vert ak_{p,q}\Vert + \sum_{l\in L_{p,q}} \Vert al \Vert\\ Z(p,k_{p,q})+ \Vert bk_{p,q}\Vert + \sum_{r\in R_{p,q}} \Vert br \Vert \end{cases} & \text{otherwise.} \end{cases} \end{align*} \begin{figure} \centering \includegraphics[page=2]{figures/dp_bistar.pdf} \caption{Fixing \(k_{p,k}\) gives two possible triangular regions where edges are fixed.} \label{fig:dp_bistar_recurrence} \end{figure} \begin{lemma}\label{lem:bistarcorrect} Using \(Z(p,q)\) for all valid $p,q$ we can find a best plane bistar rooted at \(a\) and \(b\). \end{lemma} \begin{proof} Consider a fixed best plane bistar and assume, without loss of generality, that the highest point is connected to $a$; the other case is symmetric. Let $q^*$ be the highest point that is connected to $b$; if $q^*$ does not exist then the bistar degenerates to a star rooted at $a$. This means that all the points above $q^*$ are attached to $a$. Let $p^*$ be the point above $q^*$ that, circularly around $a$, is closest to $ab$. See \cref{fig:dp_bistar_p*}. Note that $p^*,q^*$ is a valid pair and all the points above $q^*$ are to the left of $ap^*$. For $p\in \mathcal{P}$, denote by $L_p$ the set of points in $\mathcal{P}$ that, circularly around $a$, are to the left of $ap$. Similarly, denote by $R_q$ the set of points in $\mathcal{P}$ below $q$ and to the right of $bq$, when sorted circularly around $b$. See \cref{fig:dp_bistar_p*}, right. The length of this optimal plane bistar rooted at \(a\) and \(b\) is then \[ \left(\sum_{l\in L_{p^*}}\Vert al\Vert \right) + \left(\sum_{r\in R_{q^*}}\Vert br\Vert\right) + \Vert ap^*\Vert + \Vert bq^*\Vert + \Vert ab\Vert + Z(p^*,q^*). \] On the other hand, each of the values of the form \begin{equation} \left(\sum_{l\in L_p}\Vert al\Vert\right) + \left(\sum_{r\in R_q}\Vert br\Vert\right) + \Vert ap\Vert + \Vert bq\Vert + \Vert ab\Vert + Z(p,q), \label{eq:dp1} \end{equation} where $p$, $q$ is a valid pair of points such that $y(p)>y(q)$, is the length of a plane, not necessarily spanning, bistar rooted at \(a\) and \(b\). (It is not spanning, if there is some point above \(q\) and right of \(ap\).) Taking the maximum of \(|S_a|\) and equation (\ref{eq:dp1}) over the valid pairs $p,q$ such that $y(p)>y(q)$ gives the longest plane bistar for which the highest point is connected to \(a\). A symmetric formula gives the best plane bistar if the highest point is connected to \(b\). Taking the maximum of both cases yields the optimal value. \begin{figure} \centering \includegraphics[page=3]{figures/dp_bistar.pdf} \caption{Left: The point $p^*$ is the point of $\mathcal{P}$ in the shaded region that is angularly around $a$ closest to $q^*$. Right: the regions $L_{p^*}$ and $R_{q^*}$ are shaded. The region with bars is empty.} \label{fig:dp_bistar_p*} \end{figure} The actual edges of the solution can be backtracked by standard methods. \end{proof} \begin{lemma}\label{lem:bestbistar} The algorithm described in the proof of \cref{lem:bistarcorrect} can be implemented in time \(\mathcal{O}(n^2)\). \end{lemma} \begin{proof} A main complication in implementing the dynamic program and evaluating (\ref{eq:dp1}) efficiently is finding sums of the form $\sum_{l\in \Delta\cap \mathcal{P}} \Vert al\Vert$ or $\sum_{r\in \Delta\cap \mathcal{P}} \Vert br\Vert$, and the highest point in $\Delta\cap \mathcal{P}$, where $\Delta$ is a query triangle (with one vertex at $a$ or $b$). These type of range searching queries can be handled using standard data structures~\cite{ColeY84,Matousek93}: after preprecessing $\mathcal{P}$ in time \(\mathcal{O}(n^2 \polylog n)\), any such query can be answered in \(\mathcal{O}(\polylog n)\) time. Noting that there are \(\mathcal{O}(n^2)\) such queries, a running time of \(\mathcal{O}(n^2 \polylog n)\) is immediate. However exploiting our specific structure and using careful bookkeeping we can get the running time down to \(\mathcal{O}(n^2)\). As a preprocessing step, we first compute two sorted lists \(\mathcal{L}_a\) and \(\mathcal{L}_b\) of \(\mathcal{P} \setminus \{a,b\}\). The list \(\mathcal{L}_a\) is sorted angular at \(a\) and \(\mathcal{L}_b\) is sorted by the angle at \(b\). The values $\sum_{l\in L_p}\Vert al\Vert$ and $\sum_{r\in R_q}\Vert br\Vert$ (as depicted in \cref{fig:dp_bistar_p*}) for all $p,q\in \mathcal{P}$ can be trivially computed in \(\mathcal{O}(n^2)\) time: there are \(\mathcal{O}(n)\) such values and for each of them we can scan the whole point set to explicitly get $L_p$ or $R_q$ in \(\mathcal{O}(n)\) time. There are faster ways of doing this, but for our result this suffices. Assuming that the values $Z(p,q)$ are already available for all valid pairs $p$, $q$, we can evaluate (\ref{eq:dp1}) in constant time. For any two points $p$, $q$ we check whether they form a valid pair and whether $y(p)>y(q)$ in constant time. We can then either evaluate (\ref{eq:dp1}) or the symmetric formula again in constant time. Thus, in \(\mathcal{O}(n^2)\) time we obtain the optimal solution. It remains to compute the values $Z(p,q)$ for all valid pairs $p$, $q$. First, we explain how to compute all the triples of the form $(p,q,k_{p,q})$ for all valid pairs $p,q$ in \(\mathcal{O}(n^2)\) time. Then we group these triples in a clever way to implement the dynamic program efficiently. We focus on the triples with $y(p)< y(q)$ and show how to find the triples of the form $(p,\cdot,\cdot)$ for a fixed \(p\). The case with \(y(p)> y(q)\) and a fixed \(q\) is symmetric. Let $W$ be the points of $\mathcal{P}$ to the right of the ray $bp$ above the horizontal line $y=y(p)$. Furthermore let $K$ be the points of $\mathcal{P}$ to the right of $ap$ and with $y$ coordinate between $y(a)$ and $y(p)$. An illustration of \(W\) and \(K\) can be found in \cref{fig:dp_bistar_W}. Any point $q$ with $y(q)>y(p)$ forms a valid pair $p,q$ if and only if $q$ lies in $W$. The point $k_{p,q}$ must lie in $K$ by its definition. \begin{figure} \centering \includegraphics[page=4]{figures/dp_bistar.pdf} \caption{Left: The regions defining $W$ and $K$ for fixed $a$, $b$ and $p$.} \label{fig:dp_bistar_W} \end{figure} We use \(\mathcal{L}_b\) to find the triples \((p,\cdot, \cdot)\). We iterate through the list in clockwise order starting at the ray \(ba\) and keep track of the highest \(k^* \in K\) encountered so far. If the current point lies in \(\mathcal{P} \setminus (K\cup W)\) we simply skip it. If the current point lies in \(K\) we update \(k^*\) if necessary. Finally, if the current point lies in \(W\), we report the triple \((p,q,k^*=k_{p,q})\). For a fixed \(p\) we only iterate \(\mathcal{L}_b\) once. Thus, for this fixed \(p\) the running time for finding all triples \((p,q,k_{p,q})\) with \(p,q\) forming a valid pair and \(y(p)<y(q)\) is \(\mathcal{O}(n)\). By the procedure we just described and its symmetric procedure on all \(p\in \mathcal{P} \setminus \{a,b\}\) we find all the triples $(p,q,k_{p,q})$ where $p,q$ is a valid pair in overall \(\mathcal{O}(n^2)\) time. To compute $Z(p,q)$ for all valid pairs using dynamic programing, we also need to compute the corresponding values $\sum_{l\in L_{p,q}} \Vert al\Vert$ and $\sum_{r\in R_{p,q}} \Vert br\Vert$. Refer to \cref{fig:dp_bistar_recurrence} to recall the definition of \(L_{p,q}\) and \(R_{p,q}\). For the following procedure we shift the focus to the point \(k\). For each point $k\in \mathcal{P}\setminus \{a,b\}$ we collect all triples $(p,q,k=k_{p,q})$, and compute the sums $\sum_{l\in L_{p,q}} \Vert al\Vert$ and $\sum_{r\in R_{p,q}} \Vert br\Vert$ in linear time for each fixed $k$, as follows. We concentrate on the first type of sum, $\sum_{l\in L_{p,q}} \Vert al\Vert$, where $q$ has no role, as the sum is defined by $p$ and $k$. For the following description we assume that \(\mathcal{L}_a\) is sorted in counterclockwise order. We create a (sorted) subsequence \(\mathcal{L}_a^k\) of \(\mathcal{L}_a\) containing only the points with \(y\) coordinate below \(y(k)\) and an angle at \(a\) larger than \(\sphericalangle bak\). We iterate over the elements of \(\mathcal{L}_a\), starting at the successor of \(k\). While iterating we maintain the last element from \(\mathcal{L}_a^k\) we have seen and the prefix sum \(\sum_{l} \Vert al \Vert\) of all points \(l\) in \(\mathcal{L}_a^k\) we encountered so far. When advancing to the next point \(p\) in \(\mathcal{L}_a\) there are two possibilities. If \(p\) also lies in \(\mathcal{L}_a^k\) we advance in \(\mathcal{L}_a^k\) and update the prefix sum. Otherwise, we can report \(\sum_{l\in L_{p,q'}}\Vert al \Vert\) to be the current prefix sum for all \(q'\) in a triple \((p,q',k)\). For any fixed \(k\) this needs at most two iterations through the list \(\mathcal{L}_a\) and can thus be executed in \(\mathcal{O}(n)\) time. A symmetric procedure can be carried out for \(\sum_{r\in R_{p,q}} \Vert br \Vert\) using \(\mathcal{L}_b\). As in the case for finding the triples, this results in \(\mathcal{O}(n^2)\) overall time to compute all relevant sums $\sum_{l\in L_{p,q}} \Vert al\Vert$ and $\sum_{r\in R_{p,q}} \Vert br\Vert$. Now we can implement the dynamic program in the straightforward way. Using the precomputed information we spend \(\mathcal{O}(1)\) time for each value \(Z(p,q)\), for a total running time of \(\mathcal{O}(n^2)\). \end{proof} \subsection{Extending the approach to special trees of diameter 4} \label{sec:diam4} Now we show how we can extend the ideas to get a polynomial time algorithm for special trees with diameter \(4\). Given three points \(a,b,c\) of $\mathcal{P}$, a \emph{tristar rooted} at \(a,b\) and \(c\) is a tree such that each edge has at least one endpoint at $a$, $b$ or $c$. We show the following: \thmtristar* \begin{proof} Let \(a,b,c\) be the specified points on the boundary of the convex hull of \(\mathcal{P}\). We have to compute the longest plane tristar rooted at \(a,b\) and \(c\). We assume, without loss of generality, that the edges \(ac\) and \(bc\) are present in the tristar; the other cases are symmetric. We further assume that \(a\) and \(b\) lie on a horizontal line, with $a$ to the left of $b$. The regions to the left of \(ac\) and to the right of \(bc\), as depicted in \cref{fig:tristarexclude}, can be solved independently of the rest of the instance. Indeed, the presence of the edges \(ac\) and \(bc\) blocks any edge connecting a point in one of those regions to a point outside the region. Each one of these regions can be solved as plane bistars, one rooted at $a,c$ and one rooted at $b,c$. It remains to solve the problem for the points enclosed by $ac$, $cb$ and the portion of the boundary of the convex hull from $b$ to $a$ (clockwise). Let $Q$ be this region. The problem for $Q$ can also be solved independently of the other problems. We assume for the rest of the argument that all points of $\mathcal{P}$ are in $Q$. \begin{figure} \centering \includegraphics{figures/tristarexclude.pdf} \caption{The regions cut off by \(ac\) and \(bc\) can be solved independently as bistars.} \label{fig:tristarexclude} \end{figure} For solving the problem for $Q$ we will use a variation of the dynamic programming approach for bistars. For any two points $p,q$ of $\mathcal{P}$, let us write $p\preceq_c q$ when in the counterclockwise order around $c$ we have the horizontal ray through $c$ to the left, then $cp$ and then $cq$ or the segments $cp$ and $cq$ are collinear. (Since we assume general position, the latter case occurs when $p=q$.) The subproblems for the dynamic program are defined by a five tuple $(p,p',r,q',q)$ of points of $\mathcal{P}$ such that \begin{itemize} \item $p'$ and $q'$ are distinct; \item $p\preceq_c p'\preceq_c r \preceq_c q'\preceq_c q$; and \item $p'$ and $q'$ are contained in the closed triangle $cpq$. \end{itemize} One such five tuple is a \emph{valid tuple}, see \cref{fig:ds-tristar1}. Note that the first and the second condition imply that $ap$ and $bq$ do not cross. Some of the points may be equal in the tuple; for example we may have $p=p'$ or $p'=r$ or even $p=p'=r$. For each valid tuple $(p,p',r,q',q)$, let $Q(p,r,q)$ be the points of $\mathcal{P}$ contained in $Q$ below the polygonal path $ap$, $pq$ and $qb$, and below the horizontal line through the lowest of the points $p,q,r$. Note that the point $r$ is used only to define the horizontal line. \begin{figure} \centering \includegraphics[page=1,width=\textwidth]{figures/dp-tristar.pdf} \caption{Two examples of valid tuples $(p,p',r,q',q)$ with the region $Q(p,r,q)$ shaded. Each $Q(p,r,q)$ is split into 3 regions telling, for each of them, which roots can be used for that region.} \label{fig:ds-tristar1} \end{figure} For each valid tuple $(p,p',r,q',q)$, we define $Z(p,p',r,q',q)$ as the length of the optimal plane tristar rooted at $a$, $b$, $c$ for the points in the interior of $Q(p,r,q)$, without counting $\Vert ac\Vert+\Vert bc\Vert$, and with the additional restriction that a point $k$ can be connected to $c$ only if $p'\preceq_c k\preceq_c q'$. This last condition is equivalent to telling that no edge incident to \(c\) in the tristar can cross $ap'$ or $bq'$. Thus, we are looking at the length of the longest plane graph in which each point in the interior of $Q(p,r,q)$ must be connected to either $a$, $b$ or $c$, and no edge crosses $ap'$ or $bq'$. If $Q(p,r,q)$ has no points, then $Z(p,p',r,q',q)=0$. If $Q(p,r,q)$ has some point, we find the highest point \(k= k(p,r,q)\) in \(Q(p,r,q)\) and consider how it may attach to the roots and which edges are enforced by each of these choices. We can always connect \(k \) to \(a\) or \(b\), as \(Q(p,r,q)\) is free of obstacles. If $p'\preceq_c k \preceq_c q'$, then we can connect $k$ to $c$. If $k$ is connected to $c$ it only lowers the boundary of the region $Q(\cdot,\cdot,\cdot)$ that has to be considered. However if \(k\) is connected to \(a\) or \(b\), it splits off independent regions, some of them can be attached to only one of the roots, some of them are essentially a bistar problem rooted at $c$ and one of $a,b$. To state the recursive formulas precisely, for a region $R$ and roots $z,c$, let \(\mathrm{BS}_{z,c}(R)\) be the length of the optimal plane bistar rooted at $z,c$ for the points in $R$. Such a value can be computed using \cref{lem:bistarcorrect}. Formally the recurrence for $Z(p,p',r,q',q)$ looks as follows. If $Q(p,r,q)$ is empty, then $Z(p,p',r,q',q)=0$. If $Q(p,r,q)$ is not empty, let $k$ be the highest point of $Q(p,r,q)$; we have three subcases: \begin{description} \item[Case 1: $k\prec_c p'$.] Let $L$ be the points of $Q(p,r,q)$ above $ak$. Let \(B\) be the points of \(Q(p,r,q)\) below \(bk\) and let \(G\) be the points \(t\) of \(Q(p,r,q)\setminus B\) such that $k\prec_c t \prec_c p'$. Let \(g\) be the point with largest angle at \(b\) among the points in \(G\). Then we define \(R'\) to be the set of all points \(t\) in \(Q(p,r,q) \setminus B\) with $p'\prec_c t \prec_c q'$ which are above \(gb\). Finally let \(R = Q(p,q,r) \setminus (B\cup R')\), as shown in \cref{fig:ds-tristar2}. We get the following recurrence in this case: \[ Z(p,p',r,q',q) = \max\begin{cases} Z(k,p',r,q',q) + \Vert ak \Vert + \sum_{l\in L} \Vert al \Vert\\ \mathrm{BS}_{a,b}(B)+\Vert bk \Vert + \mathrm{BS}_{b,c}(R') + \sum_{r\in R} \Vert br \Vert \end{cases} \] \item[Case 2: $p' \prec_c k\prec_c q'$.] Let $L'$ be the points $t$ of $Q(p,r,q)$ above $ak$ such that $t\prec_c p'$ and let $L$ be the points $t$ of $Q(p,r,q)$ above $ak$ such that $p'\prec_c t \prec_c k$. Furthermore, let $R$ be the points $t$ of $Q(p,r,q)$ above $bk$ such that $k\prec_c t \prec_c q'$, and let $R'$ be the points $t$ of $Q(p,r,q)$ above $bk$ such that $q' \prec_c t$; see \cref{fig:ds-tristar3}. We get the following recurrence in this case: \[ Z(p,p',r,q',q) = \max\begin{cases} Z(p,p',k,q',q) + \Vert ck\Vert \\ Z(k,k,k,q',q) + \Vert ak \Vert + \mathrm{BS}_{a,c}(L) + \sum_{l\in L'} \Vert al \Vert\\ Z(p,p',k,k,k) + \Vert bk \Vert + \mathrm{BS}_{b,c}(R) + \sum_{r\in R'} \Vert br \Vert \end{cases} \] \item[Case 3: $q'\prec_c k$.] The case is symmetric to the case $k\prec_c p'$. \end{description} \begin{figure} \centering \includegraphics[page=2,,width=\textwidth]{figures/dp-tristar.pdf} \caption{The two cases in the recurrence when $k\prec_c p'$.} \label{fig:ds-tristar2} \end{figure} \begin{figure} \centering \includegraphics[page=3]{figures/dp-tristar.pdf} \caption{One of the cases in the recurrence when $p' \prec_c k\prec_c q'$.} \label{fig:ds-tristar3} \end{figure} \begin{figure} \centering \includegraphics[page=4]{figures/dp-tristar.pdf} \caption{Starting Case} \label{fig:ds-tristar4} \end{figure} The values $Z(p,p',r,q',q)$ for all valid tuples $(p,p',r,q',q)$ can be computed using dynamic programming and the formulas described above. The dynamic program is correct by a simple but tedious inductive argument. Note that we have to compute a few solutions for bistars. In the recursive calls these have the form $\mathrm{BS}_{z,c}(R)$ for \(z\in \{a,b\}\) and some region \(R\) of constant size description. More precisely, each such region is defined by two points of $\mathcal{P}$ (case of $L$ in \cref{fig:ds-tristar3}) or by four points of $\mathcal{P}$ (case of $R$ in \cref{fig:ds-tristar2}, where it is defined by $k,g,q',q$). Thus, we have $\mathcal{O}(n^4)$ different bistar problems, and each of them can be solved in polynomial time using \cref{lem:bistarcorrect}. To compute the optimal plane tristar, we add three dummy points to $\mathcal{P}$ before we start the dynamic programming. We add a point $c_a$ on the edge $ac$ arbitrarily close to $c$, a point $c_b$ on the edge $bc$ arbitrarily close to $c$, and a point $c'$ between $c_a$ and $c_b$, see \cref{fig:ds-tristar4}. We perturb the points $c_a, c'$ and $c_b$ slightly to get them into general position. Note that \((c_a, c_a, c', c_b, c_b)\) is a valid tuple. We can now compute \(Z(c_a, c_a,c', c_b, c_b)\) by implementing the recurrence with standard dynamic programming techniques in polynomial time. By adding \(\Vert ac \Vert\), \(\Vert bc \Vert\) and the lengths of the independent bistars from \cref{fig:tristarexclude} to $Z(c_a,c_a,c',c_b,c_b)$, we get the length of the longest plane tristar rooted at \(a,b\) and \(c\). \end{proof} Similar to the proof \cref{thm:dp} we can iterate over all possible triples of specified points to find the best plane tristar rooted at the boundary of the convex hull. \subsection{Extending the approach to special trees of diameter 4} Now we show how we can extend the ideas to get a polynomial time algorithm for a more general situation. Given three points \(a,b,c\), a \emph{tristar} rooted at \(a,b\) and \(c\) is a tree, where all points are connected to either \(a,b\) or \(c\). We will now argue that we can compute the best tristar rooted at a triple of points on the boundary of the convex hull in polynomial time. As in \cref{subsec:dpbistar} we will use dynamic programming. However, before we can use the dynamic programming approach we have to do some precomputing steps. Assume that both \(a, b\) and \(c\) and the edges incident to two of these vertices are fixed. Without loss of generality assume that \(a\) and \(b\) lie on a horizontal line and that the fixed edges are \(ac\) and \(bc\). Note that everything cut off by the edges \(ac\) and \(bc\) is independent of the rest and can be solved by using the dynamic program described in \cref{subsec:dpbistar}, see \cref{fig:tristarexclude}. So now we only consider the remaining part of the point set. \begin{figure}[h] \centering \includegraphics{figures/tristarexclude.pdf} \caption{The light blue regions are independent from the remaining problem.} \label{fig:tristarexclude} \end{figure} So now assume that in addition to the fixed \(a\) and \(b\), we also correctly guessed the highest points \(p\) and \(q\) such that \(p\) is connected to \(a\) and \(q\) is connected to \(b\). Now that these edges are fixed, the current region decomposes into subregions, depending on which of the three roots are visible from within the regions. See \cref{fig:tristarregions} for an illustration. We call the choice of \(a,b,c,p\) and \(q\) together with the edges within \(\{a,b,c\}\) a \emph{starting configuration}. We now describe how to solve the problem for a fixed starting configuration. \begin{figure}[h] \centering \includegraphics{figures/tristarregions.pdf} \caption{The edges \(ap\) and \(bq\) subdivide the current region into visibility regions.} \label{fig:tristarregions} \end{figure} Note that edges from points below \(p\) and above the edge \(ap\) do not interfere with any other edges, so we can again find an optimal solution for these by using the dynamic program from \cref{subsec:dpbistar}. We can also already add the edges to regions only visible from or feasible for one vertex. Next we want to fix the edges in the horizontal strip defined by \(p\) and \(q\). We again guess a point. This time we guess the point \(k\) with largest \(x\)-coordinate which is connected to \(a\). This redefines the center region as can be seen in \cref{fig:tristarmiddle}. \begin{figure}[h] \centering \includegraphics[page=2]{figures/tristarmiddle.pdf} \caption{Fixing the rightmost point \(k\) connected to \(a\) gives easier to handle regions.} \label{fig:tristarmiddle} \end{figure} Now the part bounded by the vertical line through \(k\) and the region above the edge \(ak\) is again independent from the remaining regions and can be solved by using the dynamic program from above with roots \(a\) and \(c\). By a similar argument the parts above the edge \(qb\) are either uniquely determined to connect to \(b\) or are also independent from the remaining points and can thus be connected optimally by the dynamic program from above. Finally the remaining regions of the strip between \(p\) and \(q\) are uniquely determined and can therefore also been put into place. Let \(r\) be the lowest point connected to \(c\) in the horizontal strip between \(p\) and \(q\). Furthermore redefine \(p\) to be the lowest point below the edge \(ak\) but above the horizontal line through \(q\). Note that the triangle \(\Delta pqr\) does not contain any points and that all points above of the edges \(pa\) and \(qb\) are already, independently of the remaining points, connected to some point. Keeping the invariant that \(\Delta pqr\) is empty and that the points above the edges \(ap\) and \(bq\) are fixed we can now go to defining the dynamic programming part of our solution. The basic idea is similar to the dynamic program above. Given three points \(p,q,r\) such that the edges \(ap\), \(bq\) and \(cr\) are fixed, and the triangle \(\Delta pqr\) is empty, we want define \(P_{pqr}\) to be best spanning tree for the points in the truncated triangle defined by \(ap\) and \(bq\) and below the lowest point \(m\) of the three points. Let \(k\) be the highest point in the truncated triangle which lies below \(m\). If no such \(k\) exists, the value is simply \(0\). In the other case it can be determined recursively. See \cref{fig:tristarrecurrence} for the definition of the regions \(A, A', B\) and \(B'\). \begin{align*} P_{pqr}&=\max \begin{cases} P_{kqr} + \Vert ak \Vert + \mathrm{OPT}(A) + \sum_{l\in A'} \Vert la \Vert\\ P_{pkr} + \Vert bk \Vert + \mathrm{OPT}(B) + \sum_{l\in B'} \Vert lb \Vert \\ P_{pqk} + \Vert ck \Vert& \text{if } k \text{ is visible from } k \end{cases} \end{align*} Where \(A\) and \(B\) are again regions which are independent of the points which are still to be considered, so we can again use the dynamic program from \cref{subsec:dpbistar} to solve them. \begin{figure} \centering \includegraphics{figures/tristarrecurrence.pdf} \caption{The different cases for the recurrence} \label{fig:tristarrecurrence} \end{figure} To then get the overall optimal solution for fixed \(a,b\) and \(c\), the fixed edges between them and the fixed highest points connected to \(a\) or \(b\), we simply sum up the fixed edges from the preprocessing, the solution of \(P_{pqr}\) and the length of the edges \(ap\) and \(bq\). To find the overall best tristar we have to iterate over all possible triples on the convex hull and all possible edges between them. These are \(O(n^3)\) possibilities. For each of these possibilities we fix the two vertices above the non edge pair which are the highest. These are additional \(O(n^2)\) possible pairs. Furthermore we have to fix the rightmost \(k\) connected to \(a\) in the horizontal strip. So we run the program above for \(O(n^6)\) possible starting configurations. Filling out the table costs \(O(n^3)\) plus the time needed to compute the \(\mathrm{OPT}(A)\), so in a rough estimate overall \(O(n^5)\). The preprocessing steps also take a total of at most \(O(n^2)\) so overall we have \(O(n^5)\) running time for a fixed configurations. As this is needed for all \(O(n^6)\) starting configurations, we get a total running time of \(O(n^{11})\) which is polynomial. \katharina{We can probably this to \(O(n^4\) or even \(O(n^3)\) for filling out the table by considering how often each point is part in a \(O(n^2)\) independent computation.} \katharina{It is well possible that this idea could also be more or less easily extended to arbitrary tristars and not only those on the convex hull} \section{Preliminaries}\label{sec:preliminaries} Let \(\mathcal{P}\subset\R^2\) be a set of $|\mathcal{P}|=n$ points in the plane. Henceforth we assume that $\mathcal{P}$ is in general position: no three points are collinear. For any spanning tree \(T\) on \(\mathcal{P}\), we denote by \(|T|\) the Euclidean length of \(T\). Let \(\Topt\) be a plane (that is, noncrossing) spanning tree of maximum length for \(\mathcal{P}\). Similar to the existing algorithms~\cite{AlonRS95, DBLP:journals/dcg/DumitrescuT10,biniaz_maximum_2019,cabello2020better,biniaz2020improved}, we make extensive use of stars. The \emph{star} \(S_p\) rooted at some point \(p\in \mathcal{P}\) is the tree that connects \(p\) to all other points of \(\mathcal{P}\). At several places we talk about ``flat'' point sets. A point set $\mathcal{P}$ is \emph{flat} if $\operatorname{diam}(\mathcal{P})\ge 1$ and the $y$-coordinates of all its points are essentially negligible, meaning that their absolute values are bounded by an infinitesimal $\varepsilon>0$. For flat point sets, we can estimate the length of each edge as the difference between the $x$-coordinates of its endpoints, because the error can be made arbitrarily small by taking $\varepsilon\to 0$. Lastly, $D(p,r)$ refers to a closed disk with center $p$ and radius $r$, while $\partial D(p,r)$ is its boundary: a circle of radius $r$ centered at $p$. \section{Local improvements fail}\label{sec:stuck} In this section we prove that the following natural algorithm \texttt{AlgLocal($\mathcal{P}$)} based on local improvements generally fails to compute the longest plane tree. \noindent\textbf{Algorithm} \texttt{AlgLocal($\mathcal{P}$)}: \begin{enumerate} \item Construct an arbitrary plane spanning tree $T$ on $\mathcal{P}$. \item \textbf{While} there exists a pair of points $a$, $b$ such that $T\cup ab$ contains an edge $cd$ with $|cd|<|ab|$ and \(T \cup \{ab\} \setminus \{cd\}\) is plane: \begin{enumerate} \item Set $T\to T\cup \{ab\}\setminus\{cd\}$.\hfill \texttt{ // tree $T\cup ab\setminus\{cd\}$ is longer than $T$} \end{enumerate} \item Output $T$. \end{enumerate} \begin{lemma}\label{thm:stuck} For certain point sets $\mathcal{P}$ the algorithm \texttt{AlgLocal($\mathcal{P}$)} fails to compute the longest plane tree. \end{lemma} \begin{proof} We construct a point set \(\mathcal{P}\) consisting of \(9\) points to show the claim. The first three points of \(\mathcal{P}\) are the vertices of an equilateral triangle. We assume that two of these vertices are on a horizontal line and denote by \(x\) the center of this triangle. Let \(r_0\) be the circumradius of the triangle. Inside of this triangle, we want to place the vertices of two smaller equilateral triangles, where again the smaller is contained in the larger one. Set \(\alpha = 17^\circ, r_1 = \frac{2}{3} r_0\) and \(r_2 =\frac{1}{3} r_0\). We then place the first of the additional triangles on the circle \(\partial D(x, r_1)\) in a way that the vertices have an angle of \(\alpha\) to the nearest angular bisector of the outer triangle. We place the second additional triangle on the circle \(\partial D(x, r_2)\) again with an angle to the nearest bisector of the outer triangle. However this time, the angle is \(\alpha/2\). This construction is visualized in \cref{fig:stuckconst}. \begin{figure}[ht] \center \includegraphics[page=1]{figures/stuck2.pdf} \caption{Construction of the point set} \label{fig:stuckconst} \end{figure} Now consider the tree on this point set depicted by the solid edges in \cref{fig:stucktree}. Note that the green, blue and yellow edges are rotational symmetric. The edges depicted in purple in \cref{fig:stucktree} are representative for the possible edges currently not in the tree, which connect the outer to the inner triangle. However as they are either the smallest edges in the cycle or intersect some edge not in a cycle, the algorithm cannot choose \(ab\) to be one of those edges. \begin{figure}[ht] \begin{subfigure}[t]{0.45\textwidth} \center \includegraphics[page=2]{figures/stuck2.pdf} \caption{A tree which cannot be locally improved} \label{fig:stucktree} \end{subfigure} \hfill \begin{subfigure}[t]{0.45\textwidth} \center \includegraphics[page=3]{figures/stuck2.pdf} \caption{A tree where each pair of edges in the same color is at least as long as the matching pair in \cref{fig:stucktree}} \label{fig:stucklonger} \end{subfigure} \caption{The algorithm \texttt{AlgLocal($\mathcal{P}$)} can get stuck.} \label{fig:stuck} \end{figure} The possible edges connecting the outer to the middle triangle are depicted in red. The red edge \(pq \) is not in a cycle with the edge it crosses, and thus it is not a possible swap keeping planarity. For the second red edge and the possible edges connecting the middle to the inner triangle, it can similarly be seen that they are shorter than any edge of the current tree. Finally, for the edges along the triangles or the edges connecting the interior and the middle triangle, it can easily be verified that there will be no strictly smaller edge in the unique cycle closed by them. On the other hand, in the tree depicted in \cref{fig:stucklonger} each pair of same colored edges is longer than its counterpart in \cref{fig:stucktree}. Therefore \texttt{AlgLocal($\mathcal{P}$)} does not yield a correct result. \qedhere \end{proof}
{'timestamp': '2021-01-05T02:17:03', 'yymm': '2101', 'arxiv_id': '2101.00445', 'language': 'en', 'url': 'https://arxiv.org/abs/2101.00445'}
arxiv
\section{Introduction} Data augmentation has been shown effective for various natural language processing (NLP) tasks, such as machine translation \interalia{fadaee-etal-2017-data,gao-etal-2019-soft,xia-etal-2019-generalized}, text classification \citep{wei-zou-2019-eda,quteineh-etal-2020-textual}, semantic role labeling \citep{furstenau-lapata-2009-semi} and dialogue understanding \citep{hou-etal-2018-sequence,niu-bansal-2019-automatically}. Such methods enhance the diversity of the training set by generating examples based on existing ones and simple heuristics, and make the training process more consistent \citep{xie2019unsupervised}. Most existing work focuses on word-level manipulation \interalia{kobayashi-2018-contextual,wei-zou-2019-eda,dai-adel-2020-analysis} or global sequence-to-sequence style generation \citep{sennrich-etal-2016-improving}. In this work, we study a family of general data augmentation methods, substructure substitution (\textsc{Sub}$^2$), which generates new examples by same-label substructure substitution (Figure~\ref{fig:teaser}). \textsc{Sub}$^2${} naturally fits structured prediction tasks such as part-of-speech tagging and parsing, where substructures exist in the annotations of the tasks. For more general NLP tasks such as text classification, we present a variation of \textsc{Sub}$^2${} which (1) performs constituency parsing on existing examples, and (2) generates new examples by subtree substitution based on the parses. Different from other investigated methods which sometimes hurt the performance of models, we show through intensive experiments that \textsc{Sub}$^2${} helps models achieve competitive or better performance than training on the original dataset across tasks and original dataset sizes. When combined with pretrained language models \citep{conneau2019unsupervised}, \textsc{Sub}$^2${} establishes new state of the art results for low-resource part-of-speech tagging and sentiment analysis. The question of whether explicit parse trees can help neural network--based approaches on downstream tasks has been raised by recent work \citep{shi-etal-2018-tree,havrylov-etal-2019-cooperative} in which non-linguistic balanced trees have been shown to rival the performance of those from syntactic parsers. Our work shows that constituency parse trees are more effective than balanced trees as backbones for \textsc{Sub}$^2${} on text classification, especially when only few examples are available, introducing more potential applications for constituency parse trees in the neural network era. \section{Related Work} Data augmentation aims to generate new examples based on available ones, without actually collecting new data. Such methods reduce the cost of dataset collection, and usually boost the model performance on desired tasks. Most existing data augmentation methods for NLP tasks can be classified into the following categories: \\ \par\noindent\textbf{Token-level manipulation.} Token-level manipulation has been widely studied in recent years. An intuitive way is to create new examples by substituting (word) tokens with ones with the same desired features, such as synonym substitution \cite{zhang2015character,wang-yang-2015-thats,fadaee-etal-2017-data,kobayashi-2018-contextual} or substitution with words having the same morphological features \citep{silfverberg-etal-2017-data}. Such methods have been applied to generate adversarial or negative examples which help improve the robustness of neural network--based NLP models \interalia{belinkov2018synthetic,shi-etal-2018-learning,alzantot-etal-2018-generating,zhang-etal-2019-generating-fluent,min-etal-2020-syntactic}, or to generate counterfactual examples which mitigate bias in natural language \citep{zmigrod-etal-2019-counterfactual,lu2020gender}. Other token-level manipulation methods introduce extra noise such as random token shuffling and deletion \citep{wang-etal-2018-switchout,wei-zou-2019-eda}. Models trained on the augmented dataset are expected to be more robust to the considered noise. \\ \par\noindent\textbf{Label-conditioned text generation.} Recent work has explored generating new examples by training a conditional text generation model \interalia{bergmanis-etal-2017-training,liu-etal-2020-tell,ding-etal-2020-daga,liu-etal-2020-data}, or applying post-processing on the examples generated by pretrained models \citep{yang-etal-2020-generative,wan-etal-2020-improving,yoo-etal-2020-variational}. In the data augmentation stage, given labels in the original dataset as conditions, such models generate associated text accordingly. The generated examples, together with the original datasets, are used to further train models for the primary tasks. A representative among them is back-translation \citep{sennrich-etal-2016-improving}, which has been demonstrated effective on not only machine translation, but also style-transfer \cite{prabhumoye-etal-2018-style,zhang-etal-2020-parallel}, conditional text generation \citep{sobrevilla-cabezudo-etal-2019-back}, and grammatical error correction \citep{xie-etal-2018-noising}. Another group of work on example generation is to generate new examples based on predefined templates \cite{kafle-etal-2017-data,asai-hajishirzi-2020-logic}, where the templates are designed following heuristic, and usually task-specific, rules. \\ \par\noindent\textbf{Soft data augmentation.} In addition to explicit generation of concrete examples, soft augmentation, which directly represents generated examples in a continuous vector space, has been proposed: \citet{gao-etal-2019-soft} propose to perform soft word substitution for machine translation; recent work has adapted the mix-up method \citep{zhang2018mixup}, which augments the original dataset by linearly interpolating the vector representations of text and labels, to text classification \citep{guo2019augmenting,sun-etal-2020-mixup}, named entity recognition \citep{chen-etal-2020-local} and compositional generalization \citep{guo-etal-2020-sequence}. \\ \par\noindent\textbf{Structure-aware data augmentation.} Existing work has also sought potential gain from structures associated with natural language: \citet{xu-etal-2016-improved} improve word relation classification by dependency path--based augmentation. \citet{sahin-steedman-2018-data} show that subtree cropping and rotation based on dependency parse trees can help part-of-speech tagging for low-resource languages, while \citet{vania-etal-2019-systematic} has demonstrated that such methods also help dependency parsing when very limited training data is available. \textsc{Sub}$^2${} also falls into this category. The idea of same-label substructure substitution has improved over baselines on structured prediction tasks such as semantic parsing \citep{jia-liang-2016-data}, constituency parsing \citep{shi-etal-2020-role}, dependency parsing \citep{dehouck-gomez-rodriguez-2020-data}, named entity recognition \citep{dai-adel-2020-analysis}, meaning representation--based text generation \citep{kedzie-mckeown-2020-controllable}, and compositional generalization \citep{andreas-2020-good}. To the best of our knowledge, however, \textsc{Sub}$^2${} has not been systematically studied as a general data augmentation method for NLP tasks. In this work, we not only extend \textsc{Sub}$^2${} to part-of-speech tagging and structured sentiment classification, but also present a variation that allows a broader range of NLP tasks (e.g., text classification) to benefit from syntactic parse trees. We evaluate \textsc{Sub}$^2${} and several representative general data augmentation methods, which can be widely applied to various NLP tasks. When constituency parse trees are used, there is a connection between \textsc{Sub}$^2${} and tree substitution grammars \citep[TSGs;][]{schabes1990mathematical}, where the approach can be viewed as (1) estimating a TSG using the given corpus and (2) drawing new sentences from the estimated TSG. \section{Method} \label{sec:method} We introduce the general framework we investigate in Section~\ref{sec:sub}, and describe the variations of \textsc{Sub}$^2${} which can be extended to text classification and other NLP applications. \subsection{Substructure Substitution (\textsc{Sub}$^2$)} \label{sec:sub} As shown in Figure~\ref{fig:teaser}, given the original training set $\mathcal{D}$, \textsc{Sub}$^2${} generates new examples using same-label substructure substitution, and repeats the process until the training set reaches the desired size. The general \textsc{Sub}$^2${} procedure is presented in Algorithm~\ref{algo:sub}. \begin{algorithm}[ht] \SetAlgoLined \SetKwInOut{Input}{Output} \KwIn{Original dataset $\mathcal{D}$, \\ desired dataset size $N > |\mathcal{D}|$} \KwOut{Augmented dataset $\mathcal{D}'$} $\mathcal{D}' \leftarrow \mathcal{D}$; \\ \Repeat{$|\mathcal{D}'| = N$}{ Uniformly draw $s \in \textit{substructure}(\mathcal{D}')$ \\ $S \leftarrow \textit{example}(s)$ \\ Uniformly draw $u \in \{v \mid v \in \textit{substructure}(\mathcal{D}), \textit{label}(v) = \textit{label}(s), v\neq s\}$ \\ $S' \leftarrow$ replace $s$ with $v$ in $S$ \\ $\mathcal{D}' \leftarrow \mathcal{D}' \cup \{S'\}$ } \caption{\label{algo:sub} \textsc{Sub}$^2$. } \end{algorithm} For part-of-speech (POS) tagging, we let text spans be substructures and use the corresponding POS tag sequence as substructure labels (Figure~\ref{fig:pos}); for constituency parsing, we use subtrees as the substructures, with phrase labels as the substructure labels (Figure~\ref{fig:c-parse}); for dependency parsing, we also use subtrees as substructures, and let the label of dependency arc, which links the head of the subtree to its parent, be the substructure labels. \subsection{Variations of \textsc{Sub}$^2${} for Text Classification} \label{sec:var} Text classification examples do not typically contain explicit substructures. However, we can obtain them by viewing all text spans as substructures (Figure~\ref{fig:txt-class}). This approach may be too unconstrained in practice and could introduce noise during augmentation, so we consider constraining substitution based on matching several features of the spans: \begin{itemize} \item \textbf{Number of words} (\textsc{Sub}$^2$+\textsc{n}): when considering this constraint, we can only substitute a span with another having the same number of words; otherwise we can substitute a span with any other span. \item \textbf{Phrase or not} (\textsc{Sub}$^2$+\textsc{p}): when considering this constraint, we can only substitute a phrase with another phrase (according to a constituency parse of the text); otherwise the considered spans do not necessarily need to be phrases. \item \textbf{Phrase label} (\textsc{Sub}$^2$+\textsc{l}): this constraint is only applicable when also using \textsc{Sub}$^2$+\textsc{p}. When considering this constraint, we can only perform substitution between phrases with the same phrase label (from constituency parse trees). \item \textbf{Text classification label} (\textsc{Sub}$^2$+\textsc{t}): when considering this constraint, we can only substitute a span with another span that comes from text annotated with the same class label as the original one; otherwise we can choose the alternative from any example text in the training corpus. \end{itemize} We also investigate combinations of the above constraints, where we require all the involved substructures to be the same to perform \textsc{Sub}$^2$. For example, \textsc{Sub}$^2$+\textsc{t+n} (Figure~\ref{fig:txt-class}) requires the original and the alternative span to have the same text label and the same number of words. \section{Experiments} \label{sec:expr} We evaluate \textsc{Sub}$^2${} and other data augmentation baselines (Section~\ref{sec:expr-baseline}) on four tasks: part-of-speech tagging, dependency parsing, constituency parsing, and text classification. \subsection{Setup} For part-of-speech tagging and text classification, we add a two-layer perceptron on top of XLM-R \citep{conneau2019unsupervised} embeddings, where we calculate contextualized token embeddings by a learnable weighted average across layers. We use endpoint concatenation (i.e., the concatenation of the first and last token representation) to obtain fixed-dimensional span or sentence features, and keep the pretrained model frozen during training.\footnote{We did not observe any significant improvement by finetuning the large pretrained language model, and for most cases, the performance is much worse than the current scheme we apply. } For dependency parsing, we use the SuPar implementation of \citet{dozat2016deep}.\footnote{\url{https://github.com/yzhangcs/parser}} For constituency parsing, we use Benepar \citep{kitaev-klein-2018-constituency}.\footnote{\url{https://github.com/nikitakit/self-attentive-parser}} For all data augmentation methods, including the baselines (Section~\ref{sec:expr-baseline}), we only augment the training set, and use the original development set. If not specified, we introduce 20 times more examples than the original training set when applying an augmentation method. When introducing $k\times$ new examples, we also replicate the original training set $k$ times to ensure that the model can access sufficient examples from the original distribution. All models are initialized with the XLM-R base model \citep{conneau2019unsupervised} if not specified. We train models for 20 epochs when applying the high-resource setting (i.e., high-resource part-of-speech tagging, sentiment classification trained on the full training set) or when applying data augmentation methods, and for 400 epochs in the low-resource settings without augmentation; we select the one with the highest accuracy or $F_1$ score on the development set. All models are optimized using Adam \citep{kingma2015adam}, where we try learning rates in $\{5\times 10^{-4}, 5\times10^{-5}\}$. For hidden size (i.e., the hidden size of the perceptron for part-of-speech tagging and text classification, the dimensionality of span representation and scoring multi-layer perceptron for constituency parsing, and the dimensionality of token representation and scoring multi-layer perceptron for dependency parsing), we vary between $128$ and $512$. We apply a 0.2 dropout ratio to the contextualized embeddings in the training stage. All other hyperparameters are the same as the default settings in the released codebases. \subsection{Baselines} \label{sec:expr-baseline} We compare \textsc{Sub}$^2${} to the following baselines: \begin{itemize} \item \textbf{No augmentation} (\textsc{NoAug}), where the original training and development set are used. \item \textbf{Contextualized substitution} (\textsc{CtxSub}), where we apply contextualized augmentation \citep{kobayashi-2018-contextual}, masking out a random word token from the existing dataset, and use multilingual-BERT \citep[mBERT;][]{devlin-etal-2019-bert} to generate a different word. \item \textbf{Random shuffle} (\textsc{Rand}), where we randomly shuffle all the words in the original sentence, while keeping the original structured or non-structured labels. It is worth noting that for dependency parsing, we shuffle the words, while maintaining the dependency arcs between individual words; for constituency parsing, we shuffle the terminal nodes, and insert them back into the tree structure. Our \textsc{Rand}{} method for constituency parsing is arguably more noisy than that for dependency parsing. \end{itemize} For non-structured text classification tasks, we also introduce the following baselines: \begin{itemize} \item \textbf{Random word substitution} (\textsc{RandWord}), where we substitute a random word in an original example with another random word. This can be viewed as a less restricted version of \textsc{CtxSub}. \item \textbf{Binary balanced tree--based \textsc{Sub}$^2$} (\textsc{Sub}$^2$+\textsc{p}, balanced tree). \citet{shi-etal-2018-tree} argue that binary balanced trees are better backbones for recursive neural networks \citep{zhu2015long,tai-etal-2015-improved} on text classification. In this work, we present binary balanced tree as the backbone for \textsc{Sub}$^2${}: we (1) generate balanced trees by recursively splitting a span of $n$ words into two consecutive groups, which consist of $\left\lfloor\frac{n}{2}\right\rfloor$ and $\left\lceil\frac{n}{2}\right\rceil$ words respectively, and (2) treat each nonterminal in the balanced tree as a substructure to perform \textsc{Sub}$^2$. \end{itemize} All of the data augmentation baselines are explicit augmentations where concrete new examples are generated and used. The methods above are generally applicable to a wide range of NLP tasks. \subsection{Part-of-Speech Tagging} We conduct our experiments using the Universal Dependencies \citep[UD;][]{nivre-etal-2016-universal,nivre-etal-2020-universal}\footnote{\url{http://universaldependencies.org/}} dataset. \input{tables/2-POS-ud1.2} First, we compare both \textsc{NoAug}{} and \textsc{Sub}$^2${} to the previous state-of-the-art performance \citep{heinzerling-strube-2019-sequence} to ensure that our baselines are strong enough (Table~\ref{tab:pos-ud1.2}). \citet{heinzerling-strube-2019-sequence} take the token-wise concatenation of mBERT last-layer representations, byte-pair encoding \citep[BPE;][]{gage1994new}--based LSTM hidden states and character-LSTM hidden states as the input to the classifier, and fine-tune the pretrained mBERT during training. We find that with our framework with frozen mBERT and extra learnable layer weight parameters, we are able to obtain competitive or better results than those reported by \citet{heinzerling-strube-2019-sequence}; the gains grow larger when using XLM-R, which is trained on larger corpora than mBERT. In addition, by augmenting the training set with \textsc{Sub}$^2${}, we obtain competitive performance on all languages, and achieve better average accuracy on low-resource languages. \input{tables/1-POS-ud2.6} We further test the part-of-speech tagging accuracy on 5 selected low-resource treebanks in the UD 2.6 dataset (Table~\ref{tab:pos-ud2.6}), following the official splits of the dataset. For four among the five investigated treebanks, \textsc{Sub}$^2${} achieves the best performance among all methods, while also maintaining a competitive performance on te (mtg). In contrast, other augmentation methods (\textsc{CtxSub}{} and \textsc{Rand}) are harmful compared to \textsc{NoAug}{} on all treebanks, indicating that the examples generated by \textsc{Sub}$^2${} may be closer to the original data distribution. \subsection{Dependency Parsing} \input{tables/3-d-parse} We evaluate the performance of models using the standard Penn Treebank dataset \citep[PTB;][]{marcus-etal-1993-building}, converted by Stanford dependency converter v3.0,\footnote{\url{https://nlp.stanford.edu/software/stanford-dependencies.shtml}} following the standard splits. We first compare the performance of \textsc{Sub}$^2${} and baselines in the low-resource setting (Table~\ref{tab:d-parse-size}). All methods, though not always, may help achieve better performance than \textsc{NoAug}. \textsc{CtxSub}{} helps achieve the best LAS when there is only an extremely small training set (e.g., 10 examples) available; however, when the size of the original training set becomes larger, \textsc{Sub}$^2${} begins to dominate, while \textsc{CtxSub}{} and \textsc{Rand}{} start to sometimes hurt the performance. In addition, a larger augmented dataset does not necessarily lead to better performance -- throughout our experiments, augmenting the original dataset to $10\times$--$50\times$ larger can result in reasonably good accuracy. However, when training on the full WSJ training set, \textsc{Sub}$^2${} does not necessarily help improve over baselines, but the performance is quite competitive (Table~\ref{tab:d-parse-full}).\footnote{An additional finding here is that a simple biaffine dependency parsing model \citep{dozat2016deep} with XLM-R initialization is able to set a new state of the art for dependency parsing with only in-domain annotation.} \subsection{Constituency Parsing} We evaluate \textsc{Sub}$^2${} and baseline methods on few-shot constituency parsing, using the Foreebank \citep[Fbank;][]{kaljahi-etal-2015-foreebank} and NXT-Switchboard \citep[SWBD;][]{calhoun2010nxt} datasets. Foreebank consists of 1,000 English and 1,000 French sentences; for either language, we randomly select 50 sentences for training, 50 for development, and 250 for testing.\footnote{We leave the other 650 sentences for future use.} We follow the standard splits of NXT-Switchboard, and randomly select 50 sentences from the training set and 50 from the development set for training and development respectively. We compare different data augmentation methods using the setup of few-shot parsing from scratch (Table~\ref{tab:c-parse-few}). Among all settings we tested, \textsc{Sub}$^2${} achieves the best performance, while all augmentation methods we investigated improve over training only on the original dataset (\textsc{NoAug}). Surprisingly, we find that the seemingly meaningless \textsc{Rand}{}, which random shuffles the sentence and inserts the shuffled words back into the original parse tree structure as the nonterminals, also consistently helps few-shot parsing by a nontrivial margin.\footnote{This trend may be explained by benefits in learning/optimization stability in this few-shot setting, but we leave a richer exploration of potential explanations for future work. } For domain adaptation (Table~\ref{tab:c-parse-transfer}), we first train Benepar \citep{kitaev-klein-2018-constituency} on the Penn Treebank dataset, and use the pretrained model as the initialization. While compared to few-shot parsing trained from scratch, the gain by data augmentation generally becomes smaller, \textsc{Sub}$^2${} still works the best across datasets. \input{tables/4-c-parse} \subsection{Text Classification} \input{tables/5-class} We evaluate the methods introduced in Section~\ref{sec:var} and baselines on two text classification datasets: \citep[SST;][]{socher-etal-2013-recursive} and AG News \citep{zhang2015character} sentence (Table~\ref{tab:txt-class}), in the low-resource setting.\footnote{We only keep the single-sentence instances among all examples in each split of the original AG News dataset, following \citet{shi-etal-2018-tree}. } We obtain the constituency parse trees using Benepar \citep{kitaev-klein-2018-constituency} trained on the standard PTB dataset. Since the SST dataset provides sentiment labels of phrases, it is also natural to apply such phrase sentiment labels as substructure labels, where the substructures are phrases (\textsc{Sub}$^2$+\textsc{p}+\textsc{senti}). Across the two investigated settings, data augmentation is usually helpful to improve over \textsc{NoAug}, and most variations of \textsc{Sub}$^2${} with the phrase-or-not (+\textsc{p}) substructure label are among the best-performing methods on each task (except \textsc{Sub}$^2$+\textsc{p} for SST-10\%). Additionally, constituency tree--based \textsc{Sub}$^2${} with phrase labels (+\textsc{p+l}) outperforms balanced tree--based \textsc{Sub}$^2${} in both settings, indicating that phrase structures can be considered as useful information for data augmentation in general. We further use \textsc{Sub}$^2$+\textsc{p+t+senti} to augment the full SST training set, since it is the best augmentation method for few-shot sentiment classification. In addition to sentences, we also add phrases (i.e., subtrees) as training examples, following most of existing work \interalia{socher-etal-2013-recursive,kim-2014-convolutional,brahma2018improved},\footnote{That is, different from Table~\ref{tab:txt-class}, we apply the same settings as conventional work to produce numbers in Table~\ref{tab:sst_full}. } to boost performance. In this setting, we find that \textsc{Sub}$^2${} helps set a new state of the art on the SST dataset (Table~\ref{tab:sst_full}). \section{Discussion} We investigate substructure substitution (\textsc{Sub}$^2$), a family of data augmentation methods that generates new examples by same-label substructure substitution. Such methods help achieve competitive or better performance on the tasks of part-of-speech tagging, few-shot dependency parsing, few-shot constituency parsing, and text classification. While other data augmentation methods (e.g., \textsc{CtxSub}{} and \textsc{Rand}) sometimes improve the performance, \textsc{Sub}$^2${} is the only one that consistently helps low-resource NLP across tasks. While existing work has shown that explicit constituency parse trees may not necessarily help improve recursive neural networks for text classification and other NLP tasks \citep{shi-etal-2018-tree}, our work shows that such parse trees can be robust backbones for \textsc{Sub}$^2$-style data augmentation, introducing more potential ways to help neural networks take advantages from explicit syntactic annotations. There is an open question remaining to be addressed: it is still unclear that why \textsc{Rand}{} helps improve few-shot constituency parsing, as the training process requires the model to output the correct parse tree of a sentence while only accessing shuffled words. We leave the above question, as well as applications of \textsc{Sub}$^2${} to more NLP tasks, for future work.
{'timestamp': '2021-01-05T02:15:09', 'yymm': '2101', 'arxiv_id': '2101.00411', 'language': 'en', 'url': 'https://arxiv.org/abs/2101.00411'}
arxiv
\section{Introduction} Recent progress in speech-to-text tasks such as automatic speech recognition (ASR) and speech translation (ST) has been achieved by the development and application of unsupervised speech pre-training methods~\cite{oord2018representation,Schneider2019,baevski2020wav2vec,conneau2020unsupervised,Wu2020SelfSupervisedRI,Nguyen2020InvestigatingSP}, with semi-supervised learning (self-training)~\cite{kahn2020self,Pino2020SelfTrainingFE,zhang2020pushing,xu2020self} or a combination of both methods~\cite{xu2020self}. This line of research leverages large amounts of unlabeled English speech data~\cite{kahn2020libri} that enable improvements in \emph{English} ASR or \emph{out-of-English} ST. Large amounts of multilingual audio data are needed in order to achieve similar progress for multilingual ASR and ST. Similarly, most ASR and ST research is currently conducted on the LibriSpeech~\cite{panayotov2015librispeech} and MuST-C benchmarks~\cite{cattoni2020must,di2019must}. As a result, the research community has been mostly focused on speech-to-text tasks with English as input. While multilingual ASR~\cite{Pratap2020,ardila-etal-2020-common} and ST datasets~\cite{wang2020covost,iranzo2020europarl} have recently been made available, the amount of data available quickly drops beyond the top few high-resource languages. Simultaneous speech translation (interpretation) has witnessed a resurgence with the applications of end-to-end encoder-decoder models. Most of the recent studies focus on text output and leverage ST corpora that are translated offline in the written form. There are differences, however, between translationese and interpretese~\citep{sridhar2013corpus,he2016interpretese}, where interpreters develop a variety of strategies to improve simultaneity. Models trained on translation corpora are unlikely to learn from these interpretation skills to achieve better quality-latency trade-offs. Finally, there has been little research~\citep{translatotron,tjandra2019speech,zhang2020uwspeech} into speech output due to the lack of open data. Existing corpora~\citep{tohyama2004ciair,bendazzoli2005approach} are either of limited size or no longer publicly available. In this paper, we introduce VoxPopuli, a large-scale multilingual speech corpus for representation learning, semi-supervised learning and interpretation. It contains the largest open unlabeled speech data to date, totaling 400K hours in 23 languages: Bulgarian (Bg), Czech (Cs), Croatian (Hr), Danish (Da), Dutch (Nl), English (En), Estonian (Et), Finnish (Fi), French (Fr), German (De), Greek (El), Hungarian (Hu), Italian (It), Latvian (Lv), Lithuanian (Lt), Maltese (Mt), Polish (Pl), Portuguese (Pt), Romanian (Ro), Slovak (Sk), Slovene (Sl), Spanish (Es) and Swedish (Sv). VoxPopuli~also provides a total of 1.8K hours of transcribed speech in 16 languages (En, De, Fr, Es, Pl, It, Ro, Hu, Cs, Nl, Fi, Hr, Sk, Sl, Et and Lt) and their aligned oral interpretations into 15 target languages (En, De, Fr, Es, Pl, It, Ro, Hu, Cs, Nl, Fi, Sk, Sl, Lt and Da) totaling 17.3K hours. We describe our corpus creation methodology in Section~\ref{sec:corpus_creation} and analyze the created corpus in Section~\ref{sec:data_analysis}. We provide ASR baselines and demonstrate the value of our multilingual unlabeled data as well as weakly labeled data on several non-English languages in Section~\ref{sec:experiments_and_results}. \section{Corpus Creation} \label{sec:corpus_creation} \subsection{Data Acquisition} VoxPopuli~sources data from 2009-2020 European Parliament (EP) event recordings, which include plenary sessions, committee meetings and other events. In each event, speakers give speeches in turn in different European Union (EU) languages. These speeches are partially transcribed (for plenary sessions only) and interpreted into 24 EU languages. The interpretations are only oral without any transcription. In the following part, we refer to the original speech as ``source speech" and to the interpreted one as ``target speech". We download audio clips for both source and target speeches from the official website\footnote{https://multimedia.europarl.europa.eu}. We also crawl the transcript, speaker information and starting/ending timestamps for each speech (for plenary sessions only) from that source, with which we later align the speech to its transcript and interpretation utterance by utterance. The acquired raw data suffers from missing audios, incomplete transcripts and inaccurate timestamps. We build data processing pipelines to segment speech paragraphs into utterances and filter out the ones with erroneous transcriptions. \input{unlabeled_transcribed_stats} \subsection{Data Processing} \label{sec:data_processing} \subsubsection{Unlabeled Speech} We construct VoxPopuli~unlabeled set from all source and target speeches in 23 EU languages (excluding Irish because of very limited data availability). We segment full-event audios into short clips of 15-30 seconds using an energy-based voice activity detection (VAD) algorithm\footnote{https://github.com/amsehili/auditok}. Each audio clip has a maximum of 2 seconds of continuous silence, and silent clips are discarded. Around 16\% of the data is dropped after silence removal, which leads to a final overall duration of around 400K hours. \input{s2st_stats} \subsubsection{Transcribed Speech} \label{sec:transcribed_speech} The VoxPopuli~transcribed set comes from aligning the full-event source speech audio with the transcripts for plenary sessions. Official timestamps are available for locating speeches by speaker in the full session, but they are frequently inaccurate, resulting in truncation of the speech or mixture of fragments from the preceding or the succeeding speeches. To calibrate the original timestamps, we perform speaker diarization (SD) on the full-session audio using pyannote.audio~\citep{Bredin2020} and adopt the nearest SD timestamps (by L1 distance to the original ones) instead for segmentation. Full-session audios are segmented into speech paragraphs by speaker, each of which has a transcript available. The speech paragraphs have an average duration of 197 seconds, which leads to significant memory usage and prevents efficient parallelism (batching) during model training. We hence further segment these paragraphs into utterances with a maximum duration of 20 seconds. We leverage speech recognition (ASR) systems to force-align speech paragraphs to the given transcripts and cut the utterances by ending punctuation or the longest silence inside the sentence if it exceeds 20 seconds. The ASR systems are TDS models~\citep{TDS2019} trained with ASG criterion~\citep{collobert2016wav2letter} on audio tracks from in-house de-identified video data. The resulting utterance segments may have incorrect transcriptions due to incomplete raw transcripts or inaccurate ASR force-alignment. We use the predictions from the same ASR systems as references and filter the candidate segments by a maximum threshold of 20\% character error rate (CER). We split the filtered utterances into train, development and test sets with disjoint speakers and target duration ratio (18:1:1). To determine the assignments, we group utterances by speaker and sort them by overall duration in ascending order. We assign the sorted groups to the test set in order until it reaches 20 speakers or the target duration (whichever comes later). The same process is repeated on the remaining utterance groups to construct the development set (with minimum 10 speakers instead). Finally, the rest of utterances make up the train set. This approach ensures higher speaker diversity in the test and development sets. \subsubsection{Speech-To-Speech Alignment} Even though every source speech is associated with corresponding simultaneous interpretations in target languages, considerable preprocessing and filtering is necessary to make this dataset usable. Our strategy is to align source and target at the sentence level using ASR. We first compare the spectrogram of the source and the target speech to remove the identical parts and segment the target speech into paragraphs. These identical speech are due to either the short delay between the time the source speaker and the interpreter started, or the fact that the source language is the same as the target one, and thus no interpretation is needed. For long target paragraphs, we further segment them by silence into audio clips of at most 15 minutes long. We use the same ASR model described in Section~\ref{sec:transcribed_speech} and a language model (Section~\ref{sec:lm_data}) to decode the segmented target audio. The decoded text is also forced aligned with the target audio, so that we have the timestamps of every decoded word. For each source segment produced in Section~\ref{sec:transcribed_speech}, we locate all decoded words that are within a window of five seconds to its start and end. A set of candidate target segments can be generated from all possible combinations of the starting and ending decoded words. We compute the cosine similarity between the LASER representation~\citep{artetxe2019massively} of the source text and each decoded text in the candidate set to find the best target segment, i.e. the one with the highest score. We first carry out this process for all source segments, respectively, and then finetune the boundaries of overlapping target segments for consecutive source segments. Finally, a threshold of 0.75 is applied on the similarity score to filter out low-quality alignments, which can be due to ASR errors. In addition to ASR output, we also collect human transcription on 400 hours of English target speech. The human annotators were asked to provide timestamps for each word while transcribing, and thus we can apply the same alignment process described above on human transcription and generate a set of ground truth speech-to-speech alignment data. As a by-product from this alignment process, source text and target speech is aligned, which provides speech-to-text ``translation" data in the reversed direction. This data is weakly labeled---the label (text) may contain more information than the speech data (interpretation is likely to drop unimportant details) and hence is not exact. However, it is still useful for ST model training as an addition to labeled data. \input{table_interpretation_example} \input{table_vp_asr_eval} \subsubsection{Language Modeling Data} \label{sec:lm_data} To train language models (LM) for ASR decoding, we combine VoxPopuli~transcription in the training set with the EuroParl corpus~\citep{koehn2005europarl}, which is from the proceedings of the European Parliament from 1996 to 2011. To process the EuroParl data, we first apply the sentence segmentation tool provided with the corpus. We remove all texts in the parentheses, replace hyphens and slashes with space, and remove all other punctuation except apostrophes. All digits are converted into words, and all texts are normalized into lowercase. Table~\ref{tab:unlabeled_transcribed_stats} shows the statistics of the LM data. \section{Data Analysis} \label{sec:data_analysis} \paragraph{Unlabeled speech} As we can see from Table~\ref{tab:unlabeled_transcribed_stats}, VoxPopuli~has a total of 400K hours of unlabeled data well-distributed across 23 EU languages, resulting in 8K-24K hours of data for each language. This ensures adequate data on languages with lower ASR resource, which are likely to benefit more from semi-supervised learning. It also facilitates multilingual model training since there is not much data imbalance and little need for tuning data sampling strategy. \paragraph{Transcribed speech} The VoxPopuli~transcribed data contains 16 languages totaling 1.8K hours and 4.3K speakers, whose detailed statistics can be found in Table~\ref{tab:unlabeled_transcribed_stats}, including duration (hours) by language, number of speakers, percentage of female speakers and number of tokens. The data distribution is imbalanced and reflects the natural distribution of the number of native speakers. The remaining 7 languages (Pt, Bg, El, Lv, Mt, Sv and Da) are not covered due to either limited data volume or the availability of processing pipelines. \paragraph{Speech-to-speech alignment} The statistics of the speech-to-speech alignment between all source languages and 15 target languages are shown in Table~\ref{tab:s2s_align_stats}. Compared with the total amount of data available for each source language (``Transcribed hours" in Table~\ref{tab:unlabeled_transcribed_stats}), we obtain target alignments for more than $70\%$ of the source sentences in En, De, Fr, Es and It, more than $50\%$ for Pl, Ro, Cs, Nl and Hr, and the rest has at least $40\%$ of source segments aligned. To examine the quality of our ASR system, we align the ASR output with the human transcription we collect on English target speech and see a word error rate (WER) of 31.7. With the human transcription, we can produce ground truth speech-to-speech alignment data that is 1.1 times larger than the size of the alignment data created from using ASR output, indicating that around $12\%$ of the low-quality alignments are filtered due to ASR errors. If we compare the ASR-based and the ground truth alignment data, there is on average a 0.75-second shift in the target segment boundaries. \paragraph{Interpretese vs. translationese} We exemplify the differences between simultaneous oral interpretation and offline written translation using VoxPopuli~in Table~\ref{tab:interpretataion_example}. The latter is verbatim and exact compared to the original speech, while the former tends to be more general and summarizing with unimportant details dropped. Human interpreters regularly apply these tactics to make better quality-latency trade-offs. Speech-to-speech translation models may benefit from these tactics if they are trained on interpretation data that VoxPopuli~provides. \section{Experiments \& Results} \label{sec:experiments_and_results} We provide VoxPopuli~ASR baselines and validate the versatility of VoxPopuli~unlabeled data in unsupervised representation learning and semi-supervised learning for ASR as well as ST. We also evaluate the quality of speech-to-speech alignment indirectly via the weakly labeled ST data it produces. \input{table_zerospeech17} \input{table_w2v_eval} \input{table_common_voices_in_domain} \input{table_self_training_eval} \subsection{Experimental Setup} For representation learning, we perform speaker diarization before VAD-based segmentation so that each utterance contains exactly one speaker. We augment the data with time dropout, pitch modification and reverberation~\citep{kharitonov2020data} during model training. For non-wav2vec models, we extract 80-dimensional log-mel filterbank speech features with 25ms windows size and 10ms shift. We apply per-utterance CMVN (cepstral mean and variance normalization) to the extracted features. For GPU memory efficiency, we remove training samples that have more than 60 seconds of speech or have more than 1024 characters. We train wav2vec 2.0~\citep{baevski2020wav2vec} models with original hyper-parameter settings using fairseq~\citep{ott2019fairseq}, except for Table~\ref{tab:wer_scores_main_cv} where we use wav2letter~\citep{pratap2018w2l} and follow~\citet{talnikar2020joint} to do finetuning using both supervised CTC~\citep{graves2006ctc} loss and unsupervised wav2vec 2.0 loss. The largest model (``VP-100K") takes 10 days on 128 V100 GPUs for 1M updates. For non-wav2vec models, we train Transformer~\citep{NIPS2017_3f5ee243} with cross-entropy criterion using fairseq S2T~\citep{wang2020fairseqs2t}. For Section~\ref{sec:asr_baselines} and Section~\ref{sec:unsupervised_pretraining}, we use phoneme vocabularies for models that we evaluate with PER (phone error rate) and character vocabularies for the other. For Section~\ref{sec:self_training}, we use Unigram~\cite{kudo-richardson-2018-sentencepiece} vocabularies with 2K subwords for all models. To improve ST model training, we pre-train the encoder on the LibriSpeech~\citep{panayotov2015librispeech} ASR task. We use the best checkpoint by validation loss for evaluation, except for Section~\ref{sec:self_training} where we average the 10 best checkpoints. We build n-gram language models for decoding (when specified) using KenLM~\citep{heafield2011kenlm}. \subsection{Speech Recognition (ASR) Baselines} \label{sec:asr_baselines} We provide monolingual Transformer baselines for the 14 languages that have more than 10 hours of transcribed data (see Table~\ref{tab:unlabeled_transcribed_stats}). Both development and test WER are reported in Table~\ref{tab:vp_asr_eval}. We see that several low-resource languages (Fi, It, Hr, Sk and Sl) suffer from high recognition errors ($>$40\% WER) due to the lack of training data. Even the highest resource one (En) has a high WER of around 30\%. \subsection{Unsupervised Representation Learning} \label{sec:representation_learning} We follow the setting in~\citet{riviere2020unsupervised} to evaluate unsupervised speech representations by phoneme discriminability on 3 languages (English, French and Mandarin), and report ABX discriminability score~\citep{schatz2013evaluating} on the 10s test set from ZeroSpeech 2017~\citep{dunbar2017zero}. Standard deviation (``Std.") of the scores across the 3 languages is also reported as a measure for the generality of the representations. As previous studies focus on monolingual representations, we explore multilingual representations and examine their generality across languages. We train CPC-based models~\citep{riviere2020unsupervised_wild} on 500-hour English and 500-hour French unlabeled data from VoxPopuli, respectively. And we combine English and French data with 50\% sampling (so that the total duration remains the same) for the multilingual setting. We observe from Table~\ref{tab:zerospeech17} that the multilingual model (``En+Fr-500") performs comparably to the monolingual ones (``En-500" and ``Fr-500") on their seen languages and performs better on unseen language (``Zh"). Its scores vary less across languages (lower ``Std.") compared to ``En-500". The variance of the scores is comparable to ``Fr-500" while the average is lower. We conclude that multilingual representations generalize better across languages and are more robust on unseen languages. For quick exploration, we leverage only part of the VoxPopuli~unlabeled data and leave the validation on more data to future work. \subsection{Semi-Supervised Learning} We explore two semi-supervised learning settings for the application of VoxPopuli~unlabeled data: unsupervised pre-training followed by supervised fine-tuning for ASR and self-training for ASR as well as ST. \subsubsection{ASR with Unsupervised Pre-Training} \label{sec:unsupervised_pretraining} Self-supervised (unsupervised) pre-training such as wav2vec 2.0~\citep{baevski2020wav2vec} substantially reduces the need of labeled data in ASR. Furthermore, multilingual pre-training~\citep{conneau2020unsupervised} allows cross-lingual transfer, which brings extra gains especially to low-resource languages. Pre-training wav2vec 2.0 models is, however, resource-intensive and hence re-training models for each task with different domains is impractical. With the large-scale multilingual data in VoxPopuli, we explore if scaling multilingual pre-training can take us towards the one-model-fits-all paradigm by alleviating the impacts of domain or language mismatch between pre-training and fine-tuning. We train wav2vec 2.0 models~\footnote{wav2vec 2.0 \emph{Base} (95M) unless specified otherwise.} on 10K-hour, 50K-hour and 100K-hour VoxPopuli~data in 23 languages (denoted as ``VP-10K", ``VP-50K" and ``VP-100K", respectively). We also train models with 4.5K-hour monolingual data (denoted as ``VP-Mono-5K") for comparison. For quick verification, we use only part of the VoxPopuli~unlabeled data for pre-training. We leave training the models on the full 400K-hour data to future work, which is supposed to achieve even better performance. \paragraph{In-domain pre-training} We examine the conventional in-domain pre-training setting on the VoxPopuli~ASR benchmark. We evaluate the VP-10K model, where the pre-training data is filtered so that it has no overlaps with the transcribed development and test set. From table \ref{tab:vp_asr_eval}, we see that pre-training using unlabeled data brings significant gains to all the languages (average 59\% test WER reduction). The gains are most significant on the low-resource languages, where improvements are qualitative (for example, from nearly 100\% test WER on Sl down to around 30\%). \paragraph{Out-of-domain pre-training} We examine the out-of-domain pre-training setting using the Common Voice (CV) ASR corpus~\citep{ardila-etal-2020-common}. In contrast with the political domain oral speech in VoxPopuli, they are more fluent read speech of no copyright sentences (for example, Wikipedia articles). We adopt the few-shot phoneme recognition setup on CV v3 from~\citet{riviere2020unsupervised}, with which domain adaptation is limited during fine-tuning due to the small data volume --- it has 1-hour train set, 20-minute development set and 1-hour test set for 10 languages including 5 VoxPopuli~ones. We present the performance of VP-Mono-5K, VP-10K and VP-100K with the m-CPC~\citep{riviere2020unsupervised} and XLSR~\citep{conneau2020unsupervised} baselines in Table~\ref{tab:cv_eval_per}, where phone error rate (PER) is reported. The XLSR baselines share the same wav2vec 2.0 architecture as our models but are trained with in-domain CV data. VP-Mono-5K outperforms XLSR-Mono and XLSR-10 on all 5 VoxPopuli~languages (except for a tie on Es with XLSR-Mono). VP-100K outperforms XLSR-10 on 8 (9) out of the 10 languages. VP-100K (Large) overall performs competitively to XLSR-53, which leverages 52K-hour out-of-domain data in addition to the in-domain CV data. Notably, it outperforms XLSR-53 on Zh, which is covered by XLSR-53 but remote from the EU languages in VP-100K. This suggests the high generality of the speech representations VP-100K learned. We also evaluate our multilingual model (VP-50K) under the normal setup (CV v5.1) and report test WER in Table~\ref{tab:wer_scores_main_cv}. They are compared with supervised baselines from DeepSpeech-Polyglot\footnote{https://gitlab.com/Jaco-Assistant/deepspeech-polyglot}, which leverage extended CV train sets and several other corpora for training as well as LM for decoding. Our model outperforms the baseline with fine-tuning on the standard CV train set (a subset of the baseline's one), even when not using LM in decoding. \paragraph{Out-of-language pre-training} In the few-shot phoneme recognition setup (Table~\ref{tab:cv_eval_per}), VP-100K does not cover 5 of the 10 CV languages (Ky, Ru, Tr, Tt and Zh) in pre-training, but leverages data from 18 additional EU languages. It outperforms the in-domain in-language XLSR baselines on most of the uncovered languages (except Ky which is a remote central Asian language). Moreover, it performs more stably across all the 10 languages with a smaller variance (standard deviation) on PER. \subsubsection{Self-Training for ASR and ST} \label{sec:self_training} Self-training~\citep{scudder1965probability} is a classical semi-supervised learning approach, where unlabeled data is equipped with pseudo-labels from a supervised model and then combined with labeled data for model training. We use the combination of EuroParl-ST~\citep{iranzo2020europarl} and CoVoST 2~\citep{wang2020covost} for both ASR and ST labeled data in 3 languages (directions). The former is created from 2009-2012 EP plenary sessions and hence has the same domain as VoxPopuli. The latter is based on Common Voice v4, which has different domain than VoxPopuli~and dominates the combined train set. We train Transformer \emph{Base}~\citep{NIPS2017_3f5ee243} supervised baselines and use 0.8K/3K-hour monolingual VoxPopuli~unlabeled data (from 2013-2020 sessions only to avoid overlaps with EuroParl-ST) to self-train Transformer \emph{Large} models. We upsample labeled data in self-training so that it has the same duration as the unlabeled one. We observe from Table~\ref{tab:st_self_training_eval} that self-training on VoxPopuli~improves both in-domain (``EP") and out-of-domain (``CV") performance with similar magnitude most of the time. For ST, self-training helps to narrow the gap between end-to-end models and the cascaded ones (more labeled data available) without the addition of expensive labeled data. \subsection{Weakly Supervised ST} We evaluate the quality of the weakly labeled ST data from our speech-to-speech alignment on the same benchmark as the self-training experiments. This also provides an indirect evaluation for our alignment pipeline since imprecise alignments hurt the ST label quality. We examine the performance of weakly supervised training as well as joint training using both labeled and weakly labeled data. We see from Table~\ref{tab:st_self_training_eval} that the former is on par with (or better than) the supervised baseline in the VoxPopuli~domain (``EP") with 0.3x-1.8x more training data than the baseline. Joint training brings substantial gains to both in-domain (``EP") and out-of-domain (``CV") performance, and it outperforms self-training. This suggests that our weakly labeled data (0.4K hours) is much more informative and efficient than the pseudo-labeled data (3K hours) when combined with labeled data. \section{Related Work} \paragraph{Multilingual speech corpora} LibriLight~\citep{kahn2020libri} currently represents the largest scale unlabeled speech corpus but it is limited to English. MLS~\cite{Pratap2020} is a recently released large-scale multilingual corpus of read speech in 8 languages, derived from LibriVox. MAILABS\footnote{https://www.caito.de/2019/01/the-m-ailabs-speech-dataset} is also derived from Librivox and has about 1000 hours available in 9 languages. While MLS and MAILABS are derived from audiobooks, VoxForge\footnote{http://www.voxforge.org} and Common Voice~\citep{ardila-etal-2020-common} gather data via crowd-sourcing. VoxForge collected data in about 15 different languages with about 300 hours of speech in total; Common Voice currently supports 60 languages for a total of 7327 validated hours available. The CMU Wilderness dataset~\citep{black2019cmu} collects readings from the New Testament, with 700 different languages available. IARPA Babel program\footnote{https://www.iarpa.gov/index.php/research-programs/babel} collected data for 24 languages, mostly from conversational telephone speech. The dataset is however not released and under an open license, and focused on low-resource languages, with labeled data ranging between 25 to 65 hours per language. \paragraph{Speech-to-Text and Speech-to-Speech Translation} Apart from machine translation~\citep{koehn2005europarl}, the European Parliament open data has fostered the development of corpora for speech-to-text translation and for simultaneous interpretation. EuroParl-ST~\citep{iranzo2020europarl} is a multilingual speech-to-text translation corpus with translations between 6 European languages (En, Fr, De, Es, It and Pt). Similarly, EPIC~\citep{bendazzoli2005approach} is derived from the European Parliament with simultaneous interpretation speeches in Italian, English and Spanish. CIAIR~\citep{tohyama2004ciair} and STC~\citep{shimizu2014collection} are simultaneous interpretation corpora between English and Japanese with a total of about 180 hours for the former, while the latter is currently unavailable for download. The MaSS dataset~\citep{zanon-boito-etal-2020-mass} also provides speech to speech alignments for about 8k utterances across 8 languages, for a total of about 23h of speech. \section{Conclusion} In this paper, we introduce a large-scale multilingual speech corpus, VoxPopuli, for representation learning, semi-supervised learning and interpretation. VoxPopuli~provides the largest open unlabeled speech data to date, which has broad applications including unsupervised pre-training and self-training. VoxPopuli~is also the first corpus for large amounts of open speech-to-speech interpretation data. We provide VoxPopuli~ASR baselines and validate the versatility of VoxPopuli~unlabeled data in semi-supervised learning under challenging out-of-domain settings. The corpus is available at \url{https://github.com/facebookresearch/voxpopuli}. \section{Acknowledgements} We thank Gabriel Synnaeve, Tatiana Likhomanenko, Jade Copet, Vineel Pratap, Jiatao Gu and Alexis Conneau for helpful discussions on the project. \section{Ethical Considerations} We acknowledge the European Union (EU) for creating and publishing the materials used by VoxPopuli. We will add citations as well as acknowledgements in our release. We paid the market price to transcription vendors for the human annotations we collected. VoxPopuli~includes all available speeches from the 2009-2020 EP events without any selections on the topics or speakers. The speech contents represent the standpoints of the speakers in the EP events, many of which are EU officials.
{'timestamp': '2021-07-28T02:09:13', 'yymm': '2101', 'arxiv_id': '2101.00390', 'language': 'en', 'url': 'https://arxiv.org/abs/2101.00390'}
arxiv
\section*{Acknowledgments} This research is supported in part by the Office of the Director of National Intelligence (ODNI), Intelligence Advanced Research Projects Activity (IARPA), via Contract No. 2019-19051600007, the DARPA MCS program under Contract No. N660011924033 with the United States Office Of Naval Research, the Defense Advanced Research Projects Agency with award W911NF-19-20271, and NSF SMA 18-29268. The views and conclusions contained herein are those of the authors and should not be interpreted as necessarily representing the official policies, either expressed or implied, of ODNI, IARPA, or the U.S. Government. We would like to thank anonymous reviewers and collaborators in USC INK research lab for their constructive feedback. \section{Introduction} Pre-trained text-to-text models \cite{raffel2019exploring, lewis-etal-2020-bart} provide a unified formulation and off-the-shelf weights for a variety of NLP tasks, such as question answering \cite{khashabi-etal-2020-unifiedqa} and commonsense reasoning \cite{bosselut-etal-2019-comet}. In addition to their strong performance, text-to-text models naturally support generalizing to novel tasks, by incorporating task description as part of the source sequence and fine-tuning the model with (source, target) examples \cite{weller-etal-2020-learning}. At inference time, the model is required to perform unseen tasks with the source sequence containing new task descriptions. \input{figures_input/intro} \input{figures_input/big} While this initial attempt shows positive results, there are two potential limitations for the direct fine-tuning approach. (1) Predictions can be sensitive to the task descriptions (or ``prompts'') that are heuristically designed \cite{jiang-etal-2020-know}. Paraphrasing the task description may lead to performance downgrade. (2) The model still learns from individual (source, target) examples, instead of learning to solve tasks at a higher level, by explicitly taking multiple examples within a task as a whole (see Fig. \ref{fig:intro}). Meanwhile, applying existing zero-shot learning methods that supports task-level learning to text-to-text transformers is non-trivial. Methods designed specifically for classification problems, such as prototypical networks \cite{prototypical17snell}, cannot be directly applied to text-to-text models. Moreover, given the large size of text-to-text models, generating parameters for a whole model from the task description \cite{jin-etal-2020-language} is infeasible. In this work, we follow the settings in \cite{weller-etal-2020-learning} and aim to improve a model's generalization ability to unseen tasks by better incorporating task descriptions and using a task-level training procedure. We introduce \textsc{Hypter}, a framework that employs a hypernetwork \cite{Ha2017HyperNetworks} to dynamically generate task-specific parameters (\textit{i.e.}, adapters) from task descriptions. Adapters \cite{pmlr-v97-houlsby19a} are light-weight modules that can be inserted into transformer layers for \textit{parameter-efficient} adaptation. Such formulation also effectively enables learning at the \textit{task} level, by learning to generate appropriate parameters for a task, and examine the model's competence on each task using multiple examples within that task. This is in contrast to learning at the \textit{instance} level, by learning to generate the correct output for one specific input sequence. We apply \textsc{Hypter} to two datasets: ZEST \cite{weller-etal-2020-learning} and a synthetic version of SQuAD \cite{rajpurkar-etal-2016-squad}. We demonstrate that \textsc{Hypter} improves upon direct fine-tuning baselines. Notably, training with \textsc{Hypter} achieves 0.45\% absolute improvement (11.3\% comparative improvement) in Competence@90 metric on ZEST, when BART-Large is used as the main network. \section{Approach} \section{Problem Definition} \vspace{-0.1cm} We study the problem of \textit{learning from task description} \cite{weller-etal-2020-learning}, and aim to improve models' competence on unseen tasks at the inference time. Formally, a task is denoted as a tuple of $(d, \mathcal{D})$, where $d$ is the natural language description of the task, and $\mathcal{D}=\{(s_1, t_1), ..., (s_n, t_n)\}$ contains (source, target) examples of this task (See Fig. \ref{fig:intro}). In our text-to-text formulation, both $s_i$ and $t_i$ are text sequences. At train time, both $d$ and $\mathcal{D}$ are available, while at test time, an unseen description $d$ is given, and the model is expected to predict the correct $t$ given input $s$ without further training. For instance, in the ZEST dataset \cite{weller-etal-2020-learning}, a train task description can be ``\textit{Are mountain bikes allowed at this national park?}'', while $\mathcal{D}$ contains twenty paragraphs for different national parks and twenty corresponding answers. During test time, a novel task may be ``\textit{Are there fish in this national park that live in caves?}'', and the model is asked to directly make inferences. \section{Background: Adapters} Our work is built on adapters \cite{pmlr-v97-houlsby19a}, light-weight modules that can be placed into transformer layers for parameter-efficient transfer learning. In the original paper, the main model is frozen during training, while only layer norm and adapter parameters are learnable. In this paper, we adopt a simplified design compared to the original paper (see Fig. \ref{fig:big} (Left))~--~In each transformer layer, exactly one adapter module will be added after the multi-headed attention. One adapter module contains two linear layers separated by an non-linearity activation layer. We use $(\mathbf{W}_{id}, \mathbf{b}_{id})$ to denote the down-projection parameters for the adapter in transformer layer $i$, and $(\mathbf{W}_{iu}, \mathbf{b}_{iu})$ for the up-projection parameters. \section{Method} \paragraph{Overview.} Fig. \ref{fig:big} provides an illustration of our \textsc{Hypter} framework. \textsc{Hypter} has two major parts: (1) A main network, which is a pre-trained text-to-text model. We instantiate the main network with BART-Base/Large \cite{lewis-etal-2020-bart}. (2) A hypernetwork, which generates adapters to be plugged into the main network. Fig. \ref{fig:big} (Left) contains a detailed illustration of how adapter parameters are generated and how adapter layers are incorporated into one transformer layer. \paragraph{Hypernetwork.} The hypernetwork consists of an encoder and multiple decoders. The encoder maps the task description $d$ to a latent representation $\mathbf{h}_0$, while the decoders use $\mathbf{h}_0$ to generate adapter parameters $\phi$. In our work we instantiated the encoder with a RoBERTa-Base model \cite{liu2019roberta}, \textit{i.e.}, $\mathbf{h}_0 = \text{RoBERTa}(d)$. For a text-to-text model with $n$ transformer layers, the hypernetwork contains $n$ decoders. Decoder $i$ uses $\mathbf{h}_0$ as input, and outputs adapter parameters $\phi_i$ for transformer layer $i$, \textit{i.e.}, $\mathbf{h}_{i,1} = \text{ReLU}(\mathbf{W}_{i,1}\mathbf{h_0} + \mathbf{b}_{i,1})$, $\mathbf{\phi}_i = \mathbf{W}_{i,2}\mathbf{h}_{i,1} + \mathbf{b}_{i,2}$. Here $\mathbf{W}_{i,1}, \mathbf{b}_{i,1}, \mathbf{W}_{i,2}, \mathbf{b}_{i,2}$ are trainable parameters. The generated parameters $\mathbf{\phi}_i$ are sliced and reshaped to become parameters $[\mathbf{W}_{id}, \mathbf{b}_{id}, \mathbf{W}_{iu}, \mathbf{b}_{iu}]$ used in the adapter $i$. \paragraph{Model Training.} We adopt a training schedule where we first train the main network, then train the hypernetwork while the main network is frozen. Conceptually, the first stage ensures that the main network captures the general ability across different tasks; the second stage allows the hypernetwork to learn to adapt the main network to a specific task. During the first stage the text-to-text model is fine-tuned with all $(\text{Concat}(d,s), t)$ examples in the training set. Here $\text{Concat}(d,s)$ means the concatenation of task description $d$ and input $s$. The learned main network from this stage also serves as the baseline method. During the second stage, we sample a task $(d, \mathcal{D})$ from the training set and sample a mini-batch of $(s,t)$ examples from $\mathcal{D}$. Given a description $d$, the hypernetwork generates adapter parameters $\phi_i$. We insert the resulting adapter layers into the main network, and compute the cross entropy loss $L$ of generating $t$ given input $\text{Concat}(d,s)$. The loss is end-to-end differentiable and is back-propagated to update the hypernetwork, while the main network is frozen. See Fig. \ref{fig:big} (Right) for illustration. This second stage of training effectively enables learning at the \textit{task} level. The loss $L$ characterizes the model's competence in the task $(d, \mathcal{D})$. Therefore, by optimizing $L$, the model is trained to \textit{solve tasks}. \paragraph{Model Inference.} At test time the model is given an unseen task description $d$. The hypernetwork generates description-dependent adapter parameters, similar to the procedure during training. In this way, we obtain a model that is capable of making inferences for this new task. \section{Experiments} \subsection{Experiment Setup} \paragraph{Datasets.} We use two datasets that fit our setup. The first one is Zero-shot Learning from Task Descriptions dataset (ZEST, \citealt{weller-etal-2020-learning}), which formulates task descriptions as generalized questions, and provides multiple source-target examples for each question. The performance is evaluated with a novel metric: ``Competence@K'', along with mean F1 score. Competence@K is the percentage of all tasks for which the model achieves mean F1 score higher than K. For example, Competence@90=5 suggests that 5\% of all tasks can be solved with mean F1 better than 90\%. We report dev set performance, and hidden test set performance obtained from ZEST's official leaderboard. We construct the second dataset from SQuAD v1 \cite{rajpurkar-etal-2016-squad} to simulate the problem setting in this paper. We refer to this dataset as Synthetic SQuAD. Specifically, we construct tasks from the original SQuAD train set according to ``question type'', the bi-gram containing the central question word (\textit{e.g.}, what, when). For example, ``when does'' questions are considered as a task, and ``what country'' questions are considered as another task. These bi-grams are used as ``task descriptions''. We select the 100 most frequent question types in SQuAD train set, and randomly subsample 64 examples from each type to formulate our dataset. We then randomly split the 100 types into 80/10/10 for train/dev/test. In addition, we select examples that fall into the 10 test question types from Natural Questions \cite{kwiatkowski-etal-2019-natural} and NewsQA \cite{trischler-etal-2017-newsqa}, and use these as out-of-domain test examples. Performance is evaluated with mean F1. We include the list of question types and more details about this dataset in Appendix~\ref{app:dataset}. \paragraph{Baseline.} To demonstrate the efficacy of the \textsc{Hypter} framework, we compare it to just its first half -- the main text-to-text transformer model that we obtain after the first stage of training. This is identical to the fine-tuning baseline method in \cite{weller-etal-2020-learning}, and there are no other applicable baselines to the best of our knowledge. \paragraph{Training Details.} For each method, we train the model 7 times using different random seeds, and we report average and standard deviation. We discuss other training details, including hyperparameters, in Appendix \ref{app:training}. Notably, we ensure all baseline models will not benefit from additional training, by tuning the number of epochs and using early stopping based on dev performance. This ensures the improvement brought by \textsc{Hypter} is not due to additional training. \input{tables/zest_dev} \input{tables/zest_test} \subsection{Results} \paragraph{Main Results.} We present the results for ZEST in Table~\ref{tab:zest-dev}-\ref{tab:zest-test} and results for Synthetic SQuAD in Table \ref{tab:squad}. On ZEST test set, we observe that the Competence@90 metric is improved from 3.98 to 4.43 when using BART-Large, yielding an 11.3\% relative improvement. When BART-Base is used, C@90 is improved from 2.23 to 2.53. This demonstrates that by learning to solve tasks with \textsc{Hypter}, the model's generalization ability to unseen tasks is improved. On Synthetic SQuAD dataset, we observe 0.74\% improvement with BART-Base and 0.41\% improvement with BART-Large. Additionally, models trained with \textsc{Hypter} achieves comparable or better performance on out-of-domain test sets, suggesting the learned task-solving ability is generalizable to new test distribution.\footnotetext[2]{{\url{https://leaderboard.allenai.org/zest/submissions/public}}}\setcounter{footnote}{2}\footnote{Unexpectedly, in Table \ref{tab:squad} we observe that performance of BART-Large on NewsQA is worse than that of BART-Base. We suspect that BART-Large may have overfit the SQuAD train set during the first stage of fine-tuning.} It is a known issue that evaluating zero-shot performance can be tricky. We tried our best to reduce the randomness and instability by using different random seeds. In Table~\ref{tab:zest-dev} and Table~\ref{tab:squad}, we demonstrate that performance improvement is significant (p$<$0.05) in multiple settings, \textit{e.g.}, on ZEST dev set when C@75 metric is used. \input{tables/squad} \input{figures_input/ablation} \paragraph{Model Behavior Analysis on ZEST.} ZEST dataset provides a comprehensive analysis protocol by splitting tasks into different generalization types (base, paraphrase, composition, semantic flips, and output structure) and defining four error types (recall, precision, partial, and other). Compared to the BART-Large fine-tuning baseline, our model achieves better performance in ``base'' and ``paraphrase'' categories in the ZEST official test set. We also manually inspected dev set predictions produced by the baseline and our model. We found the predictions corrected by our method span across the four error types. In particular, the proposed method flipped two ``n/a'' predictions into the correct answers in the task ``Which royalty was this dog breed popular with?'' (``base'' category), reducing the recall errors and improving the competence metric. We do not observe more granular model behavioral patterns beyond this point. \paragraph{Study of Data Efficiency.} We study whether \textsc{Hypter} is effective when trained with (1) fewer tasks, while the number of examples per task is unchanged; (2) fewer examples per task, while the number of total tasks is kept constant. We experiment with ZEST and BART-Large, and show the performance in Fig. \ref{fig:ablation}. We observe that \textsc{Hypter} is effective when trained with 75\%/100\% tasks, but does not improve performance with fewer tasks. This is reasonable since \textsc{Hypter} learns at the \textit{task} level (taking one task as an ``example''), and 50\% of the tasks may be insufficient. We also observe performance improvement with 75\%/100\% examples per task, but not with fewer examples. This suggests sufficient number of examples per task is necessary for \textsc{Hypter} to generate effective adapters. \section{Conclusion} In this paper, we introduced \textsc{Hypter}, a framework to improve text-to-text transformer's generalization ability to unseen tasks. \textsc{Hypter} enhances task-specific abilities by inserting adapters generated with a hypernetwork, meanwhile it maintains the model's general task-solving ability by freezing main model parameters. We demonstrated the effectiveness of \textsc{Hypter} on two datasets. Future work may explore teaching models with compositional instructions using \textsc{Hypter}, or propose robust fine-tuning methods that help the model generalize to unseen data. It is also necessary to construct a large dataset of diverse NLP tasks to facilitate future research in this direction. \section{Adapters} \section{Dataset Details} \label{app:dataset} \paragraph{ZEST.} ZEST dataset is released at \url{https://ai2-datasets.s3-us-west-2.amazonaws.com/zest/zest.zip}. ZEST leaderboard is hosted at \url{https://leaderboard.allenai.org/zest/submissions/public}. \paragraph{Synthetic SQuAD.} We build our synthetic dataset from the processed version of SQuAD, Natural Questions and NewsQA in MRQA Shared Task 2019 \cite{fisch2019mrqa} (\url{https://mrqa.github.io/2019/}). We provide the script to reconstruct the data we use in our released code. We list the bi-grams we use to formulate synthetic tasks and their train/dev/test partition in Listing 1. \begin{lstlisting}[language=json,firstnumber=1,caption={Train/Dev/Test Partition in Synthetic SQuAD dataset.}] "train": ["why were", "what years", "who said", "what percent", "when did", "where do", "who is", "how are", "what decade", "how does", "how long", "where was", "what has", "which two", "who was", "who were", "where are", "where does", "what did", "how far", "what organization", "what does", "what group", "what would", "how did", "who has", "who created", "how many", "what name", "what types", "what two", "which city", "who are", "how is", "what event", "what are", "what century", "what area", "whom did", "why was", "who wrote", "why are", "where is", "how old", "when is", "what caused", "who did", "where did", "what happened", "what state", "what kind", "what time", "what famous", "what's the", "what day", "what is", "what company", "what were", "why do", "what new", "what date", "what do", "what color", "which group", "what country", "how can", "what have", "where can", "what period", "which year", "when was", "what other", "what happens", "was the", "what was", "which of", "when were", "what sort", "what city", "what year"], "dev": ["what month", "why is", "what part", "what term", "how was", "how were", "how do", "who led", "which country", "when does"], "test": ["where were", "what political", "what religion", "why did", "what type", "what language", "who had", "what percentage", "what can", "how much"] \end{lstlisting} \vspace{-0.2cm} \section{Training Details} \label{app:training} We use transformers \cite{wolf-etal-2020-transformers} for all our experiments. All experiments are done with one single GPU. We use NVIDIA Quadro RTX 8000, NVIDIA Quadro RTX 6000, or NVIDIA GeForce RTX 2080 Ti, depending on availability. For text-to-text model fine-tuning, we select learning rate from \{1e-5, 3e-5, 5e-5\}, and select the total number of epochs from \{5, 10, 15, 20, 30\} for ZEST and \{10, 20, 30, 50, 100\} for synthetic SQuAD. We use a fixed batch size of 32. For hypernetwork training, we train up to 100 epochs (one epoch here refers to an iteration over all tasks). We update the hypernetwork every $b$ tasks, and we call $b$ as task batch size. When learning from one task, we sample $b'$ examples within this task, and we call $b'$ as the example batch size. We greedily and sequentially select adapter width $d$ from \{4,8,16,32\}, learning rate $\alpha$ from \{3e-6, 1e-5, 3e-5, 1e-4\}, $b$ from \{4,8,16,32\}, $b'$ from \{4,8,16,32\}, based on dev set performance. \section{Additional Baseline} Another reasonable baseline is to fine-tune a text-to-text model together with randomly initialized adapters plugged in it. We experiment with this method using BART-Large and list the performance in Table~\ref{tab:zest-ftwadapter}. We do not observe significant differences between the two methods (p=0.8840 for C@75, p=0.8118 for C@90 in two-tailed paired t-test). \input{tables/zest_ftwadapter} \section{Dev Set Performance of Models Submitted to ZEST Leaderboard} In Table~\ref{tab:zest-submitted} we present the dev performance of models submitted to the leaderboard. The submitted models are the ``first-runs'' in the 7-run series, as we add the 7-run experiments and significance test later on, following a reviewer's suggestion. \input{tables/zest_submitted} \section{Discussion} It is worth noting that the efficacy of \textsc{Hypter} is at the cost of introducing new parameters in the hypernetwork. To generate adapter parameters, more parameters are introduced and trained in the hypernetwork. One may achieve better generalization ability to unseen tasks with larger pre-trained models with billions of parameters. In this case, we consider \textsc{Hypter} as an alternative by augmenting a medium-sized pre-trained model with a hypernetwork. Meanwhile, we highlight our contribution to be the concept of generating task-specific adapters from descriptions and \textsc{Hypter}'s task-level training procedure. \section{Related Work} \paragraph{Zero-shot Learning with Transformers.} Zero-shot learning (ZSL) has been explored for various NLP tasks, including text classification \cite{yin-etal-2019-benchmarking}, entity linking \cite{logeswaran-etal-2019-zero} and entity typing \cite{obeidat-etal-2019-description}. Several works study cross-task transfer by unifying the input-output format, \textit{e.g.}, relation extraction as machine reading comprehension \cite{levy-etal-2017-zero}, named entity recognition as machine reading comprehension \cite{li-etal-2020-unified}. Such formulation allows generalization to unseen relation or named entity types at test time. Learning from task descriptions \cite{weller-etal-2020-learning} and instructions \cite{Mishra2021NaturalIB} can be considered as a sub-category in zero-shot learning, with the goal of generalizing to unseen tasks during inference. \paragraph{Adapters for Transformers.} \citet{pmlr-v97-houlsby19a} proposed adapter layers for parameter-efficient transfer learning in NLP. Adapter layers, which adopt a bottleneck architecture with two linear layers, are added after each multi-headed attention layer and each feed-foward layer in a pre-trained transformer. Adapters have been recently applied to multi-lingual settings, with successes in NER, QA and commonsense reasoning \cite{pfeiffer-etal-2020-mad,philip-etal-2020-monolingual,artetxe-etal-2020-cross}. \paragraph{Hypernetworks and Contextual Parameter Generators.} Hypernetwork \cite{Ha2017HyperNetworks} is a broad concept of ``using one network to generate the weights for another network''. This concept has been broadly applied to visual reasoning \cite{perez2018film}, zero-shot image classification \cite{jin-etal-2020-language}, etc. Closely related to our work, UDapter \cite{ustun-etal-2020-udapter} studies multilingual dependency parsing by generating adapter parameters. Our work is more generalizable as we do not restrict task format (dependency parsing v.s. general text-to-text tasks) or relations between sub-tasks (cross-lingual tasks v.s. tasks with text-form descriptions).
{'timestamp': '2021-06-16T02:12:01', 'yymm': '2101', 'arxiv_id': '2101.00420', 'language': 'en', 'url': 'https://arxiv.org/abs/2101.00420'}
arxiv
\section{Introduction} Until recently, the standard methodology in NLP was to design task-specific models, such as BiDAF for question answering \cite{Seo2017BidirectionalAF} and ESIM for natural language inference \cite{chen-etal-2017-enhanced}. With the introduction of pretraining, many of these models were replaced with simple output layers, effectively fine-tuning the transformer layers below to perform the traditional model's function \cite{gpt1}. A notable exception to this trend is \textit{coreference resolution}, where a multi-layer task-specific model \cite{lee-etal-2017-end, lee-etal-2018-higher} is appended to a pretrained model \cite{joshi-etal-2019-bert, joshi-etal-2020-spanbert}. This model uses intricate span and span-pair representations, a representation refinement mechanism, handcrafted features, pruning heuristics, and more. While the model is highly effective, it comes at a great cost in memory consumption, limiting the amount of examples that can be loaded on a large GPU to a single document, which often needs to be truncated or processed in sliding windows. Can this coreference model be simplified? We present \textit{start-to-end} (s2e) coreference resolution: a simple coreference model that does \textit{not} construct span representations. Instead, our model propagates information to the span boundaries (i.e., its start and end tokens) and computes mention and antecedent scores through a series of bilinear functions over their contextualized representations. Our model has a significantly lighter memory footprint, allowing us to process multiple documents in a single batch, with no truncation or sliding windows. We do not use any handcrafted features, priors, or pruning heuristics. Experiments show that our minimalist approach performs on par with the standard model, despite removing a significant amount of complexity, parameters, and heuristics. Without any hyperparameter tuning, our model achieves 80.3 F1 on the English OntoNotes dataset \cite{pradhan-etal-2012-conll}, with the best comparable baseline reaching 80.2 F1 \cite{joshi-etal-2020-spanbert}, while consuming less than a third of the memory. These results suggest that transformers can learn even difficult structured prediction tasks such as coreference resolution without investing in complex task-specific architectures.\footnote{Our code and model are publicly available: \url{https://github.com/yuvalkirstain/s2e-coref}} \section{Background: Coreference Resolution} \label{sec:background} Coreference resolution is the task of clustering multiple mentions of the same entity within a given text. It is typically modeled by identifying entity mentions (contiguous spans of text), and predicting an \textit{antecedent} mention $a$ for each span $q$ (query) that refers to a previously-mentioned entity, or a null-span $\varepsilon$ otherwise. \citet{lee-etal-2017-end,lee-etal-2018-higher} introduce \textit{coarse-to-fine} (c2f), an end-to-end model for coreference resolution that predicts, for each span $q$, an antecedent probability distribution over the candidate spans $c$: \begin{align*} P \left( a = c | q \right) = \frac{\exp(f(c, q))}{\sum_{c^\prime} \exp(f(c^\prime, q))} \end{align*} Here, $f(c, q)$ is a function that scores how likely $c$ is to be an antecedent of $q$. This function is comprised of mention scores $f_m(c), f_m(q)$ (i.e. is the given span a mention?) and a separate antecedent score $f_a(c, q)$: \begin{align*} f(c, q) = \begin{cases} f_m(c) + f_m(q) + f_a(c, q) & c \neq \varepsilon \\ 0 & c = \varepsilon \end{cases} \end{align*} Our model (Section~\ref{sec:model}) follows the scoring function above, but differs in how the different elements $f_m(\cdot)$ and $f_a(\cdot)$ are computed. We now describe how $f_m$ and $f_a$ are implemented in the c2f model. \paragraph{Scoring Mentions} In the c2f model, the mention score $f_m(q)$ is derived from a vector representation $\V{v}_q$ of the span $q$ (analogously, $f_m(c)$ is computed from $\V{v}_c$). Let $\V{x}_i$ be the contextualized representation of the $i$-th token produced by the underlying encoder. Every span representation is a concatenation of four elements: the representations of the span's start and end tokens $\V{x}_{q_s}, \V{x}_{q_e}$, a weighted average of the span's tokens $\hat{\V{x}}_q$ computed via self-attentive pooling, and a feature vector $\phi(q)$ that represents the span's length: \begin{align*} \V{v}_q = [\V{x}_{q_s}; \V{x}_{q_e}; \hat{\V{x}}_q; \phi(q)] \end{align*} The mention score $f_m(q)$ is then computed from the span representation $\V{v}_q$: \begin{align*} f_m(q) = \V{v}_m \cdot \text{ReLU}(\V{W}_m \V{v}_q) \end{align*} where $\V{W}_m$ and $\V{v}_m$ are learned parameters. Then, span representations are enhanced with more global information through a refinement process that interpolates each span representation with a weighted average of its candidate antecedents. More recently, \citet{xu-choi-2020-revealing} demonstrated that this span refinement technique, as well as other modifications to it (e.g. entity equalization \cite{kantor-globerson-2019-coreference}) do not improve performance. \paragraph{Scoring Antecedents} The antecedent score $f_a(c, q)$ is derived from a vector representation of the span \textit{pair} $\V{v}_{(c, q)}$. This, in turn, is a function of the individual span representations $\V{v}_c$ and $\V{v}_q$, as well as a vector of handcrafted features $\phi(c, q)$ such as the distance between the spans $c$ and $q$, the document's genre, and whether $c$ and $q$ were said/written by the same speaker: \begin{align*} \V{v}_{(c, q)} = [ \V{v}_c ; \V{v}_q ; \V{v}_c \circ \V{v}_q ; \phi(c, q) ] \end{align*} The antecedent score $f_a(c, q)$ is parameterized with $\V{W}_a$ and $\V{v}_a$ as follows: \begin{align*} f_a(c, q) = \V{v}_a \cdot \text{ReLU}(\V{W}_a \V{v}_{(c, q)}) \end{align*} \paragraph{Pruning} Holding the vector representation of every possible span in memory has a space complexity of $O(n^2 d)$ (where $n$ is the number of input tokens, and $d$ is the model's hidden dimension). This problem becomes even more acute when considering the space of span \textit{pairs} ($O(n^4 d)$). Since this is not feasible, candidate mentions and antecedents are pruned through a variety of model-based and heuristic methods. Specifically, mention spans are limited to a certain maximum length $\ell$. The remaining mentions are then ranked according to their scores $f_m(\cdot)$, and only the top $\lambda n$ are retained, while avoiding overlapping spans. Antecedents (span pairs) are further pruned using a lightweight antecedent scoring function (which is added to the overall antecedent score), retaining only a constant number of antecedent candidates $c$ for each target mention $q$. \paragraph{Training} For each remaining span $q$, the training objective optimizes the marginal log-likelihood of all of its unpruned gold antecedents $c$, as there may be multiple mentions referring to the same entity: \begin{align*} \log \sum_{c} P(a = c|q) \end{align*} \paragraph{Processing Long Documents} Due to the c2f model's high memory consumption and the limited sequence length of most pretrained transformers, documents are often split into segments of a few hundred tokens each \cite{joshi-etal-2019-bert}. Recent work on efficient transformers \cite{beltagy2020longformer} has been able to shift towards processing complete documents, albeit with a smaller model (base) and only one training example per batch. \section{Model}\label{sec:model} We present \textit{start-to-end} (s2e) coreference resolution, a simpler and more efficient model with respect to c2f (Section~\ref{sec:background}). Our model utilizes the endpoints of a span (rather than all span tokens) to compute the mention and antecedent scores $f_m (\cdot)$ and $f_a (\cdot, \cdot)$ \textit{without} constructing span or span-pair representations; instead, we rely on a combination of lightweight bilinear functions between pairs of endpoint token representations. Furthermore, our model does not use any handcrafted features, does not prune antecedents, and prunes mention candidates solely based on their mention score $f_m(q)$. Our computation begins by extracting a \textit{start} and \textit{end} token representation from the contextualized representation $\V{x}$ of each token in the sequence: \begin{align*} \V{m}^{s} = \text{GeLU} (\V{W}_m^s \V{x}) \qquad \V{m}^{e} = \text{GeLU} (\V{W}_m^e \V{x}) \end{align*} We then compute each mention score as a biaffine product over the start and end tokens' representations, similar to \citet{dozat2016deep}: \begin{align*} f_m(q) = \V{v}_{s} \cdot \V{m}^{s}_{q_s} + \V{v}_{e} \cdot \V{m}^{e}_{q_e} + \V{m}^{s}_{q_s} \cdot \V{B}_m \cdot \V{m}^{e}_{q_e} \end{align*} The first two factors measure how likely the span's start/end token $q_s$/$q_e$ is a beginning/ending of an entity mention. The third measures whether those tokens are the boundary points of the \textit{same} entity mention. The vectors $\V{v}_{s}, \V{v}_{e}$ and the matrix $\V{B}_{m}$ are the trainable parameters of our mention scoring function $f_m$. We efficiently compute mention scores for all possible spans while masking spans that exceed a certain length $\ell$.\footnote{While pruning by length is not necessary for efficiency, we found it to be a good inductive bias.} We then retain only the top-scoring $\lambda n$ mention candidates to avoid $O(n^4)$ complexity when computing antecedents. Similarly, we extract \textit{start} and \textit{end} token representations for the antecedent scoring function $f_a$: \begin{align*} \V{a}^{s} = \text{GeLU} (\mathbf{W}^s_a \V{x}) \qquad \V{a}^{e} = \text{GeLU} (\mathbf{W}^e_a \V{x}) \end{align*} Then, we sum over four bilinear functions: \begin{align*} f_a(c, q) &= \V{a}^{s}_{c_s} \cdot \V{B}_a^{ss} \cdot \V{a}^{s}_{q_s} + \V{a}^{s}_{c_s} \cdot \V{B}_a^{se} \cdot \V{a}^{e}_{q_e} \\ &+ \V{a}^{e}_{c_e} \cdot \V{B}_a^{es} \cdot \V{a}^{s}_{q_s} + \V{a}^{e}_{c_e} \cdot \V{B}_a^{ee} \cdot \V{a}^{e}_{q_e} \end{align*} Each component measures the compatibility of the spans $c$ and $q$ by an interaction between different boundary tokens of each span. The first component compares the \textit{start} representations of $c$ and $q$, while the fourth component compares the \textit{end} representations. The second and third facilitate a cross-comparison of the \textit{start} token of span $c$ with the \textit{end} token of span $q$, and vice versa. Figure~\ref{fig:illustration} (bottom) illustrates these interactions. This calculation is equivalent to computing a bilinear transformation between the concatenation of each span's boundary tokens' representations: \begin{align*} f_a(c, q) = [\V{a}^{s}_{c_s} ; \V{a}^{e}_{c_e}] \cdot \V{B}_a \cdot [\V{a}^{s}_{q_s} ; \V{a}^{e}_{q_e}] \end{align*} However, computing the factors \textit{directly} bypasses the need to create $n^2$ explicit span representations. Thus, we avoid a theoretical space complexity of $O(n^2 d)$, while keeping it equivalent to that of a transformer layer, namely $O(n^2 + nd)$. \section{Experiments} \label{section:experiments} \paragraph{Dataset} We train and evaluate on two datasets: the document-level English OntoNotes 5.0 dataset \cite{pradhan-etal-2012-conll}, and the GAP coreference dataset \cite{webster-etal-2018-mind}. The OntoNotes dataset contains speaker metadata, which the baselines use through a hand-crafted feature that indicates whether two spans were uttered by the same speaker. Instead, we insert the speaker's name to the text every time the speaker changes, making the metadata available to any model. \paragraph{Pretrained Model} We use Longformer-Large \cite{beltagy2020longformer} as our underlying pretrained model, since it is able to process long documents without resorting to sliding windows or truncation. \paragraph{Baseline} We consider Joshi et al.'s \citeyearpar{joshi-etal-2019-bert} expansion to the c2f model as our baseline. Specifically, we use the implementation of \citet{xu-choi-2020-revealing} with minor adaptations for supporting Longformer. We do not use higher-order inference, as \citet{xu-choi-2020-revealing} demonstrate that it does not result in significant improvements. We train the baseline model over three pretrained models: Longformer-Base, Longformer-Large, and SpanBERT-Large \cite{beltagy2020longformer, joshi-etal-2020-spanbert}. \paragraph{Hyperparameters} All models use the same hyperparameters as the baseline. The only hyperparameters we change are the maximum sequence length and batch size, which we enlarge to fit as many tokens as possible into a 32GB GPU.\footnote{We made one exception, and tried to tune the Longformer-Large baseline's hyperparameters. Despite our efforts, it still performs worse than Longformer-Base.} For our model, we use dynamic batching with 5,000 max tokens, which allows us to fit an average of 5-6 documents in every training batch. The baseline, however, has a much higher memory footprint, and is barely able to fit a single example with Longformer-Base (max 4,096 tokens). When combining the baseline with SpanBERT-Large or Longformer-Large, the baseline must resort to sliding windows to process the full document (512 and 2,048 tokens, respectively). \paragraph{Performance} Table \ref{table:results} and Table \ref{table:gap} show that, despite our model's simplicity, it performs as well as the best performing baseline. Our model with Longformer-Large achieves 80.3 F1 on OntoNotes, while the best performing baseline achieves 80.2 F1. When the baseline model is combined with either version of Longformer, it is not able to reach the same performance level as our model. We see similar trends for GAP. Our findings indicate that there is little to lose from simplifying the coreference resolution architecture, while there are potential gains to be had from optimizing with larger batches. \paragraph{Efficiency} We also compare our model's memory usage using the OntoNotes development set. Table~\ref{tab:efficiency} shows that our implementation is at least three times more memory efficient than the baseline. This improvement results from a combination of three factors: (1) the fact that our model is lighter on memory and does not need to construct span or span-pair representations, (2) our simplified framework, which does not use sliding windows, and (3) our implementation, which was written ``from scratch'', and might thus be more (or less) efficient than the original. \section{Related Work} Recent work on memory-efficient coreference resolution sacrifices speed and parallelism for guarantees on memory consumption. \citet{xia-etal-2020-incremental} and \citet{toshniwal-etal-2020-learning} present variants of the c2f model \cite{lee-etal-2017-end,lee-etal-2018-higher} that use an iterative process to maintain a fixed number of span representations at all times. Specifically, spans are processed sequentially, either joining existing clusters or forming new ones, and an eviction mechanism ensures the use of a constant number of clusters. While these approach constrains the space complexity, their sequential nature slows down the computation, and slightly deteriorates the performance. Our approach is able to alleviate the large memory footprint of c2f while maintaining fast parallel processing and high performance. CorefQA \cite{wu-etal-2020-corefqa} propose an alternative solution by casting the task of coreference resolution as one of extractive question answering. It first detects potential mentions, and then creates dedicated queries for each one, creating a pseudo-question-answering instance for each candidate mention. This method significantly improves performance, but at the cost of processing hundreds of individual context-question-answer instances for a single document, substantially increasing execution time. Our work provides a simple alternative, which can scale well in terms of both speed and memory \section{Conclusion} We introduce a new model for coreference resolution, suggesting a lightweight alternative to the sophisticated model that has dominated the task over the past few years. Our model is competitive with the baseline, while being simpler and more efficient. This finding once again demonstrates the spectacular ability of deep pretrained transformers to model complex natural language phenomena. \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} The following instructions are directed to authors of papers submitted to ACL 2020 or accepted for publication in its proceedings. All authors are required to adhere to these specifications. Authors are required to provide a Portable Document Format (PDF) version of their papers. \textbf{The proceedings are designed for printing on A4 paper.} \section{Electronically-available resources} ACL provides this description and accompanying style files at \begin{quote} \url{http://acl2020.org/downloads/acl2020-templates.zip} \end{quote} We strongly recommend the use of these style files, which have been appropriately tailored for the ACL 2020 proceedings. \paragraph{\LaTeX-specific details:} The templates include the \LaTeX2e{} source (\texttt{\small acl2020.tex}), the \LaTeX2e{} style file used to format it (\texttt{\small acl2020.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 ACL 2020. Authors of papers accepted for presentation at ACL 2020 must notify the program chairs by the camera-ready deadline as to whether the paper will be presented. We will not accept for publication or presentation the papers that overlap significantly in content or results with papers that will be (or have been) published elsewhere. Authors submitting more than one paper to ACL 2020 must ensure that submissions do not overlap significantly (>25\%) with each other in content or results. \section{Formatting Instructions} Manuscripts must be in two-column format. Exceptions to the two-column format include the title, authors' names and complete addresses, which must be centered at the top of the first page, and any full-width figures or tables (see the guidelines in Section~\ref{ssec:title-authors}). \textbf{Type single-spaced.} Start all pages directly under the top margin. The manuscript should be printed single-sided and its length should not exceed the maximum page limit described in Section~\ref{sec:length}. Pages should be numbered in the version submitted for review, but \textbf{pages should not be numbered in the camera-ready version}. \paragraph{\LaTeX-specific details:} The style files will generate page numbers when {\small\verb|\aclfinalcopy|} is commented out, and remove them otherwise. \subsection{File Format} \label{sect:pdf} For the production of the electronic manuscript you must use Adobe's Portable Document Format (PDF). Please make sure that your PDF file includes all the necessary fonts (especially tree diagrams, symbols, and fonts with Asian characters). When you print or create the PDF file, there is usually an option in your printer setup to include none, all or just non-standard fonts. Please make sure that you select the option of including ALL the fonts. \textbf{Before sending it, test your PDF by printing it from a computer different from the one where it was created.} Moreover, some word processors may generate very large PDF files, where each page is rendered as an image. Such images may reproduce poorly. In this case, try alternative ways to obtain the PDF. One way on some systems is to install a driver for a postscript printer, send your document to the printer specifying ``Output to a file'', then convert the file to PDF. It is of utmost importance to specify the \textbf{A4 format} (21 cm x 29.7 cm) when formatting the paper. Print-outs of the PDF file on A4 paper should be identical to the hardcopy version. If you cannot meet the above requirements about the production of your electronic submission, please contact the publication chairs as soon as possible. \paragraph{\LaTeX-specific details:} PDF files are usually produced from \LaTeX{} using the \texttt{\small pdflatex} command. If your version of \LaTeX{} produces Postscript files, \texttt{\small ps2pdf} or \texttt{\small dvipdf} can convert these to PDF. To ensure A4 format in \LaTeX, use the command {\small\verb|\special{papersize=210mm,297mm}|} in the \LaTeX{} preamble (below the {\small\verb|\usepackage|} commands) and use \texttt{\small dvipdf} and/or \texttt{\small pdflatex}; or specify \texttt{\small -t a4} when working with \texttt{\small dvips}. \subsection{Layout} \label{ssec:layout} Format manuscripts two columns to a page, in the manner these instructions are formatted. The exact dimensions for a page on A4 paper are: \begin{itemize} \item Left and right margins: 2.5 cm \item Top margin: 2.5 cm \item Bottom margin: 2.5 cm \item Column width: 7.7 cm \item Column height: 24.7 cm \item Gap between columns: 0.6 cm \end{itemize} \noindent Papers should not be submitted on any other paper size. If you cannot meet the above requirements about the production of your electronic submission, please contact the publication chairs above as soon as possible. \subsection{Fonts} For reasons of uniformity, Adobe's \textbf{Times Roman} font should be used. If Times Roman is unavailable, you may use Times New Roman or \textbf{Computer Modern Roman}. Table~\ref{font-table} specifies what font sizes and styles must be used for each type of text in the manuscript. \begin{table} \centering \begin{tabular}{lrl} \hline \textbf{Type of Text} & \textbf{Font Size} & \textbf{Style} \\ \hline paper title & 15 pt & bold \\ author names & 12 pt & bold \\ author affiliation & 12 pt & \\ the word ``Abstract'' & 12 pt & bold \\ section titles & 12 pt & bold \\ subsection titles & 11 pt & bold \\ document text & 11 pt &\\ captions & 10 pt & \\ abstract text & 10 pt & \\ bibliography & 10 pt & \\ footnotes & 9 pt & \\ \hline \end{tabular} \caption{\label{font-table} Font guide. } \end{table} \paragraph{\LaTeX-specific details:} To use Times Roman in \LaTeX2e{}, put the following in the preamble: \begin{quote} \small \begin{verbatim} \usepackage{times} \usepackage{latexsym} \end{verbatim} \end{quote} \subsection{Ruler} A printed ruler (line numbers in the left and right margins of the article) should be presented in the version submitted for review, so that reviewers may comment on particular lines in the paper without circumlocution. The presence or absence of the ruler should not change the appearance of any other content on the page. The camera ready copy should not contain a ruler. \paragraph{Reviewers:} note that the ruler measurements may not align well with lines in the paper -- this turns out to be very difficult to do well when the paper contains many figures and equations, and, when done, looks ugly. In most cases one would expect that the approximate location will be adequate, although you can also use fractional references (\emph{e.g.}, this line ends at mark $295.5$). \paragraph{\LaTeX-specific details:} The style files will generate the ruler when {\small\verb|\aclfinalcopy|} is commented out, and remove it otherwise. \subsection{Title and Authors} \label{ssec:title-authors} Center the title, author's name(s) and affiliation(s) across both columns. Do not use footnotes for affiliations. Place the title centered at the top of the first page, in a 15-point bold font. Long titles should be typed on two lines without a blank line intervening. Put the title 2.5 cm from the top of the page, followed by a blank line, then the author's names(s), and the affiliation on the following line. Do not use only initials for given names (middle initials are allowed). Do not format surnames in all capitals (\emph{e.g.}, use ``Mitchell'' not ``MITCHELL''). Do not format title and section headings in all capitals except for proper names (such as ``BLEU'') that are conventionally in all capitals. The affiliation should contain the author's complete address, and if possible, an electronic mail address. The title, author names and addresses should be completely identical to those entered to the electronical paper submission website in order to maintain the consistency of author information among all publications of the conference. If they are different, the publication chairs may resolve the difference without consulting with you; so it is in your own interest to double-check that the information is consistent. Start the body of the first page 7.5 cm from the top of the page. \textbf{Even in the anonymous version of the paper, you should maintain space for names and addresses so that they will fit in the final (accepted) version.} \subsection{Abstract} Use two-column format when you begin the abstract. Type the abstract at the beginning of the first column. The width of the abstract text should be smaller than the width of the columns for the text in the body of the paper by 0.6 cm on each side. Center the word \textbf{Abstract} in a 12 point bold font above the body of the abstract. The abstract should be a concise summary of the general thesis and conclusions of the paper. It should be no longer than 200 words. The abstract text should be in 10 point font. \subsection{Text} Begin typing the main body of the text immediately after the abstract, observing the two-column format as shown in the present document. Indent 0.4 cm when starting a new paragraph. \subsection{Sections} Format section and subsection headings in the style shown on the present document. Use numbered sections (Arabic numerals) to facilitate cross references. Number subsections with the section number and the subsection number separated by a dot, in Arabic numerals. \subsection{Footnotes} Put footnotes at the bottom of the page and use 9 point font. They may be numbered or referred to by asterisks or other symbols.\footnote{This is how a footnote should appear.} Footnotes should be separated from the text by a line.\footnote{Note the line separating the footnotes from the text.} \subsection{Graphics} Place figures, tables, and photographs in the paper near where they are first discussed, rather than at the end, if possible. Wide illustrations may run across both columns. Color is allowed, but adhere to Section~\ref{ssec:accessibility}'s guidelines on accessibility. \paragraph{Captions:} Provide a caption for every illustration; number each one sequentially in the form: ``Figure 1. Caption of the Figure.'' ``Table 1. Caption of the Table.'' Type the captions of the figures and tables below the body, using 10 point text. Captions should be placed below illustrations. Captions that are one line are centered (see Table~\ref{font-table}). Captions longer than one line are left-aligned (see Table~\ref{tab:accents}). \begin{table} \centering \begin{tabular}{lc} \hline \textbf{Command} & \textbf{Output}\\ \hline \verb|{\"a}| & {\"a} \\ \verb|{\^e}| & {\^e} \\ \verb|{\`i}| & {\`i} \\ \verb|{\.I}| & {\.I} \\ \verb|{\o}| & {\o} \\ \verb|{\'u}| & {\'u} \\ \verb|{\aa}| & {\aa} \\\hline \end{tabular} \begin{tabular}{lc} \hline \textbf{Command} & \textbf{Output}\\ \hline \verb|{\c c}| & {\c c} \\ \verb|{\u g}| & {\u g} \\ \verb|{\l}| & {\l} \\ \verb|{\~n}| & {\~n} \\ \verb|{\H o}| & {\H o} \\ \verb|{\v r}| & {\v r} \\ \verb|{\ss}| & {\ss} \\ \hline \end{tabular} \caption{Example commands for accented characters, to be used in, \emph{e.g.}, \BibTeX\ names.}\label{tab:accents} \end{table} \paragraph{\LaTeX-specific details:} The style files are compatible with the caption and subcaption packages; do not add optional arguments. \textbf{Do not override the default caption sizes.} \subsection{Hyperlinks} Within-document and external hyperlinks are indicated with Dark Blue text, Color Hex \#000099. \subsection{Citations} Citations within the text appear in parentheses as~\citep{Gusfield:97} or, if the author's name appears in the text itself, as \citet{Gusfield:97}. Append lowercase letters to the year in cases of ambiguities. Treat double authors as in~\citep{Aho:72}, but write as in~\citep{Chandra:81} when more than two authors are involved. Collapse multiple citations as in~\citep{Gusfield:97,Aho:72}. Refrain from using full citations as sentence constituents. Instead of \begin{quote} ``\citep{Gusfield:97} showed that ...'' \end{quote} write \begin{quote} ``\citet{Gusfield:97} showed that ...'' \end{quote} \begin{table*} \centering \begin{tabular}{lll} \hline \textbf{Output} & \textbf{natbib command} & \textbf{Old ACL-style command}\\ \hline \citep{Gusfield:97} & \small\verb|\citep| & \small\verb|\cite| \\ \citealp{Gusfield:97} & \small\verb|\citealp| & no equivalent \\ \citet{Gusfield:97} & \small\verb|\citet| & \small\verb|\newcite| \\ \citeyearpar{Gusfield:97} & \small\verb|\citeyearpar| & \small\verb|\shortcite| \\ \hline \end{tabular} \caption{\label{citation-guide} Citation commands supported by the style file. The style is based on the natbib package and supports all natbib citation commands. It also supports commands defined in previous ACL style files for compatibility. } \end{table*} \paragraph{\LaTeX-specific details:} Table~\ref{citation-guide} shows the syntax supported by the style files. We encourage you to use the natbib styles. You can use the command {\small\verb|\citet|} (cite in text) to get ``author (year)'' citations as in \citet{Gusfield:97}. You can use the command {\small\verb|\citep|} (cite in parentheses) to get ``(author, year)'' citations as in \citep{Gusfield:97}. You can use the command {\small\verb|\citealp|} (alternative cite without parentheses) to get ``author year'' citations (which is useful for using citations within parentheses, as in \citealp{Gusfield:97}). \subsection{References} Gather the full set of references together under the heading \textbf{References}; place the section before any Appendices. Arrange the references alphabetically by first author, rather than by order of occurrence in the text. Provide as complete a citation as possible, using a consistent format, such as the one for \emph{Computational Linguistics\/} or the one in the \emph{Publication Manual of the American Psychological Association\/}~\citep{APA:83}. Use full names for authors, not just initials. Submissions should accurately reference prior and related work, including code and data. If a piece of prior work appeared in multiple venues, the version that appeared in a refereed, archival venue should be referenced. If multiple versions of a piece of prior work exist, the one used by the authors should be referenced. Authors should not rely on automated citation indices to provide accurate references for prior and related work. The following text cites various types of articles so that the references section of the present document will include them. \begin{itemize} \item Example article in journal: \citep{Ando2005}. \item Example article in proceedings, with location: \citep{borschinger-johnson-2011-particle}. \item Example article in proceedings, without location: \citep{andrew2007scalable}. \item Example arxiv paper: \citep{rasooli-tetrault-2015}. \end{itemize} \paragraph{\LaTeX-specific details:} The \LaTeX{} and Bib\TeX{} style files provided roughly follow the American Psychological Association format. If your own bib file is named \texttt{\small acl2020.bib}, then placing the following before any appendices in your \LaTeX{} file will generate the references section for you: \begin{quote}\small \verb|\bibliographystyle{acl_natbib}|\\ \verb| \section*{Acknowledgements} This research was funded by the Blavatnik Fund, the Alon Scholarship, Intel Corporation, and the Yandex Initiative in Machine Learning. \bibliographystyle{acl_natbib}
{'timestamp': '2021-06-01T02:41:24', 'yymm': '2101', 'arxiv_id': '2101.00434', 'language': 'en', 'url': 'https://arxiv.org/abs/2101.00434'}
arxiv
\section{Uncertainty-sensitive Action Recognition} \subsection{Problem Definition: Reliable Confidence Measures} \label{sec:definition} We introduce the \emph{reliability of model confidence benchmark} to supervised multi-class activity recognition, where the models are usually validated via top-1 accuracy only~\cite{martin2019drive,kuehne2013hmdb51}. Given an input video clip $x$ with a ground-truth label $a_{true}$ and the set of all possible target classes $a \in \mathcal{A}\{1,...,m\}$, let $m$ be our activity recognition model predicting an activity label $a_{pred}$ and the corresponding model confidence value $conf(a_{pred})$: $m(x) = [a_{pred}, conf(a_{pred})]$. A \emph{reliable} model ought to not only learn to predict the correct activity (\ie~$a_{pred} = a_{true}$), but also give us well-calibrated confidence estimates $conf(a_{pred})$, which indeed reflect the probability of a successful outcome $\mathcal{P}(a_{pred}= a_{true})$. A perfectly calibrated~\ie~reliable model is often formalized as $\mathcal{P} (a_{pred}= a_{true}| conf(a_{pred}) = p) = p, \quad \forall p \in [0, 1]$ \cite{guo2017calibration}. In other words, the inadequacy of model confidence values is directly linked to the gap between the average model confidence and model accuracy. To quantify the calibration quality of the models' confidence scores, we use Expected Calibration Error (ECE) metric~\cite{guo2017calibration}. To compute ECE, we divide the space $[0, 1]$ of possible probabilities into $K$ segments (in our case, $K = 10$). We then compute the model accuracy and average model confidence for samples belonging to each individual segment. In a perfectly calibrated model, the difference between accuracy and average confidence of the individual segments would be zero. To quantify how well we can rely on the confidence scores produced by the model, we compute the distance between the mean confidence and accuracy in each bin and then calculate the average over all such segments, weighted by the number of samples in each bin. Formally, the expected calibration error is defined as: \begin{equation} ECE = \sum_{i = 1}^{K} \frac{N_{bin_i}}{N_{total}} |acc(bin_i) - conf(bin_i)|, \end{equation} where $N_{bin_i}$ is the number of samples with probability values inside the bounds of $bin_i$, $acc(bin_i)$ and $ conf(bin_i)$ are the accuracy and average confidence of such examples respectively and $N_{total}$ is the total number of data points (in all bins). The expected calibration error can be visualized intuitively using \emph{reliability diagrams} (example provided in Figure \ref{fig:reliability_explanation}). First, the space of possible probabilities (X-axis) is discretized into $K$ equally sized bins (we choose $K=10$), as previously described for the ECE calculation. Samples with predicted confidence between $0$ and $0.1$ fall into the first bin, between $0.1$ and $0.2$ into the second bin and so on. For each segment, we plot a bar with height corresponding to the accuracy in the current segment. In an ideal case, the accuracy should be equal to the average confidence score inside this bin, meaning, that the bars should have the height of the diagonal. As we see in Figure~\ref{fig:reliability_explanation}, these are often beyond the diagonal if the Pseudo 3D ResNet model probabilities are used out of the box. This means that the model tends to be overly confident, as the accuracy in the individual bins tends to be \emph{lower} than the probability produced by the model. \begin{figure}\centering \includegraphics[width=0.5\textwidth,trim={1.8cm 4.6cm 2.25cm 3.0cm},clip]{figures/reliability_diag_expl.pdf} \caption{Reliability diagrams of a model with poor confidence estimates (left) and a well-calibrated model (right). The illustrated data are the confidence values of the Pseudo 3D ResNet a the Drive\&Act validation split before and after the improvement with the CARING calibration network. } \label{fig:reliability_explanation} \vspace{-0.3cm} \end{figure} \subsection{Backbone Neural Architectures} We consider two prominent spatiotemporal CNNs for activity recognition: Inflated 3D ConvNet~\cite{carreira2017quo} and Pseudo3D ResNet~\cite{qiu2017learning}. Inflated 3D ConvNet deals with the spatial and temporal dimensions of our input by leveraging hierarchically stacked 3D-convolution and -pooling kernels with the size of $3\times 3\times 3$. P3D ResNet, on the other hand, mimics 3D convolutions by applying a filter on the spatial domain ($3\times3\times1$) followed by one in the temporal dimension ($1\times1\times3$). As in other CNNs, the neurons of the last fully-connected layer are referred to as a \emph{logit vector} $\vec{y}$ with its activations $y_a$ representing the \emph{not normalized} scores of an action $a$ being the current class. A straight-forward way to obtain the model confidence which mimics a probability function, is to normalize the scores using Softmax: $conf(a_{pred}) = \max\limits_{a \in \mathcal{A}} \frac{exp(y_a)}{\sum\limits_{\hat{a} \in \mathcal{A}} exp(y_{\hat{a}})}$. During training, the cross-entropy loss is computed using the Softmax-normalized output, optimizing the network for high top-1 accuracy. Both models have shown impressive results in activity recognition~\cite{martin2019drive,carreira2017quo,qiu2017learning}, but an evaluation of how well their Softmax-values indeed reflect the model uncertainty remains an open question and is addressed in this work. \subsection{Calibration via Temperature Scaling} \label{sec:temperature} A popular way for obtaining better confidence estimates from CNN logits in image recognition is \emph{temperature scaling}~\cite{guo2017calibration}. Temperature scaling simplifies Platt scaling~\cite{platt1999probabilistic}, and is based on learning a single parameter $\tau$ which is further used to ``soften'' the model logits. The logits are therefore divided by $\tau$ before applying the Softmax function $\vec{y}_{scaled} = \vec{y}/\tau$. With $\tau>1$ the resulting probabilities become smoother, moving towards $\frac{1}{m}$, where $m$ is the number of classes. Contrary, scaled probability would approach $1$ as $\tau$ becomes closer to $0$. After the neural network is trained for supervised classification in a normal way, we fix the model weights and optimize $\tau$ on a held-out validation set using Negative-Log-Likelihood. Despite method simplicity, temperature scaling has been highly effective for obtaining well-calibrated image recognition CNNs, surpassing heavier methods such as Histogram binning and Isotonic Regression~\cite{guo2017calibration}. As this method has not been explored for spatiotemporal video classification CNNs yet, we augment the Inflated 3D ConvNet and Pseudo 3D ResNet models with a post-processing temperature scaling module. We optimize $\tau$ using Gradient Descent with a learning rate of $0.01$ for $50$ epochs. Note, that as the networks are fully trained and their weights remain fixed while learning the scaling parameter $\tau$, transformation of the logits does not influence their order and therefore the \emph{model accuracy stays the same}. In other words, while temperature scaling gives us better uncertainty estimates, the predicted activity class does not change as all logits are divided by the same scalar. \subsection{Calibrated Action Recognition with Input Guidance} \label{sec:caring} \begin{figure}[!t] \centering \includegraphics[trim={0 5.8cm 6.5cm 0},clip,width=0.5\textwidth]{figures/model.pdf} \caption{Overview of the Calibrated Action Recognition under Instance Guidance Model (CARING). CARING is an additional neural network which learns to infer the scaling factor $\mathcal{T}$ depending on the instance representation. The logits of the original activity recognition network are then divided by $T$, giving better estimates of the model uncertainty. } \label{fig:caring-model} \vspace{-0.3cm} \end{figure} In this section, we introduce a new model for obtaining proper confidence estimates by learning how to scale the logits \emph{depending on the input}. While our evaluation described in the next section reveals, that previous method clearly improves model confidence calibration, it does not take into account representation of the current example, \ie, the logits are always divided by the \textit{same} global scalar $\tau$. We believe, that the input itself carries useful signal for inferring model confidence and build on the temperature scaling approach~\cite{guo2017calibration} with one crucial difference: the scaling factor is not global but different for varying input. Our main idea is therefore to learn acquiring the scaling parameter $\mathcal{T}(\vec{z})$ on-the-fly at test-time depending on the input representation $\vec{z}$, so that the scaled logits become $\vec{y}_{scaled} = \vec{y}/\mathcal{T}(\vec{z})$. To learn the input-dependent temperature value $\mathcal{T}(\vec{z})$, we introduce an additional \emph{calibration neural network}, which we refer to as the CARING model (\textbf{C}alibrated \textbf{A}ction \textbf{R}ecognition under \textbf{In}put \textbf{G}uidance), as it guides the scaling of the logits depending on the current instance. An overview of our model is provided in Figure \ref{fig:caring-model}. CARING network comprises two fully-connected layers, with the output of the second layer being a single neuron used to infer the input-dependent temperature scalar. Note, that we extend the last ReLU activation with an addition of $1$ to enforce $\mathcal{T}(\vec{z})\geq1$, required to soften the probability scores. Input-dependent temperature $\mathcal{T}(\vec{z})$ is therefore obtained as: \begin{equation} \quad \mathcal{T}(\vec{z}) = 1 +relu( W_2~relu( W_1 \vec{z}+\vec{b}_1) + \vec{b_2}), \end{equation} where $W_1$,$W_2$, $b_1$ and $b_2$ are the network weight matrices and bias vectors and $\vec{z}$ is the input representation, for which we use the intermediate features of the original activity recognition network ($\vec{z}$ has a size of $1024$ for Infalted 3D ConvNet and $2048$ for Pseudo 3D ResNet). We then scale the logits by the inferred instance-dependent temperature $\mathcal{T}(\vec{z})$ and our prediction probability becomes: \begin{equation} conf(a_{pred}) = \max\limits_{a \in \mathcal{A}} \frac{exp(\frac{y_a}{\mathcal{T}(\vec{z})})}{\sum\limits_{\hat{a} \in \mathcal{A}} exp(\frac{y_{\hat{a}}}{\mathcal{T}(\vec{z})})}. \end{equation} We train the CARING model on a held-out validation set with Negative Log Likelihood loss for $300$ epochs (learning rate of $0.005$, weight decay of $1e^{-6}$). Although ${\mathcal{T}(\vec{z})}$ is not a constant and varies depending on the input, the order of the output neurons stays the same, since the CARING model infers one single value given an input $\vec{z}$, so that all logits are divided by the same value ${\mathcal{T}(\vec{z})}$. Similarly to the approach described in Section \ref{sec:caring}, CARING can be viewed as a post-processing step for obtaining better uncertainty confidence and \emph{does not affect the predicted activity class and model accuracy}. \begin{figure} \centering \begin{subfigure}{.25\textwidth} \centering \includegraphics[trim={0.4cm 0 0 0},clip,width=\linewidth]{figures/ece_training.pdf} \caption{Expected Calibration Error improvement during the training procedure for validation and test data.} \label{fig:ece_during_training} \end{subfigure}% \begin{subfigure}{.25\textwidth} \centering \includegraphics[trim={0.4cm 0 0 0},clip,width=\linewidth]{figures/temperature_training.pdf} \caption{Average temperature and its\\ \null \quad standard deviation estimated by \\ \null \quad our model during training.} \label{fig:avg_temperature_during_training} \end{subfigure} \caption{CARING model evolution during training for one Drive\&Act split. Both average value and standard deviation of the learned input-dependent scaling parameter $\mathcal{T}\vec(z)$ rise as the training proceeds (right figure). Jointly with the decrease of the calibration error (left figure), this indicates the usefulness of learning different scaling parameters for different inputs.} \label{fig:learning_procedure} \vspace{-0.3cm} \end{figure} We validate, that learning input-dependent temperature value is indeed better than using a single global scaling parameter by examining the evolution of different model metrics during training. Figure~\ref{fig:learning_procedure} illustrates changes of the expected calibration error (defined in Section \ref{sec:definition}) and the average and standard deviation of the inferred scaling parameter $\mathcal{T}\vec(z)$ measured over the validation data. Figure~\ref{fig:avg_temperature_during_training} reveals, that both, the mean and standard deviation of temperature rises during training, leading to a lower calibration error (Figure~\ref{fig:ece_during_training}). The observed increase in the standard deviation of the scaling parameter confirms that handling the logits differently dependent on the input is beneficial in our task. \section{Conclusion} Activity understanding opens doors for new ways of human-machine interaction but requires models that can identify uncertain situations. We go beyond the traditional goal of high top-1 accuracy and make the first step towards activity recognition models capable of \emph{identifying their misclassifications}. We measure the \emph{reliability of model confidence} and evaluate it for two prominent action recognition models, revealing, that the raw Softmax values of such networks do not reflect the probability of a correct prediction well. We further implement two strategies for learning to convert poorly calibrated confidence values into realistic uncertainty estimates. First, we combine the native action recognition models with the off-the-shelf temperature scaling~\cite{guo2017calibration} approach which divides the network logits by a single learned scalar. We then introduce a new approach which learns to produce individual input-guided temperature values dependent on the input representation through an additional calibration network. We show in a thorough evaluation, that our model consistently outperforms the temperature scaling method and native activity recognition networks in producing realistic confidence estimates. \section{Experiments} \subsection{Benchmark settings} \label{sec:benchmark-settings} Since there is no established evaluation procedure targeting the reliability of confidence values in context of activity recognition, we adapt existing evaluation protocols for two conventional action classification datasets, Drive\&Act~\cite{martin2019drive} and HMDB-51~\cite{kuehne2013hmdb51}, for our task. We choose the Drive\&Act~\cite{martin2019drive} testbed for driver activity recognition as our main benchmark, as it is application-driven and encompasses multiple challenges typical for real-life systems (\eg~fine-grained categories and unbalanced data distribution). Drive\&Act comprises $34$ fine-grained activity classes, which, however are highly unbalanced as the number of examples ranged from only $19$ examples of \emph{taking laptop from backpack} to $2797$ instances of \emph{sitting still}. As CNNs have a lower performance when learning from few examples, we sort the behaviors by their frequency in the dataset and divide them into \emph{common} (top half of the classes) and rare (the bottom half). We subsequently evaluate the models in three modes: considering \emph{all activities}, as it is usually done, using only the \emph{overrepresented-} or only the \emph{rare} classes. \looseness=-1 \input{tables/tbl_results_reliability_pakos_ids1_ids1_narrow.tex} We further validate the models on HMDB-51~\cite{kuehne2013hmdb51}, a more general activity recognition dataset comprising of YouTube videos. The benchmark covers $51$ activity classes, which are more discriminative in their nature (\eg~laughing and playing football) and are perfectly balanced (three splits with $70$ training and $30$ test examples for every category). Input to the P3D- and I3D models are snippets of $64$ consecutive frames. If the original video segment is longer, the snippet is chosen randomly during training and at the video center at test-time. If the video segment is shorter, we repeat the last frame until the $64$ frame snippet is filled. Following the problem definition of Section~\ref{sec:definition}, we extend the standard accuracy-driven evaluation protocols~\cite{martin2019drive,kuehne2013hmdb51} with the expected calibration error (ECE), depicting the deviation of model confidence score from the true misclassification probability. In addition, we report the Negative Log Likelihood (NLL), as high NLL values are linked to model miscalibration~\cite{guo2017calibration}. Since HMDB-51 does not contain a validation split, we randomly separate $10$\% of the training data for this purpose. As done in the original works~\cite{martin2019drive, kuehne2013hmdb51}, we report the average results over the three splits for both testbeds. \subsection{Confidence Estimates for Action Recognition} \label{sec:exp-closed-set} \input{tables/tbl_results_class_wise_ece.tex} In Table \ref{tbl:reliability_results} we compare CNN-based activity recognition approaches and their uncertainty-aware versions in terms of the expected calibration error and NLL for \textit{rare}, \textit{overrepresented} and \textit{all} Drive\&Act classes as well as in the HMDB-51 setup. First, we verify our suspicion that native activity recognition architectures provide unreliable confidence estimates: confidence scores produced by I3D score have a misalignment of $15.97\%$ for Drive\&Act and $20.11\%$ for HMDB-51. Similar issues are present in P3D: $21.2\%$ ECE on Drive\&Act, an error far too high for safety-critical applications. Model reliability is clearly improved by learning to obtain proper probability estimates, as all uncertainty-aware variants surpass the raw Softmax values. Interestingly, although I3D has better initial uncertainty estimates than P3D (ECE of $21.09$\% for P3D, $15.97$\% for I3D), P3D seems to have a stronger response to both, temperature scaling and CARING approaches then I3D (ECE of $5.26$\% for CARING-P3D, $6.02$\% for CARING-I3D). However, as this difference is very small ($<1\%$), we would rather recommend using I3D, as it mostly gives higher accuracy~\cite{martin2019drive,carreira2017quo,qiu2017learning}. While we consider the expected calibration error to be of vital importance for applications, we realize that this metric is complementary to model accuracy and encourage taking both measures into account when selecting the right model. We want to remind, that both temperature scaling and the CARING method \emph{do not influence the model accuracy} (see Sections \ref{sec:temperature} and \ref{sec:caring}). For Pseudo 3D ResNet we achieve an overall accuracy of $54.86\%$ (validation) and $46.62\%$ (test) on Drive\&Act, which does not change through our uncertainty-based modifications. Consistently with~\cite{martin2019drive} I3D achieves a higher accuracy of $68.71\%$ for validation and $63.09\%$ for test set \footnote{The slight deviation from the accuracy reported in the original work\cite{martin2019drive} (between $0.18\%$ and $1.3\%$) is due to random factors in the training process.}. As expected, the model confidence reliability correlates with the amount of training data (see distinguished areas for \textit{common}, \textit{rare} and \textit{all} classes of Drive\&Act in Table \ref{tbl:reliability_results}). For example, the \emph{common classes} setting encounters the lowest expected calibration error for both original and uncertainty-aware architectures ($13.38\%$ for I3D, $5.26\%$ for CARING-I3D). Leveraging intermediate input representation via our CARING calibration network leads to the best probability estimates on both datasets and in all evaluation settings. Thereby, the CARING strategy surpasses the raw neural network confidence by $9.95\%$ and the temperature scaling method by $2.53\%$ on Drive\&Act, highlighting the usefulness of learning to obtain probability scores \emph{depending on the input}. We further examine model performance for the individual classes, considering the five most frequent and the five most uncommon Drive\&Act activities separately in Table \ref{tbl:class-wise}. In addition to ECE, we report the accuracy for samples belonging to the individual class, the average confidence value they obtained with the corresponding model and the difference between them (denoted \emph{$\Delta$Acc}). While a such global confidence-accuracy disagreement is interesting to consider (and is $0$ for a perfectly calibrated model) it should be viewed with caution, as it might lead to an incorrect illusion of good confidence calibration, as \eg a lot of samples with too high and too low confidence values might cancel each other out through averaging. \looseness=-1 Reliability of the confidence scores is significantly improved through the CARING method and is connected to the amount of training data and the accuracy. Models have significant issues with learning from few examples (\eg~$76\%$ I3D and $59.80\%$ CARING-I3D ECE for \emph{putting laptop into backpack}). For both, over- and underrepresented classes, the ECE of easy-to-recognize activities (\ie the ones with high accuracy) is lower. Before calibration, the average confidence value is always higher than the accuracy (positive $\Delta Acc$) disclosing that the models are too optimistic in their predictions. Interestingly, after the CARING transformation is applied, the average model confidence is lower than the accuracy for some classes, such as \emph{eating}. CARING models therefore tend to be more conservative in their assessment of certainty. \subsection{Calibration Diagrams} \label{sec:calib_diag} \begin{figure*}[] \centering \begin{subfigure}{.16\textwidth} \centering \includegraphics[trim={0.1cm 0 1.4cm 0},clip,width=\linewidth]{figures/reliability_diag/I3D_logits_None_val_all.pdf} \caption{I3D (original), \\ \null \quad all action classes} \label{fig:i3d_all} \end{subfigure}% \begin{subfigure}{.16\textwidth} \centering \includegraphics[trim={0.1cm 0 1.4cm 0},clip,width=\linewidth]{figures/reliability_diag/I3D_temperature_normal_None_val_all.pdf} \caption{I3D + temp. scaling, all action classes} \label{fig:i3d_temp_all} \end{subfigure}% \begin{subfigure}{.16\textwidth} \centering \includegraphics[trim={0.1cm 0 1.4cm 0},clip,width=\linewidth]{figures/reliability_diag/I3D_temperature_input_dependent_None_val_all.pdf} \caption{CARING-I3D, \\ \null \quad all action classes} \label{fig:i3d_caring_all} \end{subfigure}% \begin{subfigure}{.16\textwidth} \centering \includegraphics[trim={0.1cm 0 1.4cm 0},clip,width=\linewidth]{figures/reliability_diag/P3D_logits_None_val_all.pdf} \caption{P3D (original), \\ \null \quad all action classes} \label{fig:p3d_all} \end{subfigure}% \begin{subfigure}{.16\textwidth} \centering \includegraphics[trim={0.1cm 0 1.4cm 0},clip,width=\linewidth]{figures/reliability_diag/P3D_temperature_normal_None_val_all.pdf} \caption{P3D + temp. scaling, all action classes} \label{fig:p3d_temp_all} \end{subfigure}% \begin{subfigure}{.16\textwidth} \centering \includegraphics[trim={0.1cm 0 1.4cm 0},clip,width=\linewidth]{figures/reliability_diag/P3D_temperature_input_dependent_None_val_all.pdf} \caption{CARING-P3D, \\ \null \quad all action classes} \label{fig:p3d_caring_all} \end{subfigure}% \begin{subfigure}{.16\textwidth} \centering \includegraphics[trim={0.1cm 0 1.4cm 0},clip,width=\linewidth]{figures/reliability_diag/I3D_logits_None_val_common.pdf} \caption{I3D (original), \\ \null \quad common classes} \label{fig:i3d_common} \end{subfigure}% \begin{subfigure}{.16\textwidth} \centering \includegraphics[trim={0.1cm 0 1.4cm 0},clip,width=\linewidth]{figures/reliability_diag/I3D_temperature_normal_None_val_common.pdf} \caption{I3D + temp. scaling, common classes} \label{fig:i3d_temp_common} \end{subfigure}% \begin{subfigure}{.16\textwidth} \centering \includegraphics[trim={0.1cm 0 1.4cm 0},clip,width=\linewidth]{figures/reliability_diag/I3D_temperature_input_dependent_None_val_common.pdf} \caption{CARING-I3D, \\ \null \quad common classes} \label{fig:i3d_caring_common} \end{subfigure}% \begin{subfigure}{.16\textwidth} \centering \includegraphics[trim={0.1cm 0 1.4cm 0},clip,width=\linewidth]{figures/reliability_diag/P3D_logits_None_val_common.pdf} \caption{P3D (original), \\ \null \quad common classes} \label{fig:p3d_common} \end{subfigure}% \begin{subfigure}{.16\textwidth} \centering \includegraphics[trim={0.1cm 0 1.4cm 0},clip,width=\linewidth]{figures/reliability_diag/P3D_temperature_normal_None_val_common.pdf} \caption{P3D + temp. scaling, common classes} \label{fig:p3d_temp_common} \end{subfigure}% \begin{subfigure}{.16\textwidth} \centering \includegraphics[trim={0.1cm 0 1.4cm 0},clip,width=\linewidth]{figures/reliability_diag/P3D_temperature_input_dependent_None_val_common.pdf} \caption{CARING-P3D, \\ \null \quad common classes} \label{fig:p3d_caring_common} \end{subfigure}% \begin{subfigure}{.16\textwidth} \centering \includegraphics[trim={0.1cm 0 1.4cm 0},clip,width=\linewidth]{figures/reliability_diag/I3D_logits_None_val_rare.pdf} \caption{I3D (original), \\ \null \quad rare classes} \label{fig:i3d_rare} \end{subfigure}% \begin{subfigure}{.16\textwidth} \centering \includegraphics[trim={0.1cm 0 1.4cm 0},clip,width=\linewidth]{figures/reliability_diag/I3D_temperature_normal_None_val_rare.pdf} \caption{I3D + temp. scaling, rare classes} \label{fig:i3d_temp_rare} \end{subfigure}% \begin{subfigure}{.16\textwidth} \centering \includegraphics[trim={0.1cm 0 1.4cm 0},clip,width=\linewidth]{figures/reliability_diag/I3D_temperature_input_dependent_None_val_rare.pdf} \caption{CARING-I3D, \\ \null \quad rare classes} \label{fig:i3d_caring_rare} \end{subfigure}% \begin{subfigure}{.16\textwidth} \centering \includegraphics[trim={0.1cm 0 1.4cm 0},clip,width=\linewidth]{figures/reliability_diag/P3D_logits_None_val_rare.pdf} \caption{P3D (original), \\ \null \quad rare classes} \label{fig:p3d_rare} \end{subfigure}% \begin{subfigure}{.16\textwidth} \centering \includegraphics[trim={0.1cm 0 1.4cm 0},clip,width=\linewidth]{figures/reliability_diag/P3D_temperature_normal_None_val_rare.pdf} \caption{P3D + temp. scaling, rare classes} \label{fig:p3d_temp_rare} \end{subfigure}% \begin{subfigure}{.16\textwidth} \centering \includegraphics[trim={0.1cm 0 1.4cm 0},clip,width=\linewidth]{figures/reliability_diag/P3D_temperature_input_dependent_None_val_rare.pdf} \caption{CARING-P3D, \\ \null \quad rare classes} \label{fig:p3d_caring_rare} \end{subfigure}% \caption{Reliability diagrams of different models reflect the agreement between the confidence values and the empirically measured probability of correct prediction (results of one Drive\&Act validation split). A model with \emph{perfectly calibrated uncertainty scores would match the diagonal} (a detailed explanation in Section \ref{sec:calib_diag} ). Note, that the ECE values deviate from Table \ref{tbl:reliability_results}, as they visualize a single split, while the final reported results are averaged over all splits. While the temperature scaling consistently improves the confidence estimates, our CARING model leads to the lowest calibration error in all settings. } \label{fig:reliability_diag} \vspace{-0.1cm} \end{figure*} In Figure \ref{fig:reliability_diag}, we visualize the agreement between the predicted model confidence and the empirically measured probability of the correct outcome via reliability diagrams (explained in Section \ref{sec:definition}) . In case of good estimates, the result will be close to the diagonal line. Values above the diagonal are linked to models being overly confident in their prediction, while values below indicate that the model doubts the outcome too much and the accurate prediction probability is higher than assumed. First, we discuss the reliability diagrams of the original action recognition networks. Both P3D and I3D confidence values deviate from the target, with a clear bias towards too optimistic scores (\ie values are oftentimes below the diagonal in Figures \ref{fig:i3d_all}, \ref{fig:p3d_all}, \ref{fig:i3d_common}, \ref{fig:p3d_common}, \ref{fig:i3d_rare}, \ref{fig:p3d_rare}). One exception is an above-diagonal peak in the low probability segment for \textit{all} and \textit{common} classes, meaning that in ``easier'' settings, low confidence examples often turn out to be correct (\ref{fig:i3d_all}, \ref{fig:p3d_all}, \ref{fig:i3d_common}, \ref{fig:p3d_common}). In the ``harder'' setting of \emph{rare} activities (Figure \ref{fig:i3d_rare}, \ref{fig:p3d_rare}), the bias towards too high probabilities is present for all values. We see a clear positive impact of temperature scaling (Figures \ref{fig:i3d_temp_all}, \ref{fig:p3d_temp_all}, \ref{fig:i3d_temp_common}, \ref{fig:p3d_temp_common}, \ref{fig:i3d_temp_rare}, \ref{fig:p3d_temp_rare}) and our CARING model (Figures \ref{fig:i3d_caring_all}, \ref{fig:p3d_caring_all}, \ref{fig:i3d_caring_common}, \ref{fig:p3d_caring_common}, \ref{fig:i3d_caring_rare}, \ref{fig:p3d_caring_rare}). CARING models outperform other approaches in all settings and lead to almost perfect reliability diagrams for \textit{all} and \textit{common} classes. Still, both temperature scaling and CARING methods have issues with rare classes, with model confidence still being too high, marking an important direction for future research. Note, that ECE might be in a slight disarray with the visual reliability diagram representation, as the metric weighs the misalignment in each bin by the amount of data-points in it, while the reliability diagrams do not reflect such frequency distribution. For example, while the CARING-I3D model in Figure~\ref{fig:i3d_caring_common} slightly exceeds the target diagonal, it has lower expected calibration error than CARING-P3D which seems to produce nearly perfect results in Figure~\ref{fig:p3d_caring_common}. As there are only very few examples in the low-confidence bin, they are overshadowed by smaller differences in the high-confidence bins, which contribute much more as they have more samples. \section{Introduction} Humans have a natural grasp of probabilities~\cite{fontanari2014probabilistic}: If we hear that a certain event is detected in a video by a neural network with $99$\% confidence, we automatically assume this to be the case. \begin{figure} \centering \includegraphics[width=\linewidth,trim={0 0 0.29cm 0.0cm},clip]{figures/density_plot_model_grey_v2.png} \vspace{0.1cm} \caption{Softmax confidence distribution of a popular video classification network (Pseudo 3D ResNet tested on a Drive\&Act validation split) before and after the improvement through our \textbf{C}alibrated\textbf{ A}ction\textbf{ R}ecognition with \textbf{In}put \textbf{G}uidance model. Native confidence values underestimate model uncertainty (the majority of samples was rated with $>90\%$ confidence, while the accuracy is significantly lower). We propose to incorporate the \emph{reliability} of model confidence in the evaluation of activity recognition models and develop algorithms for improving it. } \label{fig:intro} \vspace{-0.45cm} \end{figure} Such assumption however would be naive, as the inference merely gives us values of the last fully-connected layer which are usually optimized for a high top-1 accuracy on a fixed set of previously defined categories. As these values are usually normalized through the Softmax function to sum up to one, they \emph{appear} to be class probabilities but they do not depict the true confidence of the model~\cite{gal2016dropout}. Besides, when engineers apply such deep learning models in practice, they will quickly discover the phenomenon of \emph{model miscalibration}~\ie~the resulting Softmax scores tend to be biased towards very high values~\cite{guo2017calibration,gal2016dropout}. Unfortunately, such high confidence values are not only present in correct predictions but also in case of misclassifications. Despite impressive results in conventional classification, such overly self-confident models become a burden in applications, and might lead to tragic outcomes if assessing model uncertainty in its prediction plays an important role. Apart from the direct benefits of proper confidence values for decision-making systems, good assessment of uncertainty enhances model interpretability. For example, in the realistic scenario of open-world recognition, low-confidence input might be passed to human experts, which would provide the correct annotations (\ie active learning) and therefore improve the decision boundary. \looseness=-1 Uncertainty-aware models are vital for safety-critical applications of \emph{activity recognition} approaches, which range from robotics and manufacturing to autonomous driving and surveillance~\cite{roitberg2015multimodal,gebert2019end,Roitberg2020_InterpretableCNN}. While obtaining well-calibrated probability estimates is a growing area in general image recognition~\cite{guo2017calibration,hendrycks17baseline}, this performance aspect did not yet receive any attention in the field of video classification. The impressive progress reported on the conventional action recognition benchmarks linked to the rise of deep learning~\cite{carreira2017quo,qiu2017learning,hara2018can} may therefore draw a rather idealistic picture, as their validation is often limited to the top-1 accuracy on a static set of carefully designed actions~\cite{kuehne2013hmdb51,carreira2017quo,martin2019drive}. While such neural networks are notably bad at detecting data ambiguities, examining how well the confidence values of activity recognition models indeed reflect the probability of a correct prediction has been overlooked in the past and is the main motivation of our work. In this paper, we aim to elevate the role of uncertainty in the field of activity recognition and develop models, which do not only select the correct behavior class but are also able to \emph{identify misclassifications}. In other words, the resulting probability value should indeed reflect the likelihood of the prediction to be correct. To this intent, we propose to incorporate the \emph{reliability} of model confidence in the evaluation of activity recognition models and develop methods which transform oftentimes biased confidence outputs of the native action recognition models into reliable probability estimates. \mypar{Contributions and Summary} We argue, that for applications in industrial systems, activity recognition models must not only be accurate, but should also asses, how likely they are to be correct in their prediction through realistic confidence values. This paper makes the first step towards activity recognition models capable of \emph{identifying their misclassifications} and has thee major contributions. (1) We present the first study of how well the confidence of the modern activity recognition architectures indeed reflects the likelihood of a prediction being correct. To this intent, we incorporate the Expected Calibration Error metric in the evaluation procedure of two action recognition CNNs: Pseudo 3D ResNet (P3D)~\cite{qiu2017learning} and Inflated 3D ConvNet (I3D)~\cite{carreira2017quo}. Our experiments on two action recognition datasets confirm, that the out-of-the-box probability values of such models do not reflect model uncertainty well (\eg~over $20\%$ expected calibration error on HMDB-51~\cite{kuehne2013hmdb51}). (2) We further aim for a framework which learns to transform the poorly calibrated confidence values of the native action recognition models into more realistic probability estimates. We enhance these architecture with the temperature scaling method~\cite{guo2017calibration}, a prominent approach for model calibration in image recognition, which learns a single temperature parameter $T$ used to scale the network logits. This method, however, learns \emph{one global temperature value} for scaling,~\ie~after calibration, the logit values are always divided by the same scalar. (3) We believe, that input representation gives us significant cues for quantifying network uncertainty, and present a new method for \textbf{C}alibrated \textbf{A}ction \textbf{R}ecognition with \emph{\textbf{In}put \textbf{G}uidance} (CARING). In contrast to~\cite{guo2017calibration}, CARING entails an additional calibration network, which takes as input intermediate representations of the observed activity and learns to produce \emph{temperature values specific to this input}. While temperature scaling alone drastically improves the confidence values (\eg~the expected calibration error for the I3D model drops from $15.97\%$ to $8.55\%$), our CARING method consistently leads to the best uncertainty estimates in all benchmarks, further reducing the error by $2.53\%$ on Drive\&Act. \section{Related Work} \subsection{Activity Recognition} Activity recognition research is strongly influenced by progress in image recognition methods, where the core classification is applied on video frames and extended to deal with the video dimension on top of it. Similar to other computer vision fields, the methods have shifted from manually designed feature descriptors, such as Improved Dense Trajectories (IDT)~\cite{wang2013action} to Convolutional Neural Networks (CNNs) which learn intermediate representations end-to-end~\cite{wang2013action}. The first deep learning architecture to outperform IDTs was the two-stream network~\cite{simonyan2014two, wang2016temporal}, which comprises 2D CNNs operating on individual frames of color- and optical flow videos. The frame output is joined via late fusion~\cite{simonyan2014two, wang2016temporal} or an additional recurrent neural network~\cite{donahue2015long,ng2015beyond}. The field further progressed through emergence of 3D CNNs, which leverage spatiotemporal kernels to deal with the time dimension~\cite{ji20133d,carreira2017quo,hara2018can}. This type of networks still holds state-of-the-art results in the field of action recognition, with Inflated 3D Network~\cite{carreira2017quo}, 3D Residual Network~\cite{hara2018can} and Pseudo 3D ResNet~\cite{qiu2017learning} being the most prominent backbone architectures. The above works develop algorithms with the incentive to improve the top-1 recognition accuracy on standard activity classification benchmarks \emph{without taking the faithfulness of their confidence values into account} (as demonstrated in Figure~\ref{fig:intro} with an example of Pseudo3D ResNet). Our work focuses on \emph{uncertainty-aware action recognition} and aims for models which confidence values indeed reflect the likelihood of a correct prediction. Note, that the developed methods drastically improve the ability of an action recognition network to assign proper confidence values, they do not affect the accuracy, as they are based on learned scaling of the logits without changing their order. \subsection{Identifying Model Misclassifications} While multiple authors expressed the need for better uncertainty estimates in order to safely integrate deep CNNs in real-life systems~\cite{sunderhauf2018limits,hendrycks17baseline,nguyen2015deep}, the feasibility of predicted confidence scores has been missed out in the field of activity recognition. However, this problem has been addressed before in image classification~\cite{guo2017calibration,gal2016dropout}, person identification~\cite{bansal2014towards} and classical machine learning~\cite{niculescu2005predicting,degroot1983comparison,platt1999probabilistic}. Some of the uncertainty estimation methods are handled from the Bayesian point of view, leveraging Monte Carlo Dropout sampling~\cite{gal2016dropout} or ensemble-based methods~\cite{lakshminarayanan2017simple}. In such methods, the uncertainty is represented as a Gaussian distribution with output being the predictive mean and variance. In contrast, calibration-based approaches~\cite{platt1999probabilistic, zadrozny2001obtaining,zadrozny2002transforming,guo2017calibration,ott2018analyzing,naeini2015obtaining} have lower computational cost as they do not preform sampling and return a single confidence value. While these works approach the problem in a different way, they are all trained to obtain a proper confidence value on a held-out validation set following the initial training of the model and, thus, might be viewed as postprocessing methods. Recently, multiple calibration-based algorithms, such as isotonic regression, histogram binning, and Bayesian quantile binning regression and were brought in the context of CNN-based image classification by Guo~\etal~\cite{guo2017calibration}. The authors introduced temperature scaling, a simple variant of Platt Scaling~\cite{platt1999probabilistic}, where a single parameter is learned on a validation set and to rescale the neural network logits. Despite its simplicity, the temperature scaling method has outperformed other approaches in the study by Guo~\etal~\cite{guo2017calibration} and has since then been successfully applied in natural language processing~\cite{ott2018analyzing} and medical applications~\cite{huang2020tutorial}. Several works have studied uncertainty estimation in the context of novelty detection~\cite{roitbergBMVC2018novelty,hendrycks17baseline,liang2017enhancing, roitberg2020open}. A Bayesian approach has been used in a framework for recognizing activity classes which were not present during training~\cite{roitbergBMVC2018novelty}. Hendrycks and Gimpel have introduced a baseline for out-of-distribution detection using raw Softmax values~\cite{hendrycks17baseline}, which was further improved by Liang~\etal\cite{liang2017enhancing} through input corruptions and temperature scaling~\cite{guo2017calibration}. Our work, however, aims to study the confidence activity recognition models to \emph{identify, whether the prediction is correct, or not} and is therefore more comparable to the model calibration benchmarks of~\cite{guo2017calibration,niculescu2005predicting}. Our model builds on the approach of Guo~\etal~\cite{guo2017calibration}, extending it with \emph{input-guided} scaling. In contrast to~\cite{guo2017calibration}, which uses a static temperature parameter for all data points, we introduce an additional \emph{calibration network} to estimate a proper scaling parameter depending on the input. A similar input-dependent strategy has been recently introduced in the area of pedestrian detection for autonomous driving~\cite{neumann2018relaxed}, but there are architecture-related differences to our work, \eg~, there is no additional calibration network (the scaling factor is obtained through the initial CNN) and the logits are multiplied instead of being divided by the inferred value. Furthermore, our benchmark examines the reliability of model confidence values in context of action recognition for the first time.
{'timestamp': '2021-01-05T02:18:05', 'yymm': '2101', 'arxiv_id': '2101.00468', 'language': 'en', 'url': 'https://arxiv.org/abs/2101.00468'}
arxiv
\section{Introduction} With the rapid development of modern production techniques, the textile industry has undergone rapid changes. Intelligent weave machines have been introduced to make textiles convenient to produce and diversified in style and pattern. In addition, we have a clear need for personalized customization and on the whole, are not satisfied with traditional, uniform styles. Many of the ancient textiles exist as real objects only, and the patterns are still valuable and not outdated. If we want to reproduce such ancient fabrics, we need to analyze the patterns. Technicians can analyze the pattern by observing the fabric using a microscope and recording the crossing state of each yarn by disassembling them, but this is time consuming and tedious. At the same time, the original textile will be destroyed. Therefore, it is not a good way to solve this problem and we need to find a novel technique for automatically extracting the pattern. This would be useful for both reproduction and generating new patterns. In this work, we focused on Jacquard fabric in which the crossing of warp and weft was specified by a binary matrix pattern. \id{(\#5, \#35)}\add{ In contrast to ordinary looms, which only weave repetitive patterns, Jacquard looms can weave free patterns without repetition restrictions. With Jacquard fabric, the warp and weft can be defined for each crossing point; the resulting fabric is not composed of uniform pattern regions. If the fabric is made with small repetitive patterns, the analysis can be done manually without much effort, but for Jacquard fabrics, the analysis of large patterns that make up the entire fabric is required, and manual analysis requires much effort. The segmentation based on pattern uniformity does not work for analyzing Jacquard textile patterns. } \add{Jacquard textiles are often used in valuable fabrics such as traditional costumes and neckties, and there is high industrial value for the encoding and decoding of the patterns. Therefore, in this work, we focused on Jacquard fabric, in which the crossing of the warp and weft was specified by a binary matrix pattern.} The warp and weft yarns were dyed different colors and the pattern defined how the yarns crossed. The binary matrix pattern was defined as a binary image. For example, when the black yarn was above the white yarn, the crossing point was displayed in either black or white. We input the binary pattern into the weaving machine to produce the fabric. The Jacquard loom was able to accept the over-under relationship for the individual crossing points. \id{(\#39)}\add{Modern Jacquard looms can weave a coded pattern by loading a file of the pattern \cite{JacquardLoom}.} \id{(\#33, \#44, \#70)}\add{The appearances of images are different from each other, even at the same crossing point where a weft overlaps a warp. Fig. \ref{fig:appearance} shows zoomed-in images of the crossing point area in an observational image. Conventional template matching was not able to estimate the exact positions of the crossing points.} \begin{figure}[ht] \centering \includegraphics[width=0.4\textwidth]{appearance.eps} \caption{\id{(\#33, \#44, \#70)}\add{The variety of crossing points makes the problem difficult. Conventional template matching cannot deal with the crossing points.}} \label{fig:appearance} \end{figure} Where there are many pairs of fabric images and their corresponding binary patterns, deep neural networks (DNNs) can {\it decode} unknown binary patterns from a corresponding fabric image. However, DNNs cannot directly output a binary pattern with thousands of crossing points from a fabric image with millions of pixels. To solve the problem, we introduced an {\it intermediate representation} that bridged the pair and enabled us to output the intermediate representational patterns by a DNN. In addition, to convert a fabric image into the intermediate representation, and the intermediate representation into a binary pattern, we built a practical method for the conversion. \id{(\#45,\#79)}\add{We introduced intermediate representation images because we expected the images to directly represent the likelihoods which are the crossing points. In addition, due to insufficient sample size, complex networks that require a large amount of training data are not likely to be trained well. A more complex network, like an end-to-end network which directly answers the positions of crossing points, trained by numerous samples could provide accurate results.} \id{(\#12,\#21,\#30, \#76)}\add{We believe that the objective of this study, textile pattern decoding, has not been done to the best of the authors' knowledge in previous work. Therefore, we have not found any previous method that allows direct comparison of accuracy. Instead, by changing the parameters and kinds of filters in various ways, we confirmed the best possible settings for the current situation. } \begin{figure*}[ht] \centering \includegraphics[width=\textwidth]{overview.eps} \caption{The overview of our proposed method including the steps of (1) Pre-processing; (2) Manual labeling; (3) Integration; (4) Training; (5) Execution; and (6) Post-processing.} \label{fig:overview} \end{figure*} \id{(\#46)}The contributions of this paper are as follows: \begin{enumerate} \item Introduction of an intermediate representation for textile decoding tasks; \item \id{(\#11, \#41)}\add{Interface design for manual tagging of cross points on an observed textile image (Section 3.1.1);} \item Proposal of a pre-process for converting a fabric image to an intermediate representation (Section \add{3.1.3}\delete{III.A}); and \item Proposal of a post-process for converting an output intermediate representation pattern into a regular binary matrix pattern (Section \add{3.3}\delete{III.C}). \end{enumerate} Fig. \ref{fig:overview} shows the overview of our proposed method. Section \id{(\#61)}\add{2}\delete{II} introduces the background and related work, and Section \add{3}\delete{III} shows a method of converting a fabric image into an intermediate representation pattern as well as an intermediate representation pattern into a binary pattern. We also describe the details of DNN configurations. In Section \add{4}\delete{IV} we present experimental results and in Section \add{5}\delete{V}, a summary. \section{Related Work} \subsection{Pattern Creation by Computer Support} Depending on the local density of the crossing points as well as the colors of yarn appearing on the top, a textile pattern brings different levels of brightness. Inappropriate patterns result in misaligned grid points and partial fabric stiffness. Considering many conditions, and through trial and error, textile patterns have been manually created since ancient times. In recent years, systems for designing textile patterns with the support of computers have been proposed and it has become possible to create more complex patterns \cite{Igarashi17,Ng14,Zhang18}. Toyoura et al. \cite{Toyoura19} proposed a dithering method for reproducing smoothly changing tones and fine details of natural images on woven fabric, focusing on representing gray scale images by using two colors of warp and weft yarns. The weaving pattern is generated by binarizing the input image using dither masks. The step dithering method alternately places values of $0$ and $255$ at given intervals in each row of the dither mask such that there is at least one cross point of warp and weft yarns in the spacing in the resulting fabric. Within these intervals, the threshold increases from $0$ to $255$ or from $255$ to $0$. This forms a stepping structure up and down. The resulting binary image reproduces the brightness of the input image while limiting the number of crossing points in the weave pattern. By modeling and rendering 3D CG (computer graphics) from a textile pattern, the woven result can also be predicted. By adding a physical collision detection, it is possible to reproduce the appearance of fabrics by CG. Users will be able to modify the pattern without actually weaving it. There have been many studies on computer graphics to generate photo-realistic fabric images from defined patterns \cite{Dobashi19,Leaf14,Sadeghi13,Zhao16}. The images obtained by observing yarns, fabrics, and 3D yarn data obtained by CT are used to generate realistic images. 3D fabric models are constructed from the data. These are the opposite of directional studies, as our proposed method restores patterns from actual fabrics. \id{(\#24)}\delete{Realization of our proposed method means the actual fabric can be reproduced from 3D CG.}\add{In this work, we aimed to output a pattern of weaving, which would be a complementary work.} \subsection{Pattern Analysis for Fabric Images} \idr{(\#2)}Due to industrial demand, \id{(\#3, \#68)}\add{the pattern analysis by DNNs has been introduced for content-based image retrieval \cite{Hamreras20}, } \addr{noisy image recognition \cite{Koziarski17}, } \add{3D medical image super-resolution \cite{Hemsi20}, } \addr{video surveillance \cite{Benito20}, foreground detection \cite{Garcia20}, multi-object tracking \cite{Yang19}, } \add{explosive device detection \cite{Donnelly20}, } \addr{pupil detection \cite{Vera19}, online data streaming \cite{Lara20}, airport baggage handling \cite{Sorensen20}, } \add{and many other objectives. } \addr{Computational photography \cite{Wu19} and purpose-specific machine learning \cite{Rostami17} have been also employed to solve industrial problems. } Many studies have been conducted to detect defects from fabric images. Huangpeng et al. \cite{Huangpeng18} constructed a weighted, low-rank, representational model of textures and detected defects. Ren et al. \cite{Ren17} realized the detection from a small sample set using pre-trained \delete{deep neural networks} \add{DNNs}, and Wei et al. \cite{Wei19} also employed DNN for \add{the} classification of fabric \delete{defect} \add{defects} \delete{only from the} \add{using a} small \delete{size} \add{number} of samples. \add{Jeyaraj et al. \cite{Jeyaraj19} improved the accuracy of defect detection by introducing the characteristic of texture in the training of DNN. Jing et al. \cite{Jing19} analyzed the detailed parameter settings of pre-trained networks, image patch sizes, the number of layers, and so on for detecting defects in repetitive patterns. } Li et al. \cite{Li16} proposed a method for detecting defects by Fisher criterion-based stacked denoising autoencoders. Liu et al. focused on information entropy and frequency domain saliency \cite{Liu20}. \add{The ability to detect defects is valuable for the industry} \addr{\cite{AItexWeb,Tirronen08,Kwak01}} \add{and patents for defect detection have been published \cite{Patent01}. On the other hand, } defect detection is a task of anomaly detection or classification; however the pattern analysis of interest in this work is the binarization of the regularly aligned crossing points of warp and weft yarns. In order to measure the density of the weft for the woven fabric, Schneider et al. detected the intensity minima of brightness and estimated the positions for each \cite{Schneider14}. Compared with the simple Fourier transform, the change in the density of the weft can be obtained more accurately. Luo and Li \cite{Luo20} employed image processing techniques for quantifying fiber distribution uniformity in blended yarns based on cell counting and dilation area estimation. Meng et al. \cite{Meng19} realized their goal of estimating the yarn density of multi-color woven fabrics by deep learning. In this method, assuming that the whole fabric is woven in \id{(\#25)}\add{a periodical}\delete{the same} pattern, the intersection of the warp and the weft arranged on a regular grid is detected. \id{(\#73)}\add{Near-infrared spectroscopy revealed the material of yarns \cite{Sun15}. Machine learning also contributed to estimate the kinematic behavior of yarns \cite{Ribeiro20}.} In this paper, we aimed to analyze different patterns in a fabric. The grid formed by the warp and the weft may be greatly collapsed. Zheng et al. \cite{Zheng19} proposed a method for recognizing how predefined patterns are arranged on a piece of fabric. \id{(\#23)}\add{Loke and Cheong used co-occurrence matrices for the recognition \cite{Loke09}. These methods} \delete{This method} can be applied when the fabric is composed of a small number of known patterns, but this cannot be assumed for woven fabrics in which the pattern is created manually. Therefore, we aimed to determine the intersection of each point on the grid. \vspace{0.5cm} \noindent \id{(\#9)}\add{3. Textile Pattern Decoding from Observed Image} \\ \delete{3. Method} \setcounter{section}{3} \setcounter{subsection}{0} \id{(\#10, \#62)}\add{Here, we describe a method for decoding binary textile patterns from observed images. The method consists of three parts; pre-processing for converting a fabric image to an intermediate representation (Section 3.1); using a DNN for generating a label image (Section 3.2); and post-processing for converting the intermediate representation into a binary matrix textile pattern (Section 3.3). The training data is a set of observed images and a corresponding set of intermediate representations of these images with manually labeled cross point positions. At runtime, the final binary pattern is output from an observed image only. Fig. \ref{fig:overview} shows an overview of the process.} \delete{We employed deep learning and image processing techniques. As shown in the overview in Fig. \ref{fig:overview}, a deep neural network outputs an intermediate representation image from an input image and post-processes the image to obtain the final binary pattern. We manually created intermediate representation images for training the deep neural network. } \subsection{Pre-process for converting a fabric image to an intermediate representation} \add{\subsubsection{Manual tagging of crossing points}} \begin{figure*}[ht] \centering \begin{tabular}{c c c} \includegraphics[width=0.225\textwidth]{LOG/eye.eps} & \includegraphics[width=0.25\textwidth]{LOG/edge.eps} & \includegraphics[width=0.20\textwidth]{LOG/minima.eps} \\ \add{\small (a) Observed image} & \add{\small (b) LOG filtered image} & \add{\small (c) Yarn position estimation} \end{tabular} \caption{Estimation of warp and weft positions. \id{(\#15, \#56, \#63)}\add{For the input image shown in (a), the LOG filter image shown in (b) is calculated ($\sigma$=11 for Gaussian filter). In order to find the position of wefts, the sum of the pixel values in the LOG image is calculated row by row. (c) For a 1D sequence of sums, we smooth the values by finding the average of a certain value and the five neighboring values before and after the value. The local minima of the sequence indicate the positions where the power of edges is low, so they are output as the center positions of wefts. To estimate the positions of warps, the local minima of the sequence of vertical sums.} \delete{The obtained image is filtered by a LOG filter. The row or column whose integral of edge intensity reaches a local minimum is likely to correspond to the center positions.}} \label{fig:LOG} \end{figure*} Analysis of the weaving pattern can be done manually by observing the fabric using a microscope and recording the cross state of each yarn by disassembling it. This method is very time consuming, laborious, inefficient, and costly. In addition, it is also undesirable to perform such destructive inspections on textiles of high historical value. As is shown in Fig. \ref{fig:LOG}, we estimated fabric patterns from captured images and interactively modified fabric patterns to analyze weaving patterns. Initial estimation results of the crossing point positions of warp and weft yarns were given by image analysis. The positions were interactively modified with a GUI so that the pattern could be obtained in a short time without destroying the actual fabric. Fig. \ref{fig:LOG} outlines the detection of the positions of weft yarns by filtering the image with a Laplacian of Gaussian (LOG) filter. \id{(\#14,\#27)}\add{A LOG filter is used to extract edges, such as regional boundaries, while removing small noise. We expected to ignore the fine threads and to output the boundaries between warp and weft yarns. Where the boundary pixels are few, it can be assumed that it is the center of the crossing point of warp and weft yarns.} Since \add{the} edge pixels could be observed at the edge of the yarn, the center of the yarn was found by picking up the local minima with fewer edge pixels \cite{Zheng19}. \begin{figure*}[ht] \centering \begin{tabular}{c c c c} \includegraphics[width=0.20\textwidth]{three/creation/observedimage.eps} & \includegraphics[width=0.20\textwidth]{three/creation/preprocessedimage.eps} & \includegraphics[width=0.20\textwidth]{three/creation/manuallytaggedcrossingpoints.eps} & \includegraphics[width=0.20\textwidth]{three/creation/filteredlabeledimage.eps} \\ {\small (a) Observed image.} & {\small (b) Pre-processed image.} & {\small (c) Manually tagged crossing } & {\small (d) Filtered labeled image.} \\ & & \multicolumn{1}{l}{{\small \ \ \ points.}} & \end{tabular} \caption{Converting processes of input image into labeled image. The observed image was captured with a camera with a macro lens. The image was smoothed in the pre-process and the positions of the crossing points were manually tagged. By filtering the crossing points, we obtained the final, labeled image.} \label{fig:creation} \end{figure*} When the pixel values were integrated in the horizontal direction (X direction), the intensity of the edge component in each row was obtained. The position where the edge intensity reached the maximum was the end of the row with many edge elements, and the row whose edge intensity reached the local minimum was the center of the yarn with relatively few edges. Applying the same process to the warp yarns, the crossing points of the warp and weft yarns could be obtained as the initial positions of crossing points. Although this method can analyze patterns quickly, it is not automated enough to perform large-scale analysis. Therefore, we used this method only to prepare training data. \id{(\#11, \#62)}\add{Once the initial positions of the warps and wefts were determined from the input image, we computed which of the warps or wefts was higher for each of the grid points. By giving two representative colors of warp and weft, we could see which color was closer at a grid point, and then give the state of the grid at that point as 0 or 1.} \add{In the developed GUI, a user can add, remove, and move yarns by clicking and dragging on the screen. The operational mode was defined as move, add, or delete by key presses: The operation with the shift key pressed was for the warp; the operation with the ctrl key pressed was for the weft, and the operation without pressing any key was for the crossing point. When the weft and warp positions were updated, the initial intersection (based on the new warp and weft positions) could be obtained by pressing the C key. When the F key was pressed, the vertical direction of the weft and warp at the crossing point closest to the clicked mouse position was reversed.} \add{\subsubsection{Noise removal of fine fibers}} In the observed image, even fine fibers are observed, as shown in Fig. \ref{fig:creation}(a). The fine fibers produce intensity edges which result in high values in the LOG-filtered image. This problem can be easily solved by the image processing of erosion and \id{(\#28)}\add{dilation}\delete{expansion}, resulting in the image shown in Fig. \ref{fig:creation}(b). \id{(\#16)}\add{Erosion and dilation are used to remove the regions with little area. In our experiments, we used three functions in MATLAB; strel, imerode, and imdilate. To obtain the results, the image was eroded with a $5.5$ pixel radius setting and then expanded with the same setting. The radius setting was determined by checking to see if the thin fibers disappeared in the sample image.} Fig. \ref{fig:creation}(c) shows the image with the manually labeled crossing points. The red and blue points are central with the red point indicating that the warp is on top at the point. The blue point indicates that the weft is on top at the point. Fig. \ref{fig:creation}(d) shows the image with white pixels for the point of the warp on the weft; black pixels for the point of weft on the warp; and gray pixels for other than the crossing points in the image. For machine learning, the pre-processed image in Fig. \ref{fig:creation}(b) and the intermediate representation image in Fig. \ref{fig:creation}(d) are provided as a pair; \id{(\#28)}\add{the} DNN receives the pre-processed image and outputs an intermediate representational image. \begin{figure*}[ht] \centering \begin{tabular}{l l l l} \includegraphics[width=0.20\textwidth]{three/impulsepeak.eps} & \includegraphics[width=0.20\textwidth]{three/gausspeak.eps} & \includegraphics[width=0.20\textwidth]{three/boxpeak.eps} & \includegraphics[width=0.20\textwidth]{three/binarypeak.eps} \\ \multicolumn{1}{l}{\footnotesize (a) Impulse peak pattern.} & \multicolumn{1}{l}{\footnotesize (b) Gaussian-filtered peak } & \multicolumn{1}{l}{\footnotesize (c) Box-filtered peak pattern.} & \multicolumn{1}{l}{\footnotesize (d) Binary pattern.} \\ \multicolumn{1}{l}{\footnotesize \add{$I_0$, defined by Eq. (1). }} & \multicolumn{1}{l}{\footnotesize \add{pattern. $I_G$, defined by}} & \multicolumn{1}{l}{\footnotesize \add{$I_B$, defined by Eq. (3). }} & \\ & \multicolumn{1}{l}{\footnotesize \add{Eq. (2). }} & & \end{tabular} \caption{\id{(\#17)}\add{Impulse peak pattern and three}\delete{Three} kinds of labeled images.} \label{fig:three} \end{figure*} \add{\subsubsection{Converting intermediate representation images}} Here, we considered how to make an intermediate representational image. If we were to use the result of manual labeling in its present form, we would get an image $I_0$ with impulses at the crossing points, as shown in Fig. \ref{fig:three}(a) \id{(\#17)}\add{and Eq. (1)}. At a crossing point, it would take a value of 0 or 1 and at the very next pixel, it would take a gray value of 0.5. \begin{eqnarray} I_0(x,y) = \left\{ \begin{array}{l l} 1 & if \ weft \ on \ warp \ at \ (x,y), \\ 0 & if \ warp \ on \ weft \ at \ (x,y), \\ 0.5 & otherwise. \end{array} \right. \label{eqnarray:1} \end{eqnarray} In the input image, there is no significant change in the immediate vicinity of the crossing position, so it is expected that DNN would have difficulty producing such an image. The image $I_G$ with the Gaussian blur shown in Fig. \ref{fig:three}(b) can represent the situation in which the likelihood peaks at the crossing point and the likelihood gradually decrease. It is expected to be easier to handle with DNN than the impulses. $I_0$ can be reproduced by finding the minimum and maximum points of each peak. Furthermore, by trial and error, we found that the image with the box filter as shown in Fig. \ref{fig:three}(c) has better accuracy \id{(\#29)}\add{for} \delete{in} the resulting images. The results of using $I_0, I_G$ \id{(\#17)}\add{defined by Eq. (2)}, and $I_B$ \add{defined by Eq. (3)} for the training data, respectively, are presented in the Experiment section. \begin{eqnarray} I_G &=& LOG(I_0), \\ I_B(x,y) &=& \left\{ \begin{array}{l l} 1 & \max_{(s,t) \in N(x,y)} I_0(s,t)=1, \\ 0 & \max_{(s,t) \in N(x,y)} I_0(s,t)=0, \\ 0.5 & otherwise. \end{array} \right. \end{eqnarray} \noindent Note that $N(x,y)$ represents the set of neighborhood pixels of $(x,y)$. \id{(\#64)}\add{In Fig. \ref{fig:overview} and Fig. \ref{fig:creation}(b), we used a window of $9 \times 9$ pixels as $N(x,y)$. Different sizes of windows were also tried and examined in the experiment.} In Fig. \ref{fig:three}(d), the final binary pattern is transformed into an image, but the size of the image is much smaller than the input image. Additionally, the positions of the crossing points are different from those of the input image. To obtain such an image by DNN is difficult because DNN tries to determine whether a point is a crossing point based on the information of a pixel and its neighbors. In that situation, DNN cannot produce an image like Fig. \ref{fig:three}(d) in which the position is completely misaligned. \subsection{DNN model for generating label image} We used a DNN to output a label image from the input image. It was necessary to determine whether a pixel corresponded to a crossing point by looking at the surroundings of the pixel without losing the accuracy of the position. We employed a DNN with a U-net structure \cite{Ronneberger15} to solve this task in which a network with this structure can take into account the surroundings by a network of autoencoders and maintain the resolution by jumping paths. The model structure is shown in Fig. \ref{fig:network}. \add{\id{(\#49, \#53, \#54)} The input to the DNN is a pre-processed image, which is an image with fine noise removed, and the output from the DNN is an intermediate representation of the image, which shows the likelihood of the existence of the crossing points on the image.} The model has a total of six down-roll multi-layer and six upper convolution layers; the final output size is the same as the input size. When the pre-processed observation images were input, the network was trained so that the label images were output. \id{(\#55)}\add{The input image size of $320 \times 512$ was chosen because it is difficult to train a network with too many neurons due to the limited number of samples, and because it is easy to work with when tagging manually. It does not necessarily have to be this size; other sizes may be used with confidence.} In the learning phase, we gave a pair of observed images and a label image that were manually generated. For the loss function, the L1 norm of pixel values was employed. \id{(\#51)}\add{The number of neurons in each layer is also shown in the figure. PyTorch was used for implementation. A more detailed implementation environment is described at the beginning of the experimental section.} \begin{figure}[ht] \centering \includegraphics[width=0.47\textwidth]{Unet.eps} \caption{Neural network model structure for converting labeled intermediate representation image.} \label{fig:network} \end{figure} \begin{figure}[ht] \centering \includegraphics[width=0.35\textwidth]{post-processingv2.eps} \caption{Post processing for the conversion of output image from a deep neural network.} \label{fig:transition} \end{figure} \subsection{Post-process for converting intermediate representation into binary matrix textile pattern} DNN outputs an intermediate representation image; however, a non-trivial post-processing is required to obtain the final binary pattern. This occurs in several steps: 1) the intermediate representation image is converted into a tri-valued image of $0$, $0.5$, and $1$; 2) each peak region is merged into one; 3) the approximate horizontal and vertical positions of the warp and weft yarns are found; and 4) a determination is made as to which of warp and weft are over at each grid point. Finally, we get a binary pattern with 0s and 1s on the grid points, as shown in Fig. \ref{fig:transition}. \vspace{0.2cm} \subsubsection{Converting the intermediate representation image into a tri-valued image} The intermediate representation image \id{(\#66)}\add{output} \delete{outputted} from the DNN had continuous values in the range of $(0,1)$. In order to find the crossing points by segmenting the image, each pixel must have a discrete value. We replaced the value of each pixel with the closest of the three values, in which the crossing point of the warp was 0, the crossing point of the weft was 1, and 0.5 otherwise. This process is equivalent to thresholding by two values of 0.25 and 0.75. \id{(\#31)}\add{An image is converted into a tri-valued image only with white, black, and gray pixels.} \vspace{0.2cm} \subsubsection{Integrating regions of multiple values} In the image obtained by \id{(\#31, \#52)}\add{the process described in 3.3.1}\delete{(1)}, based on the gray background, a region consisting of white pixels only, a region consisting of black pixels only, and a region containing both white and black pixels appeared. Since the crossing points were never adjacent to each other in real fabrics, no region ever contained both white and black pixels. \id{(\#52)}\delete{Therefore,}\add{We aim to avoid the coexistence of white and black pixels in each region that represents a crossing point.} \delete{the}\add{The} region containing both white and black pixels was merged into the region with the larger number of white or black pixels. \id{(\#31,\#38,\#52)}\add{The pseudo code for the process is described in Algorithm \ref{Algorithm:CCL}.} {\small \begin{figure}[ht] \begin{algorithm}[H] \caption{\id{(\#31,\#38,\#52)}\add{Integrating regions with multiple values with connected component labeling (CCL)}}\label{CCL} \label{Algorithm:CCL} \begin{algorithmic}[1] \renewcommand{\algorithmicrequire}{\textbf{Input:}} \renewcommand{\algorithmicensure}{\textbf{Output:}} \algblockdefx[Foreach]{Foreach}{EndForeach}[1]{\textbf{foreach} #1 \textbf{do}}{\textbf{end foreach}} \Require Tri-valued image \State Pixel value $v(p) \in \{0, 0.5, 1\}$ in tri-valued image \State 4-neighboring pixel of $p$ is $N(p)$ \State Function $BW(p,q)$ = True only when ($v(p)=0 \wedge v(q)=1$) $\vee$ ($v(p)=1 \wedge v(q)=0$) \Ensure Tri-values image without 0-1 mixed regions \State \Comment{CCL segmentation} \State CCL segments regions with unique values \State Identify regions $\{r\}$ by IDs $\{i\}$ \State \Comment{Merge region IDs} \State flag $\leftarrow$ True \While {flag = True} \State flag $\leftarrow$ False \Foreach {Region $r_i$} \Foreach {Pixel $p \in r_i$} \If {$\exists q \in N(p), BW(p,q) = True$} \If {$p \in r_i$ and $q \in r_j$ \ and \ $i<j$} \State $j \leftarrow i$ \State flag $\leftarrow$ True \EndIf \EndIf \EndForeach \EndForeach \EndWhile \State \Comment{Unify pixel values in individual regions} \Foreach {Region $r_i$} \If {0-valued pixels are more than 1-valued pixels in $r_i$} \State All pixels in $r_i$ $\leftarrow$ 0 \Else \State All pixels in $r_i$ $\leftarrow$ 1 \EndIf \EndForeach \end{algorithmic} \end{algorithm} \end{figure} } The regions were labeled by segmentation and the adjacent regions for each region were searched. The connected components labeling (CCL) gave the individual, connected regions of a binary image drawn by identical numbers. A region containing both white and black pixels could be detected from the adjacency matrix. Ignoring the background gray region, we first flagged the adjacent regions. We then flagged the adjacent regions of the first set of adjacent regions and repeated the process until no more flags appeared. Finally, the black and white regions included in each independent region were recognized. The number of white and black pixels belonging to each region were counted and the region was merged by the higher color. After we merged the regions with only white pixels and black pixels, we next found the representative points of each region. Since the representative point should be located in the center of the crossing point region, the pixel at the gravity point of each segmented region was to be the representative point of that region. \vspace{0.2cm} \subsubsection{Finding approximate horizontal and vertical positions} Regional representative points indicating crossing points included duplicated and missing points. The crossing points were constraints that existed in a grid along the yarns. The regional representative points satisfying this constraint were picked up and converted into binary matrix patterns. First, by detecting the positions of the warp and weft yarns, the approximate positions of the grid points were estimated. The distance transformation image for the obtained candidate crossing points were able to show the likelihood of a warp or weft passing through its position. The positions of warp and weft yarns were estimated in the same way as in the pre-processing, using the distance transformation image as the target. The crossing point pixels were replaced by $1$ as the object region and the other pixels were replaced by $0$ as the background region. The value of each pixel in the distance transformation image indicated the distance from that pixel to the nearest pixel in the object region. The distance was $0$ for pixels in the object region; the further away the pixel was, the larger the value was. We integrated the distance transformation values of pixels in a column. Along a column, the more pixels that were in the object region or close to it, the smaller the integral became while the likelihood of being the center of the warp or weft yarn increased. As described in Section 3.A, the positions of warp and weft yarns were estimated by determining the likelihood according to the power of intensity edges. The integral was smoothed in the same way to reduce the effect of local noise. By way of this process, the positions of the warp and weft yarns were estimated. \vspace{0.2cm} \subsubsection{Determining value at each grid point} As the positions of the warp and weft yarns were estimated, the positions of the grid points were also estimated automatically. By assigning a value of $0$ or $1$ to each grid point, we were able to obtain the final binary pattern in a matrix form. In Fig. \ref{fig:transition}, the blue lines indicate the estimated location of the warps while the red lines indicate the estimated location of the wefts. The white and black points are representative points with the values of $1$ or $0$. For each grid point, we extracted the best candidate point within distance $s$ and let the value of $0$ or $1$ of the candidate points be the value of the grid points. If there was more than one candidate point, we adopted the closest one to the grid point; if there was no point, we adopted the closer color of which the warp or weft colors from the color of the grid point itself. $s$ allowed for being set arbitrarily; a smaller value meant that we adopted only candidates strictly close to the grid point. In the experiment, we confirmed the accuracy of pattern reproduction according to the variety of $s$. \section{Experiment} \begin{figure*}[ht] \centering \subfigure[Pre-processed input image.]{ \includegraphics[width=0.3\linewidth]{comparison/112_input.eps} \includegraphics[width=0.3\linewidth]{comparison/231_input.eps} \includegraphics[width=0.3\linewidth]{comparison/241_input.eps} } \quad \subfigure[Result image by impulse peak pattern training.]{ \includegraphics[width=0.3\linewidth]{comparison/112_binary.eps} \includegraphics[width=0.3\linewidth]{comparison/231_binary.eps} \includegraphics[width=0.3\linewidth]{comparison/241_binary.eps} } \quad \subfigure[Result image by Gaussian-filtered peak image training.]{ \includegraphics[width=0.3\linewidth]{comparison/112_gauss.eps} \includegraphics[width=0.3\linewidth]{comparison/231_gauss.eps} \includegraphics[width=0.3\linewidth]{comparison/241_gauss.eps} } \quad \subfigure[Result image by box-filtered peak image training.]{ \includegraphics[width=0.3\linewidth]{comparison/112_block.eps} \includegraphics[width=0.3\linewidth]{comparison/231_block.eps} \includegraphics[width=0.3\linewidth]{comparison/241_block.eps} } \quad \subfigure[\id{(\#75)}\add{ROC-like curve.}]{ \includegraphics[width=0.3\linewidth]{comparison/112_graph.eps} \includegraphics[width=0.3\linewidth]{comparison/231_graph.eps} \includegraphics[width=0.3\linewidth]{comparison/241_graph.eps} } \caption{Comparison of the different kinds of intermediate representations for DNN training. \id{\#64}\add{The results shown in (c) are given with $\sigma=5$ for Gaussian filter, and (d) are given with $N(x,y)$ as a window of $9 \times 9$ pixels. } } \label{fig:comparison} \end{figure*} Textile samples were observed with an SLR camera Canon EOS M for consumer use; we attached a fixed focus macro lens with LED illumination Canon EF-S 35mm f/2.8 Macro IS STM. High-resolution images were divided into small, partial images. \id{(\#32)}\add{The images were made by observing samples represented in reference \cite{Toyoura19}. The samples were woven with black and white yarns only, and the patterns were generated from natural images. } \id{(\#18, \#57, \#58, \#67, \#72)}\add{We obtained 176 images; each had a resolution of $512 \times 320$ pixels. We then manually tagged all the images.} \delete{We obtained $224$ images of $512 \times 320$ pixels using $176$ images for training and $48$ for validation.} \id{(\#54)}\add{The number of images is to be increased to get more accurate results, but it requires more effort. } The training images were augmented by flipping them vertically and horizontally and rotating them $180^{\circ}$; then, $704$ \id{(\#22, \#32, \#67)} \delete{augmented images were used}\add{examples were used for the training. With the horizontal mirror images, the vertical mirror images, the images flipped $180^{\circ}$, and the original images, there were a total of $176 \times 4 = 704$ images.} For each image, we performed the manual cross point extraction as described in Section 3.1. \id{(\#22)}\add{The observed images and manually added tags are shared at https://github.com/toyoura/TextileDecoding.} PyTorch was employed as a deep learning framework and GPU GeForce2080Ti 11GB was used for training and validation. It took about $2.4$ hours to train. The batch size was set to $4$ and the maximum epoch was set to $400$. To complete the process of one image at runtime it took about $1.21$ seconds, which included $0.24$ second for pre-processing, $0.08$ second for executing DNN, and $0.89$ second for post-processing. \subsection{Comparison of intermediate representations} DNNs were respectively trained by the three intermediate representational images described in Section 3.2. \id{(\#18, \#57, \#58, \#67, \#72)}\add{We performed an 11-fold cross-validation procedure to ensure the robustness of the method. The 176 images were divided into 11 groups of 16 images. After training the network with 160 images, we verified the accuracy of the remaining 16 images and repeated this process 11 times.} The output images obtained by each training are shown in Fig. \ref{fig:comparison}. For the results, no post-processing was done. First, we can see that impulse peak pattern training does not provide good results. Many regions of the white yarns were detected as crossing points, and candidate points also appeared at the edges formed by the yarn contours. When considering the segmentation of post-processing, the noisy clutters did not result in the correct detection of candidate points. Although much better results were provided than those by impulse peak pattern training, Gaussian-filtered peak pattern training generated blurry images. The post-processing of the segmentation was not successful because each of the regions became one continuous region of adjacent, segmented regions. This trend did not improve, even after changing the variance of the Gaussian peak. When the variance was set too small, the results were similar to those induced by the impulse peak pattern. Finally, the results trained by the box-filtered peak pattern were better than the two previous results. The region indicating each crossing point was less likely to be integrated with its adjacent regions. The extraction of the candidate representative points by post-processing also showed good results in appearance. \add{The correct rate for all groups was $83.25 \%$ on average, and the minimum was $74.13 \%$, the maximum was $99.17 \%$, and the standard deviation was $8.40 \%$. } \subsection{Performance of cross point detection} The resulting binary patterns obtained in the form of matrices could not be evaluated directly because the same number of crossing points in each row and column could not be aligned in the observed image. Therefore, the observed crossing points could not be represented in a matrix manner. Instead of the direct evaluation of the binary patterns, we verified whether the label images were correctly obtained. The correct label image could be given by manual labeling. The accuracy of the position of the crossing points could also be examined. Here, we evaluated the representative points of the crossing point regions obtained from the resulting label image. Many pixels took a value of $0.5$ and a few took $0$ or $1$ to indicate that the pixels were representative crossing points. Similarly, in the manually labeled images, a small number of crossing points were placed in a background of many pixels that took a value of $0.5$. In order to verify the match between them, we set a threshold $s$ for Euclidean distance. For a crossing point in the manually tagged image, if the extracted candidate crossing points were within the threshold distance, we considered the crossing point to be correctly detected; if there were multiple intersections within $s$, we considered the crossing point with the smallest distance to be the corresponding point as shown in Fig. \ref{fig:th_s}. \begin{figure}[ht] \centering \includegraphics[width=0.47\textwidth]{th_sv3.eps} \caption{Threshold $s$ for quantitative performance assessment.} \label{fig:th_s} \end{figure} \begin{figure*}[ht] \centering \subfigure[Number of layer.]{ \begin{minipage}[t]{0.18\linewidth} \centering \includegraphics[width=1in]{layer.eps} \end{minipage} } \subfigure[Box filter size.]{ \begin{minipage}[t]{0.18\linewidth} \centering \includegraphics[width=1in]{boxfilter.eps} \end{minipage} } \subfigure[Gaussian filter size.]{ \begin{minipage}[t]{0.18\linewidth} \centering \includegraphics[width=1in]{gaussfilter.eps} \end{minipage} } \subfigure[s in Box filter.]{ \begin{minipage}[t]{0.18\linewidth} \centering \includegraphics[width=1in]{boxs.eps} \end{minipage} } \subfigure[s in Gaussian filter.]{ \begin{minipage}[t]{0.18\linewidth} \centering \includegraphics[width=1in]{gausss.eps} \end{minipage} } \centering \caption{\add{ Comparison experiment for different number of layers, filters, and distance threshold s.}} \label{fig:analysis} \end{figure*} \begin{figure*}[ht] \centering \subfigure[Input image.]{ \begin{minipage}[t]{0.22\linewidth} \centering \includegraphics[width=1\linewidth]{training_set_results/121_original.eps}\vspace{4pt} \includegraphics[width=1\linewidth]{training_set_results/231_original.eps}\vspace{4pt} \includegraphics[width=1\linewidth]{training_set_results/241_original.eps}\vspace{4pt} \includegraphics[width=1\linewidth]{training_set_results/112_original.eps}\vspace{4pt} \end{minipage}} \subfigure[Estimated binary pattern.]{ \begin{minipage}[t]{0.22\linewidth} \centering \includegraphics[width=1\linewidth,height=0.625\linewidth]{training_set_results/121_pattern.eps}\vspace{4pt} \includegraphics[width=1\linewidth,height=0.625\linewidth]{training_set_results/231_pattern.eps}\vspace{4pt} \includegraphics[width=1\linewidth,height=0.625\linewidth]{training_set_results/241_pattern.eps}\vspace{4pt} \includegraphics[width=1\linewidth,height=0.625\linewidth]{training_set_results/112_pattern.eps}\vspace{4pt} \end{minipage}} \subfigure[\add{Binary pattern validation.}]{ \begin{minipage}[t]{0.22\linewidth} \centering \includegraphics[width=1\linewidth,height=0.625\linewidth]{training_set_results/121_validation.eps}\vspace{4pt} \includegraphics[width=1\linewidth,height=0.625\linewidth]{training_set_results/231_validation.eps}\vspace{4pt} \includegraphics[width=1\linewidth,height=0.625\linewidth]{training_set_results/241_validation.eps}\vspace{4pt} \includegraphics[width=1\linewidth,height=0.625\linewidth]{training_set_results/112_validation.eps}\vspace{4pt} \end{minipage}} \subfigure[Reproduced woven fabric of (b).]{ \begin{minipage}[t]{0.22\linewidth} \centering \includegraphics[width=1\linewidth]{training_set_results/121_reproduced.eps}\vspace{4pt} \includegraphics[width=1\linewidth]{training_set_results/231_reproduced.eps}\vspace{4pt} \includegraphics[width=1\linewidth]{training_set_results/241_reproduced.eps}\vspace{4pt} \includegraphics[width=1\linewidth]{training_set_results/112_reproduced.eps}\vspace{4pt} \end{minipage}} \centering \caption{Reproduced woven fabric by final decoded binary patterns.} \label{fig:result02} \end{figure*} For quantitative evaluation, for each representative crossing point in the \add{estimated binary pattern}\delete{manually labeled image}, the rate of correctly detected crossing points (Correct), the rate of incorrectly detected crossing points (Error), and the rate of points with no candidate points in distance $s$ (Missed) were calculated. These rates varied depending on the value of $s$ and were represented by ROC-like curves. Fig. \ref{fig:comparison}(e) shows the resulting label images and ROC-like curves. Note that we omitted the quantitative analysis for impulse peak pattern training. There were not enough extracted crossing points from impulse peak pattern training because resulting output images had few large white and black regions after post-processing. \id{(\#12,\#19,\#26,\#29,\#30,\#71,\#76)}\add{After extensive trial and error, we found a DNN with 12 layers, a $9 \times 9$ box-filter, and a distance threshold $s = 10$ indicated good performance. In the following, we show the experimental results for different filters, the window size, the number of layers, and the distance threshold s. From the image set used for the 11-fold cross-validation, we employed the worst group (160 images for training and 16 images for test) for the comparison experiment. } \vspace{0.2cm} \noindent {\it \id{(\#65,\#79)}{\add{Number of DNN layers}}} \add{To confirm the optimal structure of the DNN, we designed comparative experiments, reducing and increasing the number of neural network layers. The number of layers should be even because the same number of layers is required for encoder and decoder parts. The deepest layers near the bottleneck were added and removed for changing the number of layers. The smallest layer of 14-layer network is $5 \times 8 \times 48$, then we cannot add any more layers to 14-layer network. Fig. \ref{fig:analysis}(a) shows that the 12-layer neural network had an accuracy level of $74.13\%$. Under the same circumstances, the 10-layer neural network had an accuracy level of $74.88\%$, while the accuracy of the 14-layer neural network was $78.92\%$. For the size of the dataset and the degree of difficulty of the task, the 14-layer network had the best performance. } \vspace{0.2cm} \noindent {\it {\add{Filter parameters}}} \add{For the intermediate representation, we controlled other unchanged variables, and compared their results by changing the size of the filter. Although there were a number of values from which to choose, considering the feasibility of the experiment, as shown in Figs. \ref{fig:analysis}(b) and \ref{fig:analysis}(c), we compared the Box methods with filter sizes of 5, 7, 9, and 11; we compared the Gaussian methods with filter sizes of 3, 5, 7, and 9. When the filter size was 9, the Box-filter method had the highest accuracy of $78.92\%$, 7 and 11 had accuracy levels of $72.21\%$ and $73.99\%$, respectively. When the filter size was 5, the Gaussian-filter method had the highest accuracy of about $71.69\%$; 7 and 9 had accuracy levels of about $60.77\%$ and $41.00\%$, respectively. For Gaussian size 3 and Box size 5, we could not extract the binary pattern, so their accuracy was 0. By comparison, when the filter size of the Box-filter method was 9, that yielded the best result, and that was the scheme adopted for our method.} \vspace{0.2cm} \noindent {\it {\add{Distance threshold $s$}}} \delete{Each resulting label image showed the same trend, with approximately $90 \%$ of correct crossing points at $s=8$; $95 \%$ of correct crossing points at $s=13$; less than $0.1 \%$ of error crossing points at $s=13$; and only $5 \%$ of missed crossing points when $s$ was increased. This indicated that $95 \%$ of the crossing points were detected correctly within the distance $s$, while $5 \%$ of the warp and weft crossing points were detected incorrectly. Statistically, as shown in Table 1, the rate of correct crossing points was greatest at $s=13$, which was $94.09 \%$.} \add{Each resulting label image showed the same trend, as shown in Figs. \ref{fig:analysis}(d) and \ref{fig:analysis}(e), there were $47.47\%$ of correct crossing points at $s = 5$; $74.13\%$ of correct crossing points at $s = 10$; a $6.81\%$ error crossing points at $s = 10$; and only $0.67\%$ of missed crossing points when $s$ was increased. This indicated that $74.13\%$ of the crossing points were detected correctly within the distance $s$, while $7.48\%$ of the warp and weft crossing points were detected incorrectly. Statistically, the rate of correct crossing points was greatest at $s=15$, which was $74.44\%$. Considering the total rate of correct, error, and missed, the performance is the best at $s = 10$. } \subsection{Validation of decoded binary patterns} Fig. \ref{fig:result02} shows the results that were woven by the obtained binary pattern, together with the observed image. Since the input image contained crossing points near the image boundary that could not be expressed in the form of a matrix, we ignored the intersections near the boundary and evaluated them. \id{(\#20, \#34, \#40, \#59, \#72)}\add{In addition, we added binary pattern validation in Fig. \ref{fig:result02}(c) to show the analysis results. We evaluated whether the values of 0 and 1, given the grid points in the estimated binary image matched the values in the ground truth image. Each grid point corresponded to a pixel of the observed image, so we could check the match between it and the binary value of the nearest crossing point in the ground truth image. In Fig. \ref{fig:result02}(c), a red box shows that 0 was wrongly estimated as 1, and a blue box shows that 1 was wrongly estimated as 0 for each grid point.} In the patterns, we were able to obtain results that were close in appearance. Since some of the patterns were extracted that are not common as woven patterns, such as too many or too few crossing, there was room for the pattern to be improved by converting it with an uncommon pattern such as a restriction. \id{(\#20, \#34, \#40, \#57, \#59, \#72)}\add{Although the error in which 0 was wrongly set to 1 and vice-versa is different from a false positive or a false negative in a general sense, the accuracy and F-measure of the statistical metric can be applied to the data. The accuracy for 176 images was 0.930 and the F-measure was 0.929, on average.} Although the obtained pattern was not perfect, it can be said that the same pattern was approximately obtained automatically. \section{Conclusions} In this paper, we proposed a method for decoding the binary patterns that define the weaving of fabric. By developing intermediate representations, we were able to accomplish the task by deep learning. The pre-processing and post-processing allowed us to bridge the intermediate representation image and the binary pattern. The experimental results showed that our method allowed for correctly extracting $93\%$ of the crossing points, and the reproduced textiles were close to the original one in appearance. \id{(\#50)}\add{Although the box filter may not be optimal, it gives better results than the isotropic Gaussian filter. We consider this to be due to the grid arrangement of the yarns.} Only black and white yarn images were discussed in this paper. If the warp and weft are of one color each, the same processing is considered possible by converting the image according to the proximity of each color. Multiple colors may be used for weft yarns, and this will be handled by converting the image by the color distance from that of warp yarn; however we have not confirmed whether this will work well. That is a topic for future studies. \idr{(\#1)} It is necessary to ensure that each \add{of the pieces of} yarn \add{are}\delete{is} captured one by one in the observed image, which limits the scope of the observation. We need a method to integrate the resulting patterns observed at multiple locations. The resulting patterns are partially incomplete, which makes the problem more difficult. Various image stitching techniques are helpful. \id{(\#47)}\add{Although we used} \addr{LOG-filtered} \add{images for detecting the positions of the yarns, there is the possibility of improving the accuracy by introducing the structural tensor. In the case of textiles, the yarns are made of even finer yarns twisted together, so the fine edges can interfere with calculating the correct tensor.} We would like to address \delete{this issue} \add{these issues} in the future. \id{(\#12, \#21, \#30, \#76)}\add{We will also leave the further tasks of the optimization of network configuration and the selection of the backbone network to future work. } \idr{(\#3)}\addr{Recent powerful machine learning techniques \cite{Ahmadlou10,Rafiei17,Pereira20,Alam20} will contribute to improve the accuracy of pattern decoding even when the dataset is not large enough. } \section*{Acknowledgement} The authors appreciate the joint support for this project by the JSPS KAKENHI (Grant Nos. JP16H05867, JP20H04472), the NSFC-Zhejiang Joint Fund for the Integration of Industrialization and Informatization (Grant No. U1909210), the National Natural Science Foundation of China (Grant Nos. 61761136010, 61772163), \deleter{and} the Natural Science Foundation of Zhejiang Province (No.LY18F020016), \idr{(\#4)}\addr{and Zhejiang Lab Tianshu Open Source AI Platform (No.111007-AD1901)}.
{'timestamp': '2021-01-05T02:14:21', 'yymm': '2101', 'arxiv_id': '2101.00395', 'language': 'en', 'url': 'https://arxiv.org/abs/2101.00395'}
arxiv
\section{Introduction} \label{sec:intro} \blfootnote{\noindent This research was supported by the Office of Naval Research (ONR) under MURI Grant N00014-19-1-2621.} The Internet of Things (IoT) is arguably the most important technology of the coming decade \cite{saad2019vision}. However, the effective operation of several IoT services, such as industrial monitoring \cite{indus}, health monitoring \cite{health}, drones \cite{mohadrone}, virtual reality \cite{chenvr}, and vehicular network \cite{vehicular}, requires timely and frequent communications. To maintain the proper performance of such diverse IoT applications, the base station (BS) must maintain the most relevant information gathered from the IoT devices at any given time.\\ \indent In addition to timely transmissions from the devices to the BS, another key challenge is to account for the distinctive characteristics of an IoT and its devices. One prominent property of an IoT is its massive scale as the number of devices greatly outnumbers the available communication resources \cite{saad}. Therefore, an appropriate allocation of the limited communication resources among numerous IoT devices is necessary for the deployment of an IoT and its services \cite{iotalloc}. Furthermore, the IoT exhibits a high heterogeneity in terms of device types, functions, messages, transmission requirements, and resource constraints \cite{minehetero}. The aforementioned IoT properties pose challenges for timely uplink transmission in an IoT. To ensure the performance of time-sensitive IoT applications despite the aforementioned challenges, a new information timeliness performance metric is needed as an alternative to conventional delay, reliability, and data rate.\\ \indent To evaluate the communication between the BS and the devices, the \textit{age of information} (AoI), which is a metric that can quantify the relevance and the freshness of the information, is used \cite{aoi1, bo2}. However, the AoI has different characteristics compared to delay \cite{aoi1}, because it explicitly considers packet generation time. The problem of AoI minimization in an IoT has unique challenges due to the characteristics of an IoT, including massive scale, limited communication resources, and IoT device heterogeneity. Largely, AoI minimization can be done in a centralized way or in a distributed way. However, a centralized AoI minimization approach is not always viable for an IoT, because the energy constrained IoT devices may not be able to communicate frequently with BS. On the other hand, a distributed AoI minimization approach may require extensive device-to-device communication and could perform worse than a centralized solution for some IoT scenarios. Therefore, both centralized and distributed AoI minimization must be investigated to compare their applicability and performances in an IoT.\vspace{-1mm} \subsection{Existing Works} A number of recent works studied the problem of AoI minimization in wireless networks \cite{bo2, aoi1, aoischedule1, aoischedule3, multihop, adhoc, aoimultiaccess, aoischedule2, aoicsi, bo3, aoischedule4, multiinfo, multisource, aoibackoff, aoicsma, aoisleep, qm3, mm1, mg1, mg11, aoiurllc, qm2, aoinoma, nonlin1, gc2020}. These studies use various approaches to minimize the AoI under different constraints and conditions. For instance, the works in \cite{bo2, aoi1, aoischedule1, aoischedule3, multihop, adhoc, aoimultiaccess, aoischedule2, aoicsi, bo3, aoischedule4, multiinfo, multisource, aoibackoff, aoicsma, aoisleep,qm3, mm1, mg1, mg11, aoiurllc, qm2, aoinoma, nonlin1} study a variety of scheduling policies for AoI minimization in different networks, including single hop broadcast network \cite{aoischedule1}, single-hop uplink communication \cite{aoischedule3}, multi-hop uplink communication \cite{multihop}, ad-hoc networks \cite{adhoc}, and ALOHA-like random access \cite{aoimultiaccess}. The authors in \cite{aoischedule2} and \cite{aoicsi} propose and analyze scheduling policies for the wireless networks with known and unknown channel state information. The works in \cite{aoi1}, \cite{aoischedule3}, \cite{adhoc}, and \cite{bo3} introduce effective scheduling policies to minimize the average AoI with network constraints, such as throughput requirement, physical constraint for sensing, spectrum sharing, and varying packet sizes. In \cite{adhoc}, \cite{aoischedule4}, and \cite{multiinfo}, the authors use online techniques, such as reinforcement learning to perform AoI-minimal scheduling. Moreover, the authors in \cite{multiinfo} and \cite{multisource} analyze the performance of user scheduling for minimizing the average AoI in presence of multiple sources of information and propose a hybrid queueing system. The authors in \cite{aoibackoff} analyze the coexistence of DSRC and WiFi networks as a game, in which the DSRC network minimizes the AoI and the WiFi network maximizes the throughput. For CSMA networks, the work in \cite{aoicsma} optimizes the backoff time of each communication link to minimize the total average AoI, and the authors in \cite{aoisleep} propose a sleep-wake scheduling to optimize the tradeoff between AoI minimization and energy consumption.\\ \indent The works in \cite{qm3, mm1, mg1, mg11} address the problem of AoI minimization using queueing-theoretic approaches. In \cite{qm3}, the authors analyze the peak AoI in a multi-class queueing system with packets having heterogeneous service times and requirements. The authors in \cite{mm1, mg1, mg11} derive closed-form solutions for the average AoI and the peak AoI for different queueing models, including M/M/1, M/G/1, and M/G/1/1. In \cite{aoiurllc}, the authors consider a vehicular network with ultra-reliable low-latency communication and minimize the tail of the AoI distribution. The peak AoI considering the packet delivery failure is analyzed in \cite{qm2}. Moreover, the non-orthogonal multiple access is compared against the conventional orthogonal multiple access in terms of AoI minimization in \cite{aoinoma}. The authors study the sampling policies to minimize the average AoI with the joint status sampling in IoT \cite{bo2} or with the non-linear aging functions \cite{nonlin1}.\\ \indent Despite being interesting, the existing solutions in \cite{bo2, aoi1, aoischedule1, aoischedule3, multihop, adhoc, aoimultiaccess, aoischedule2, aoicsi, bo3, aoischedule4, multiinfo, multisource, aoibackoff, aoicsma, aoisleep, qm3, mm1, mg1, mg11, aoiurllc, qm2, aoinoma, nonlin1, gc2020} do not consider some of the unique properties of an IoT, such as limited communication resources, massive scale, and high device heterogeneity. One of the key challenges in IoT is the massive scale of IoT coupled with highly limited available communication resources. However, the works in \cite{aoi1, aoischedule1, aoischedule3, multihop, adhoc, aoimultiaccess, aoischedule4}, and \cite{qm2, aoinoma, nonlin1} do not investigate the realistic IoT scenario in which the number of devices greatly outnumbers the communication resources. Furthermore, the inherent heterogeneity among IoT devices and the presence of non-linear aging functions are not considered in \cite{bo2, aoischedule1, aoischedule3, multihop, adhoc, aoimultiaccess, aoischedule2, aoicsi, bo3, aoischedule4}, and \cite{mm1, mg1, mg11, aoiurllc, qm2, aoinoma}. Moreover, most of the prior works for AoI minimization in \cite{aoi1, aoischedule1, aoischedule3, multihop, adhoc, aoimultiaccess, aoischedule2, aoicsi, multiinfo, multisource,aoibackoff, aoicsma, aoisleep,qm3, mm1, mg1, mg11}, and \cite{nonlin1} only considers a centralized approach. Moreover, in \cite{gc2020}, we studied centralized AoI minimization with non-linear aging functions and proposed a centralized resource allocation scheme to enable the BS to consider different aging functions. However, the work in \cite{gc2020} only investigates a centralized approach for AoI minimization and does not introduce a distributed resource allocation framework for an IoT with non-linear aging functions. A centralized approach may not always be suitable for an IoT, because the frequent communication with BS is not viable for the energy constrained IoT devices. These important challenges for enhancing the AoI in an IoT have been largely overlooked in prior works \cite{bo2, aoi1, aoischedule1, aoischedule3, multihop, adhoc, aoimultiaccess, aoischedule2, aoicsi, bo3, aoischedule4, multiinfo, multisource, aoibackoff, aoicsma, aoisleep, qm3, mm1, mg1, mg11, aoiurllc, qm2, aoinoma, nonlin1, gc2020}. \subsection{Contributions} \indent The main contributions of this paper are novel centralized and distributed resource allocation frameworks that can be used to minimize the average instantaneous AoI for a massive IoT with heterogeneous devices and non-linear aging functions. In particular, we capture the heterogeneity among IoT devices using \emph{non-linear aging functions}. Typically, the AoI is defined only in terms of time, and it is assumed to increase linearly with a slope of $1$ \cite{aoi1}. However, the definition of the AoI can be broader such that the AoI can be a function of completeness, validity, accuracy, currency, and utility \cite{nonlin2, nonlin3}. Under such a broader definition of the AoI, the aging function can be defined as an age penalty function or an age utility function \cite{nonlin1}, which can be an exponential, linear, or step function \cite{nonlin2}. As such, we propose to capture the heterogeneity among IoT devices and messages by assigning different aging functions based on the devices types, the IoT application, the message content, and the transmission requirement.\\ \indent For centralized AoI minimization, we propose a new priority scheduling scheme with a learning perspective such that the device types and the aging functions can be determined. For non-linear aging functions, we show that using the future AoI for priority scheduling achieves a lower average instantaneous AoI than using the current AoI. Simulation results for the centralized approach show that the proposed priority scheduling scheme achieves $26.7\%$ lower average instantaneous AoI with high activation probability and $31.7\%$ lower average instantaneous AoI with high outage probability than a simple priority scheduling. In particular, our approach outperforms a simple priority scheduling and performs similar to a priority scheduling with complete information on device types and aging functions.\\ \indent For the distributed AoI minimization, we formulate a minority game \cite{kolkata}, such that massive number of IoT devices can share the limited available communication resources autonomously. Furthermore, a payoff function is designed to allow the messages with the highest AoI to transmit first in a self-organizing manner. We then show the conditions that a resource allocation among IoT devices must satisfy to achieve a Nash equilibrium (NE). We propose a stochastic crowd avoidance algorithm for the resource allocation game and prove that the resource allocation using our proposed algorithm converges to an NE with sufficient information and under certain network parameters. Simulation results for the distributed case show that the proposed algorithm is effective in minimizing the AoI even if the devices only have the partial information about other devices. The results show that our game-based approach achieves $63.6\%$ lower average instantaneous AoI with limited information and $45.8\%$ lower average instantaneous AoI with high outage probability than a random resource allocation. Moreover, after convergence, our game-based approach performs similar to the pre-determined resource allocation with complete information.\\ \indent The centralized and the distributed AoI minimization schemes are compared in terms of overhead, implementation, and requirements. In particular, the centralized AoI minimization has an overhead of uplink communication request, while the distributed AoI minimization has an overhead of device-to-device communication. Simulation results show that the distributed AoI minimization achieves $40$-fold higher average instantaneous AoI than the centralized AoI minimization in a massive IoT, where the communication resources are highly limited and the devices only have partial information. In a less constrained IoT, simulation results show that the distributed AoI minimization achieves $8$-fold higher average instantaneous AoI than the centralized AoI minimization. Although the centralized AoI minimization outperforms the distributed AoI minimization in terms of average instantaneous AoI, the distributed approach may be more suitable for an IoT, because the centralized approach may not be practical or viable for an IoT. As such, our analysis clearly showcases the contrasts between the two solutions.\\ \indent The rest of this paper is organized as follows. Section II introduces the system model and the non-linear aging functions. Section III analyzes the AoI minimization with coexistence of linear and non-linear aging functions. Section IV presents the centralized and the distributed resource allocations in an IoT. Section V analyzes the simulation results, while Section VI draws conclusions.\vspace{-2mm} \section{System Model}\label{sec:SM} Consider the uplink of a wireless IoT system consisting of one BS serving $N$ IoT devices. The IoT devices can transmit their messages to the BS using the communication resources allocated by either a centralized or distributed resource allocation scheme. To transmit to the BS, the IoT devices use time-slotted orthogonal frequency-division multiple access (OFDMA). Here, $R$ time-frequency resource blocks (RBs) are allocated to the IoT devices at each time slot. If more than one IoT device use a given RB, none of the messages transmitted using the given RB can be successfully decoded, which leads to transmission failures. This implies that at most $R$ devices can transmit successfully to the BS at a time slot. In an IoT where the number of devices $N$ greatly outnumbers the number of RBs $R$, RB allocation is critical for the operation of IoT, and RB allocation can be done in a centralized or in a distributed way.\\ \indent Under a centralized resource allocation scheme, the BS allocates the RBs to the IoT devices such that a given RB is used by only one device. Therefore, duplicate RB usage will not occur when using a centralized resource allocation. However, centralized resource allocation incurs an overhead related to the need that the devices request their uplink communication resources via a random access channel (RACH) \cite{aoi3gpp}. Furthermore, the uplink communication resource request using RACH can fail resulting in transmission failure. In contrast, when using a distributed resource allocation scheme, the devices decide which RB to use autonomously without any intervention from the BS and without RACH. Although there is no overhead related to the need for requesting uplink communication resources, distributed resource allocation incurs an overhead related to the devices cooperating to avoid duplicate RB usage. Since there is no RACH request when performing distributed resource allocation, no RACH request failures will happen. However, the uplink transmission may fail because of a duplicate RB usage.\\ \indent For both centralized and distributed resource allocations, the uplink transmission can also fail because of the RB outage. The RB outage is based on the signal-to-noise ratio (SNR) such that the transmission is considered to be a failure if the SNR is less than a given threshold $\epsilon \geq 0$. We consider a stationary Rayleigh fading channel with additive white Gaussian noise (AWGN), such that the statistical properties of channel do not change over time. Therefore, the SNR outage probability is $\Pr\left(\sfrac{S^2}{\sigma^2} \leq \epsilon \right)$, where the received signal power $S^2$ is an exponentially distributed random variable and $\sigma^2$ is the variance of the AWGN. We assume that the IoT devices only know the distributional properties of the channel and the AWGN at the receiver. Furthermore, we assume that all devices transmit with the same transmit power as the devices do not know exact channel gain \cite{chenvr, iotalloc}, and \cite{aoisp1, aoisp2, aoisp3}. Since we consider a Rayleigh fading channel, the received signal power $S^2$ is exponentially distributed, and the devices know the mean $\lambda^{-1}$ of $S^2$. We assume that the transmit powers of all IoT devices are equal, and, thus, the mean of the received signal power will be the same for all devices. When an IoT device uses multiple RBs simultaneously, then the transmit power will be equally divided among those RBs. For instance, if an IoT device $i$ uses $R_{i,t}$ RBs simultaneously at time slot $t$, then the received signal power is $\sfrac{S^2}{R_{i,t}}$. For an IoT device $i$ using $R_{i,t}$ RBs simultaneously at time slot $t$, the outage probability $p_{i,t}$ for device $i$ at time slot $t$ will be: \begin{equation} p_{i,t} = \Pr\left(\frac{\sfrac{S^2}{R_{i,t}}}{\sigma^2} \leq \epsilon \right). \label{outp1} \end{equation} Since $S^2$ is exponentially distributed with mean $\lambda^{-1}$, $\frac{\sfrac{S^2}{R_{i,t}}}{\sigma^2}$ is exponentially distributed with mean $(R_{i,t} \sigma^2 \lambda)^{-1}$ for a given $R_{i,t}$ and a known $\sigma^2$. Moreover, the outage probability $p_{i,t}$ can be interpreted as a cumulative distribution function of an exponential distribution. Since an exponential random variable $S^2$ with mean $\lambda^{-1}$ has a cumulative distribution function of $\Pr\left(S^2 \leq \epsilon\right) = 1 - \exp\left(-\lambda \epsilon\right)$ for $\epsilon \geq 0$, the outage probability $p_{i,t}$ in \eqref{outp1} will be: \begin{equation} p_{i,t} = 1 - \exp\left(-\left(R_{i,t} \sigma^2 \lambda\right)\epsilon\right). \label{outp2} \end{equation} For a successful uplink transmission, an RB must be used by only one device, and the SNR must be higher than a given threshold $\epsilon$.\\% devices static so we do not consider the pathloss? no need to mention for now, do not mention transmit power at all or max transmit power \indent One prominent feature of an IoT is its massive scale. In particular, the number of IoT devices $N$ greatly outnumbers the number of RBs $R$. For an IoT scenario where $N > R$, the problem of RB allocation among the IoT devices becomes more challenging. Another prominent feature of an IoT is the heterogeneity among the IoT devices. The IoT devices are heterogeneous in terms of message types, transmission requirements, and packet content. A metric that can be used to determine which $R$ out of the $N$ devices will transmit and to quantify the freshness of the information in perspective of the destination is AoI. Furthermore, the heterogeneity among the IoT devices and their messages can be captured by extending the definition of AoI to include the quality of information and introducing non-linear aging functions. \subsection{Age of Information The AoI is a metric that quantifies the freshness of the information in the perspective of a destination \cite{bo2}, and the definition of the AoI is the time elapsed since the generation of a message that is most recently received at the BS. In prior art on the AoI, devices are commonly assumed to generate the messages at will \cite{gatwill2} and to update BS with a new message just in time \cite{jintime}. The generate-at-will model for AoI implies that IoT devices can have messages to transmit to the BS at any time, and the just-in-time model for AoI implies that IoT devices transmit new message to the BS immediately after the successful transmission of the current message. However, for an IoT, the devices are not always \textit{active} and do not always have the messages to transmit to the BS. In our model, a device has a message to transmit to the BS at a given time slot with an activation probability $v_a$. If a device transmits to the BS unsuccessfully at a given time slot, then the device retransmits the message immediately at following time slot without a random backoff time. For the distributed RB allocation, the proposed game is designed to give incentive to devices with low AoI to not transmit. The RACH phase of the centralized RB allocation can use the game formulated for distributed RB allocation to achieve a lower average instantaneous AoI. Meanwhile, the random backoff time used in \cite{aoibackoff} and \cite{backoff} does not consider different aging functions, when the backoff time is determined for each device. For instance, a long backoff time can be assigned to a device with higher AoI and exponential aging function, while a short backoff time can be assigned to a device with low AoI and linear aging function.\\ \indent Minimizing the AoI implies that the destination maintains fresh information from the source. However, minimizing the AoI is different from simply minimizing delay\cite{aoi1}. The AoI is measured by an aging function, and it is typically assumed that all devices have the same, linear aging function with a slope of $1$\cite{aoi1}. However, by using different aging functions for different messages, the AoI can naturally capture the inherent heterogeneity among IoT devices and messages. For instance, depending on the device type and the message characteristics, the aging function can be assigned appropriately. If the device is a simple sensor transmitting a time-insensitive update messages, the appropriate aging function is a linear aging function. On the other hand, if the device is an industrial monitoring sensor transmitting a time-sensitive status report, the appropriate aging function is an exponential aging function. By using different aging functions, the AoI captures both the freshness of information and the value of information \cite{nonlin1, nonlin2, nonlin3}.\\ \indent To model the heterogeneous messages, we consider the coexistence of linear aging function and exponential aging function. In particular, with a linear aging function, the AoI from IoT device $i$ at the beginning of time slot $t \in \mathbb{Z}_+$ is: \begin{equation} a_i(t) = t - \delta_i(t), \label{af1} \end{equation} where $\delta_i(t)$ is time slot at which the most recent message from device $i$ received by the BS was generated. With an exponential aging function, the AoI from IoT device $i$ at the beginning of time slot $t \in \mathbb{Z}_+$ is: \begin{equation} b_i(t) = 2^{t - \delta_i(t) - 1}. \label{af2} \end{equation} Although a specific linear and exponential aging functions are considered, our proposed centralized and distributed approaches to minimize the AoI are not limited to these aging functions only, and any type of aging function can be used.\\ \indent In a scenario where all IoT devices have the same linear aging function with slope $1$, the IoT devices and the BS can easily determine the AoI of the messages by simply counting the number of time slots passed since the most recently received message was generated \cite{aoi1}. However, in our system model where different aging functions coexist, the aging function of a given message is determined by the content of the message\cite{nonlin2}. For instance, the aging function of a message whose content is critical would be the exponential aging function $b_i(t)$, while the aging function of a message whose content is normal would be the linear aging function $a_i(t)$ \cite{nonlin1}. This implies that the BS cannot determine the aging function directly before receiving it, and, thus, the BS cannot compute the AoI of the messages. Therefore, the devices determine the aging function of their own message and compute the current AoI.\\ \indent To capture the heterogeneity among the IoT devices, the IoT devices are classified into different types based on the probabilistic properties of their messages. A typical IoT device would not always have a time-sensitive message to send to BS. Additionally, a device that usually sends time-insensitive messages may sometimes have a critical message to send. In our model, we consider two types of devices. Type $1$ devices are more likely to have linearly aging messages than exponentially aging messages. In other words, type $1$ devices have the messages with aging function $a_i(t)$ with probability $m_1$ and have messages with aging function $b_i(t)$ with probability $(1-m_1)$ with $1 > m_1 > 0.5$. Type $2$ devices are more likely to have exponentially aging messages than linearly aging messages. In other words, type $2$ devices have messages with aging function $b_i(t)$ with probability $m_2$ and have messages with aging function $a_i(t)$ with probability $(1 - m_2)$ with $1 > m_2 > 0.5$. We assume that the characteristics of devices types, such as $m_1$ and $m_2$, are known to the BS, but the BS does not know the type of a given device. Although having different types of messages realistically models the heterogeneity of the IoT devices, this makes the RB allocation more challenging, because the messages transmitted by a given device may have different aging functions. With non-linear aging functions and heterogeneous device types, the problem of AoI minimization is different from AoI minimization with only linear aging function and homogeneous devices. Hence, next we investigate the problem of non-linear AoI minimization with coexistence of different aging functions and heterogeneous devices. \section{Non-linear AoI Minimization} \indent To minimize the average instantaneous AoI, the devices with highest AoI are permitted to transmit to the BS, and the AoI of different devices are compared to decide which devices are allocated the RBs in a massive IoT. Without coexistence of different aging functions, comparing AoI from different devices to allocate the limited RBs is simple. If all devices have same linear aging function $a_i(t)$, then $a_i(\tau) > a_h(\tau)$ implies $a_i(\tau + \beta) > a_h(\tau + \beta)$ for any positive integers $\tau$ and $\beta$ given that devices $i$ and $h$ do not transmit successfully to the BS. Therefore, in a massive IoT with $N > R$, comparing current AoI with $t = \tau$ at time slot $\tau$ can be used to decide which $R$ out of $N$ devices transmit and to minimize the average instantaneous AoI. Furthermore, using current AoI with $t = \tau$ or using future AoI with $t = \tau+\beta$ at time slot $\tau$ is equivalent, when all devices have same linear aging function $a_i(t)$.\\ \indent When a linear aging function $a_i(t)$ and an exponential aging function $b_i(t)$ coexist, it is insufficient to only compare the AoI of different devices to minimize the average instantaneous AoI, and RBs must be allocated considering the aging functions to minimize the average instantaneous AoI. For instance, even if a device $i$ with $b_i(t)$ has lower AoI than a device $h$ with $a_h(t)$, device $i$ will eventually have higher AoI than device $h$, because $b_i(t)$ increases faster than $a_h(t)$. Therefore, the AoI comparison must take aging functions into account, and one way to consider the aging functions is to compare the future AoI.\\ \indent The optimization problem to minimize the average instantaneous AoI at time slot $\tau$ is: \begin{align} \min_{\boldsymbol{n}}& \ \ \frac{1}{N}\left(\sum_{i \in \boldsymbol{n}} z_{i}'(\tau) + \sum_{i \not \in \boldsymbol{n}, i \in \boldsymbol{N}} z_{i}(\tau)\right)\\ \textrm{s.t.} &\ \ \boldsymbol{n} \subseteq \boldsymbol{N},\\ &\ \ |\boldsymbol{n}| = R, \end{align} where $\boldsymbol{N} = \{1, \cdots, N\}$ is set of all devices, $z_{i}'(\tau)$ is aging function of device $i$ such that $\delta_i(\tau) \neq \delta_i(\tau-1)$ is updated, and $z_{i}(\tau)$ is aging function of device $i$ such that $\delta_i(\tau) = \delta_i(\tau-1)$. $\boldsymbol{n}$ is a set of all devices allocated the RBs at $(\tau-1)$, while $\boldsymbol{N} - \boldsymbol{n}$ is a set of all devices not allocated the RBs at $(\tau-1)$. Next, for the problem of instantaneous AoI minimization, we prove that performing RB allocation based on the future AoI achieves a lower average instantaneous AoI than an alternative that is based on the current AoI. \begin{proposition} \label{pp1} \normalfont In a massive IoT where $N > R$, if there are different aging functions $a_i(t)$ and $b_i(t)$, comparing the future AoI with $t = \tau + \beta$ for some positive integer $\beta$ at time slot $\tau$ to determine the RB allocation achieves a lower average instantaneous AoI than comparing the current AoI with $t = \tau$. \end{proposition} \begin{proof} See Appendix \ref{app1}. \end{proof} \indent From Proposition \ref{pp1}, we observe that allocating RBs to the devices with highest future AoI results in a lower overall average instantaneous AoI of all devices at all time slots than allocating RBs to the devices with highest current AoI. It is important to note that the current AoI at the time slot of successful transmission is used to compute the average instantaneous AoI, and the future AoI is only used to determine the RB allocation. In Proposition \ref{pp1}, the value of the positive integer $\beta$ in determining which future AoI to use for the RB allocation is a design parameter, and different values of $\beta$ have different effects. If higher values of $\beta$ are used, devices with exponentially aging messages are more likely to be allocated the RBs than devices with linearly aging messages. This implies that devices with exponentially aging messages are allocated the RBs even when their current AoI is low, while devices with linearly aging messages are not allocated the RBs even when their current AoI is high. Therefore, the exponentially aging messages are being transmitted before the linearly aging messages. In other words, with higher values of $\beta$, the average instantaneous AoI of IoT devices with exponentially aging messages is lower, while the average instantaneous AoI of IoT devices with linearly aging messages is higher. Furthermore, using higher values of $\beta$ for the future AoI does not necessarily achieve a lower average instantaneous AoI, and $\beta$ can be chosen depending on how much the exponentially aging messages are prioritized over the linearly aging messages. In our system model, the centralized and the distributed RB allocations use future AoI with $\beta = 1$.\\ \indent We consider that the IoT devices may have messages requiring multiple RBs to successfully transmit to the BS. When the messages take multiple RBs to successfully transmit, $\delta_i(t)$ in \eqref{af1} and \eqref{af2} will represent the time slot during which the most recent message from device $i$, which is fully received by BS, was generated. In this case, the devices must determine how to transmit the messages taking multiple RBs. In particular, if a device $i$ has a message that requires $n_i$ RBs to transmit, then the message may be transmitted simultaneously by using $n_i$ RBs at a given time slot, consecutively by using $1$ RB each time for $n_i$ time slots, or jointly by using both simultaneous and consecutive transmissions. The simultaneous transmission may complete the transmission at once reducing the AoI, but it has high $R_{i,t}$ and outage probability $p_{i,t}$ \eqref{outp2}. A consecutive transmission achieves its lowest outage probability $p_{i,t}$ with $R_{i,t} = 1$, but it takes the largest number of time slots to completely transmit increasing the AoI. Therefore, the problem of AoI minimization must consider the outage probability. The optimization problem to minimize the average instantaneous AoI for a device $i$ with a linearly aging message requiring $n_i$ RBs at time slot $\tau$ is: \begin{align} \min_{\boldsymbol{R}}& \ \ a_i\left(\tau + \sum_{j = \tau}^{\tau + n_i - 1} (1 - p_{i,j})^{-1}\right), \label{opt}\\ \textrm{s.t.} &\ \ \sum\nolimits_{j = \tau}^{\tau + n_i - 1} R_{i,j} = n_i,\\ &\ \ 0 \leq R_{i,j} \leq R \ \forall \ j, \end{align} where $\boldsymbol{R} = [R_{i,\tau}, ..., R_{i, \tau+n_i-1}]$. Since $R_{i, \tau} \in \mathbb{Z}_+$, $|\boldsymbol{R}| = n_i$, and $n_i$ is typically small for the IoT devices \cite{iotshort}, the solution space of optimization problem \eqref{opt} is finite and small. Therefore, the optimization problem can be solved easily using any discrete optimization method, such as combinatorial optimization. In particular, for any $n_i$, the optimization problem \eqref{opt} can be mapped as a directed graph with $(1 - p_{i,j})^{-1}$ as weights to find a shortest path. When a device uses $R_{i,t}$ RBs simultaneously, $(1 - p_{i,t})$ is the probability of successful transmission given that duplicate RB selection did not occur. Taking $(1 - p_{i,t})$ as the success probability in a geometric distribution, the expected number of time slots needed for the successful transmission when using $R_{i,t}$ RBs simultaneously is $(1 - p_{i,t})^{-1}$, which is the mean of the geometric distribution. Therefore, $\sum_{j = \tau}^{\tau + n_i - 1} (1 - p_{i,t})^{-1}$ is the expected number of time slots needed to transmit a message requiring $n_i$ RBs. If a device $i$ has an exponentially aging message, $b_i(t)$ replaces $a_i(t)$ in \eqref{opt}. The solution to the optimization problem \eqref{opt} determines the number of RBs $R_{i,\tau}$ that a device $i$ should be allocated with at time slot $\tau$ so that the average instantaneous AoI is minimized. Furthermore, the solution to the optimization problem is used for centralized and distributed approaches for the RB allocation. \section{Resource Block Allocation} In a massive IoT with $N > R$, RB allocation is a challenging problem especially given the high heterogeneity among IoT devices and the messages. RB allocation in an IoT can be done in a centralized way or in a distributed way. Moreover, RB allocation schemes can achieve a lower average instantaneous AoI by allocating the limited RBs to IoT devices with higher future AoI. Centralized RB allocation scheme is based on a priority scheduling improved with maximum likelihood to determine the aging functions and to learn the device types. The proposed distributed RB allocation scheme in Algorithm 1 is designed to enable only the devices with sufficiently high future AoI to transmit, and the proposed stochastic crowd avoidance algorithm is proved to converge to an NE of the formulated game. \subsection{Centralized RB Allocation} For centralized RB allocation, the BS allocates the RBs to the IoT devices. In a time slot. the centralized approach has two phases. The active devices request for the RB using RACH in the first phase. If an active device is allocated an RB, the active device transmits its message to the BS in the second phase. Although there will be no duplicate RB usage causing a transmission failure in the second phase, there may be RACH preamble collision causing an RB request failure in the first phase. Therefore, using centralized RB allocation scheme, a device fails to transmit to the BS because of the RACH preamble collision, the outage based on SNR, and the lack of RB allocation.\\ \indent We let $P$ be the number of RACH preambles and $N_t$ be the number of active devices at time slot $t$. The probability of the RACH preamble collision $c_t$ at time slot $t$ is: \begin{equation} c_t = 1 - \left(\frac{P-1}{P}\right)^{N_t-1}, \label{prefail} \end{equation} which is the probability of more than one active device using a given RACH preamble. If a device fails to request for an RB at time $t$ with probability $c_t$, then this is equivalent to a transmission failure. However, if a device $i$ successfully requests for an RB at time $t$, IoT device $i$ sends the information about its current AoI $C_i$ and the necessary number of RBs $R_{i,t}$ at time slot $t$. After gathering the information from the devices, the BS determines the RB allocation based on the future AoI of devices to minimize the average instantaneous AoI.\\% need to defend why not just send F_i, no need to learn type if you send F_i from the beginning \indent In the second phase, the BS allocates the RBs to the active devices using a priority scheduling based on the future AoI. The priority scheduling allocates the $R$ RBs to at most $R$ active devices with the highest future AoI, minimizing the average instantaneous AoI. If a device $i$ with high future AoI has $R_{i,t} > 1$, then IoT device $i$ may be allocated more than $1$ RB at time slot $t$. The problem in the second phase is determining the future AoI using the received current AoI because of the coexistence of different aging functions. In other words, the BS does not know the aging function of an active device $i$, and the BS must determine the aging function to compute the future AoI $F_i$, which is used for the priority scheduling scheme to achieve a lower average instantaneous AoI as shown in Proposition \ref{pp1}. However, the BS can determine the current aging function of an active device $i$ from $C_i$.\\ \indent The BS can determine that the aging function of an active device $i$ is $a_i(t)$, when $C_i$ cannot be derived using $b_i(t)$. The possible values of AoI using $a_i(t)$ are $\{1, 2, 3, 4, ...\}$, and the possible values of the AoI using $b_i(t)$ are $\{1, 2, 4, 8, ...\}$. Therefore, the values of AoI that are only possible using $a_i(t)$ are $\{3, 5, 6, 7, ...\}$. If the received current age $C_i$ from an active device $i$ is one of $\{3, 5, 6, 7, ...\}$, then the aging function is $a_i(t)$, and, thus, the future AoI $F_i$ of device $i$ is $C_i + 1$. The BS can also determine the aging functions of active devices by using regression. For an active device $i$, the BS can use the AoI from the most recently received uplink request from device $i$ and $C_i$ to determine if the aging function is $a_i(t)$ or $b_i(t)$. After determining the aging functions of active devices, the BS can compute the future AoI $F_i$ of active devices and learn the device types, which are used for the priority scheduling scheme with learning. The BS can use either of the two methods to accurately determine the current aging functions, but it is not always possible to use these methods. When both methods are not possible to use in a given time slot due to RACH preamble collision, the BS uses the expected value of $F_i$ for the priority scheduling scheme.\\ \indent The BS can compute the expected value of $F_i$ of an active device $i$ by learning the device type of device $i$. The BS can learn the type of a device $i$ by using the previous data from the instances that the BS was able to determine the aging function of messages from device $i$. In particular, the BS can use a maximum likelihood to determine the device types. We let $\mathcal{S}$ be a set of all device types and $\boldsymbol{O}_i$ be a vector of aging functions that a device $i$ had that the BS was able to determine exactly. Furthermore, we let $k_{i,f}$ be the number of times that the BS determined device $i$ to have aging function $f$. Assuming that the aging functions of a device $i$ are determined independently, the learned type $H_i \in \mathcal{S}$ of a device $i$ is: \begin{align} H_i &= \argmax\limits_{s \in \mathcal{S}} \Pr(\boldsymbol{O}_i \mid s) = \argmax\limits_{s \in \mathcal{S}} \prod\limits_{f\in\mathcal{F}} {\Pr(f \mid s)}^{k_{i,f}},\\ &= \argmax\limits_{s \in \mathcal{S}} \sum\limits_{f\in\mathcal{F}} {k_{i,f}}\ln(\Pr(f\mid s)), \label{ml} \end{align} where $\mathcal{F}$ is a set of all aging functions. For our model, the values of $\Pr(f \mid s)$ for any $f \in \mathcal{F}$ and $s \in \mathcal{S}$ are known. In particular, $\Pr(a_i \mid s = 1) = m_1$, $\Pr(b_i \mid s = 1) = 1 - m_1$, $\Pr(a_i \mid s = 2) = 1 - m_2$, and $\Pr(b_i \mid s = 2) = m_2$. Therefore, the maximum likelihood in \eqref{ml} can be solved by the BS directly.\\ \indent Once the device type of a device $i$ is learned, the expected future AoI $\mathbb{E}[F_i]$ of device $i$ can be computed. For our model, if $H_i = 1$, then the expected future AoI $\mathbb{E}[F_i\mid H_i = 1]$ is: \begin{equation} \mathbb{E}[F_i \mid H_i = 1] = m_1(C_i + 1) + (1 - m_1)(2C_i). \end{equation} If $H_i = 2$, then the expected future AoI $\mathbb{E}[F_i\mid H_i = 2]$ is: \begin{equation} \mathbb{E}[F_i \mid H_i = 2] = (1 - m_2)(C_i + 1) + m_2(2C_i). \end{equation} The expected value of $F_i$ is used for the priority scheduling scheme only if the exact value of $F_i$ cannot be determined.\\ \indent Priority scheduling determines the RB allocation among the active IoT devices based on the future AoI $F_i$. In a time slot $\tau$, the RBs are allocated first to the devices with the highest $F_i$. Furthermore, for a device $i$ with highest $F_i$ at time slot $\tau$, the number of RBs allocated to device $i$ is $R_{i, \tau}$. If some of the active devices have same $F_i$, then the RBs are allocated first to the devices whose type is more likely to have a faster aging function. For instance, if a device $i$ is device type $1$, a device $j$ is device type $2$, and $F_i = F_j$, then device $j$ has a priority over device $i$, because device $j$ is more likely to have exponentially aging messages. The RBs are allocated to the active devices until all RBs are allocated or all active devices are allocated the RBs.\\ \begin{algorithm}[t] \caption{Priority scheduling based on future AoI at time slot $t$.} \begin{algorithmic}[1]\label{centalg}\vspace{1mm} \item[1 :] \hspace{0.0cm} Receive values $C_i$ and $R_{i,t}$, and initialize $R$. \item[2 :] \hspace{0.0cm} Compute $F_i$ or $\mathbb{E}[F_i]$ for each $C_i$. \item[3 :] \hspace{0.0cm} {\bf for} $j = 1, 2, \cdots$ \item[4 :] \hspace{0.3cm} $\mathcal{Z}_1 \leftarrow$ set of type $1$ devices with $j$-th highest value among $F_i$. \item[5 :] \hspace{0.3cm} $\mathcal{Z}_2 \leftarrow$ set of type $2$ devices with $j$-th highest value among $F_i$. \item[6 :] \hspace{0.3cm} {\bf for all $i \in \mathcal{Z}_2$} \item[7 :] \hspace{0.6cm} {\bf if} $R > 0$, \item[8 :] \hspace{0.9cm} Allocate $\textrm{min}(R, R_{i,t})$ RBs to device $i$. \item[9 :] \hspace{0.9cm} $R \leftarrow R - \textrm{min}(R, R_{i,t})$. {\bf end if} \item[10 :] \hspace{0.3cm} {\bf end for} \item[11 :] \hspace{0.3cm} {\bf for all $i \in \mathcal{Z}_1$} \item[12 :] \hspace{0.6cm} {\bf if} $R > 0$, \item[13 :] \hspace{0.9cm} Allocate $\textrm{min}(R, R_{i,t})$ RBs to device $i$. \item[14 :] \hspace{0.9cm} $R \leftarrow R - \textrm{min}(R, R_{i,t})$. {\bf end if} \item[15 :] \hspace{0.3cm} {\bf end for} \item[16:] \hspace{0.0cm} {\bf end for} \end{algorithmic}\vspace{1mm} \end{algorithm} \indent One of the major problems with priority scheduling is the infinite blocking of low-priority tasks. However, since the priority depends on the future AoI, the priority of low-priority messages increases with time. Therefore, regardless of the aging function or the device type, the messages will eventually be allocated the RBs to transmit to the BS. One of the limitations of centralized RB allocation scheme is the overhead related to the RB request via RACH. With the higher number of active devices $N_t$ at time $t$, the probability of the RACH preamble collision $c_t$ becomes significant, and, thus, more transmission failures occur. Furthermore, with centralized RB allocation scheme, a frequent communication between the devices and the BS is required, which may not be viable for the IoT devices \cite{nocent}. However, the main advantage of centralized RB allocation scheme is that the RBs are fully utilized. \subsection{Distributed RB Allocation} Distributed RB allocation enables the devices to allocate the RBs in a self-organizing manner without any intervention from the BS. Since a duplicate RB selection results in transmission failures, the active devices must choose the RBs such that no other device is choosing the same RB. Furthermore, the distribution RB allocation can be modeled as one-to-one association between the RBs and the devices. The behavior of the devices wanting to choosing an RB alone can be formulated as a minority game \cite{iotkolkata}.\\ \indent A suitable minority game for distributed RB allocation in an IoT is the Kolkata paise restaurant (KPR) game \cite{kolkata}. The KPR game is a repeated game in which the customers simultaneous go to one of the restaurants, which can only serve one customer each. Additionally, the cost of going to a restaurant is the same for all restaurants, and a customer can only go to one restaurant at any given time. In the KPR game, the players are the customers, whose action in each iteration is to choose one of the restaurants. The payoff of a given player depends on the utility of the chosen restaurants and the number of players choosing the same restaurant. Given players, actions, and payoffs in a game, one important stable solution is an NE. A vector of actions is an NE if no player can achieve a higher payoff by a unilateral change of action. For the KPR game, the existence of an NE depends on the utilities of the restaurants \cite{kolkata}, and an NE is when all customers go to different restaurants and none of the customers have the utility of $0$. If an NE exists in the KPR game, it coincides with the socially optimal solution, which is when all restaurants are being utilized.\\ \indent The fundamental structure of the KPR game can be readily extended for our IoT model. The customers can be modeled as IoT devices, and the restaurants can be modeled as the RBs. Furthermore, the cost of using any of the RBs is same. However, there are significant differences between the KPR game and the IoT game. In the KPR game, the number of customers and the number of restaurants are the same, and each customer goes to one of the restaurants at every iteration. In the IoT game, the number of devices $N$ and the number of RBs $R$ may not be the same, and not all devices are active and need to use the RBs at each time slot. The most significant difference is the payoff in the case of duplicate RB selection. When multiple customers choose the same restaurant in the KPR game, one of those customers is randomly chosen to get the full payoff, while other customers with duplicate selection get a zero payoff. However, in the IoT game, all devices that choose the same RB get a zero payoff because of the transmission failures.\\ \indent For our AoI minimization, the players are the $N$ IoT devices, and their action is to transmit using the RBs or not to transmit. We let $\mathcal{R}$ be the set of $R$ RBs and let $x_i(t)$ be the action of device $i$ at time slot $t$. If $x_i(t) \in \mathcal{R}$, then device $i$ transmits using the RB in $x_i(t)$ at time slot $t$. If $x_i(t) = 0$, then device $i$ does not transmit at time slot $t$. at each time slot, the payoff of each device depends on the actions of all devices. If a device transmits successfully by using an RB alone, then the payoff is $\rho$. Furthermore, a successful transmission using any of the RBs has the same payoff of $\rho$. If a device transmits unsuccessfully due to a duplicate RB usage, then the payoff is $-\gamma$. The transmission failure has a negative payoff, because the energy is consumed for the transmission without success. Additionally, the transmission failure using any of the RBs has the same payoff of $-\gamma$, and $\rho$ and $\gamma$ are positive numbers such that $\rho > \gamma$.\\ \indent To minimize the AoI of the devices, active devices with lower AoI must not transmit, while the active devices with high AoI need to transmit. Using a distributed RB allocation scheme, the devices must know the AoI of other devices to determine if their own AoI is high enough to transmit. We assume that the active devices broadcast their own future AoI $F_i$ to other devices within the communication range $r_c$, and the communication resource for this broadcast is pre-allocated. Moreover, we assume that device-to-device communication links are orthogonal to the uplink communication as done in \cite{iotd2d1, iotd2d2, iotd2d3, iotd2d4, iotd2d5}. Similar to the overhead related to the RACH uplink request for centralized RB allocation scheme, the communication between the devices to share the AoI can be seen as the overhead for distributed RB allocation scheme. However, depending on $r_c$, the active devices may not know $F_i$ of all other active devices. We let $\alpha_i$ be the active status of a device $i$ such that $\alpha_i = 0$ implies that device $i$ is inactive and $\alpha_i = 1$ implies that device $i$ is active. We let $\boldsymbol{A}$ be a vector that captures the future AoI $F_i$ of all active devices, and $\boldsymbol{A}_i$ be a vector of the future AoI $F_i$ of the active devices within $r_c$ of an active device $i$. With $r_c$ sufficiently large, $|\boldsymbol{A}_i| = |\boldsymbol{A}|$ for all devices, where $|\boldsymbol{A}|$ is the cardinality of $\boldsymbol{A}$. For an active device $i$, if $F_i$ is higher than $\kappa$-th highest AoI in $\boldsymbol{A}_i$, then the active device $i$ transmits. $\kappa$ determines if $F_i$ is sufficiently higher than the future AoI of other active devices, and we let $\boldsymbol{A}_i(\kappa)$ be the $\kappa$-th highest AoI in $\boldsymbol{A}_i$. Moreover, $\kappa$ should ensure that the number of transmitting devices $T_t$ at time slot $t$ is equal to $R$ such that all transmitting devices can be allocated with the RB. If $T_t$ is higher than $R$, then there are at least two active devices with transmission failure, which causes the average instantaneous AoI to increase. If $T_t$ is less than $R$, then there are some of the RBs not used by any of the active devices, which may cause the average instantaneous AoI to increase. However, $T_t = R$ is difficult to achieve when $r_c$ is not sufficiently large and $|\boldsymbol{A}_i| < |\boldsymbol{A}|$.\\ \indent When $|\boldsymbol{A}_i| = |\boldsymbol{A}|$, the devices have full information on the future AoI $F_i$ of the active devices. Moreover, the devices know all active devices. Since the devices have full information of $F_i$, an active device $i$ transmits if $F_i \geq \boldsymbol{A}_i(R)$, and an active device $i$ does not transmit if $F_i < \boldsymbol{A}_i(R)$. Therefore, $\kappa = R$ when $|\boldsymbol{A}_i| = |\boldsymbol{A}|$ for all $i$. This ensures that $R$ active devices transmit, while $|\boldsymbol{A}| - R$ devices do not transmit. Therefore, the number of transmitting devices $T_t$ at time slot $t$ is equal to $R$. To formulate this decision to transmit or not to transmit into the payoff, the payoff $y_{\textrm{full}}$ when an active device $i$ does not transmit is: \vspace{-2mm} \begin{multline} y_{\textrm{full}}(\boldsymbol{A}_i) = (\rho + \eta) \theta_{\mathbb{R}_{+}}(\boldsymbol{A}_i(R) - F_i-\eta)\\ - (\gamma + \eta) \theta_{\mathbb{R}_{+}}(F_i - \boldsymbol{A}_i(R)), \label{payoff1} \end{multline} where $\eta$ is a real number in $(0, 1)$ and $\theta_{\mathbb{R}_{+}}$ is an indicator function such that: \begin{equation} \theta_{\mathbb{R}_{+}}(x)=\left\{ \begin{array}{ll} 1 \hfill &\text{if} \ x \in [0, \infty),\\ 0 \hfill &\text{if} \ x \not\in [0, \infty). \end{array} \right. \end{equation} The function of $\eta$ in payoff functions is to ensure that the payoff functions are used as intended and only appropriate indicator function is activated. It is important to note that $y_{\textrm{full}}(\boldsymbol{A}_i)$ does not depend on actions of the players, because the decision to transmit or not to transmit only depends on future AoI. Given the payoff in \eqref{payoff1}, the $R$ active devices with $F_i \geq \boldsymbol{A}_i(R)$ transmit, because their payoff of not transmitting is $-(\gamma + \eta)$. The $|\boldsymbol{A}| - R$ active devices with $F_i < \boldsymbol{A}_i(R)$ do not transmit, because their payoff of not transmitting is $\rho + \eta$. Therefore, IoT devices with $R$ highest future AoI transmit, while other devices do not transmit.\\ \indent In a more realistic scenario where IoT devices do not have full information of $F_i$, $|\boldsymbol{A}_i| < |\boldsymbol{A}|$, and the devices do not know all active devices. It is difficult to make only $R$ active devices to transmit at time slot $t$, and, thus, $\kappa$ is designed to make $T_t \approx R$. For the case of $|\boldsymbol{A}_i| < |\boldsymbol{A}|$, $\kappa$ is: \begin{equation} \kappa = \left\lceil\frac{R}{|\boldsymbol{A}|} |\boldsymbol{A}_i|\right\rceil, \label{kappa1} \end{equation} where $\kappa = R$ in the case of $\boldsymbol{A} = \boldsymbol{A}_i$. However, with partial information, the active devices do not know $\boldsymbol{A}$ in \eqref{kappa1}. $|\boldsymbol{A}|$ is the number of active devices, and the expected number of newly active devices is $Nv_a$. However, with previously active devices yet to transmit successfully, $|\boldsymbol{A}|$ is typically greater than $Nv_a$. Therefore, in \eqref{kappa1}, $|\boldsymbol{A}|$ can be estimated with $N v_a \zeta$, where $\zeta$ is a design parameter to consider the number of previously active devices yet to transmit successfully. With higher values of $\zeta$, the number of transmitting devices $T_t$ at time slot $t$ is smaller, while $T_t$ is bigger with smaller values of $\zeta$. Therefore, with approximation for $|\boldsymbol{A}|$, $\kappa$ is: \begin{equation} \kappa = \left\lceil\frac{R}{N v_a \zeta} |\boldsymbol{A}_i|\right\rceil. \label{kappa2} \end{equation} For an active device $i$, $\kappa$ in \eqref{kappa2} approximates if $F_i$ is sufficiently higher than the future AoI of other active devices based on the percentile of $F_i$ on the known vector of future AoI $\boldsymbol{A}_i$. With $|\boldsymbol{A}_i| < |\boldsymbol{A}|$, the payoff $y_{\textrm{act}}$ when an active device $i$ does not transmit is:\vspace{-2mm} \begin{multline} y_{\textrm{act}}(\boldsymbol{A}_i) = (\rho + \eta) \theta_{\mathbb{R}_{+}}(\boldsymbol{A}_i(\kappa) - F_i-\eta)\\ - (\gamma + \eta) \theta_{\mathbb{R}_{+}}(F_i - \boldsymbol{A}_i(\kappa)). \label{payoff2} \end{multline} It is important to note that $y_{\textrm{act}}(\boldsymbol{A}_i)$ is equal to $y_{\textrm{full}}(\boldsymbol{A}_i)$, when the active devices have full information with $|\boldsymbol{A}_i| = |\boldsymbol{A}|$ and $\kappa = R$. Similar to $y_{\textrm{full}}(\boldsymbol{A}_i)$ \eqref{payoff1}, with the payoff $y_{\textrm{act}}(\boldsymbol{A}_i)$, the active devices with sufficiently high $F_i$ satisfying $F_i \geq \boldsymbol{A}_i(\kappa)$ transmit, while the active devices with $F_i$ such that $F_i < \boldsymbol{A}_i(\kappa)$ do not transmit. Moreover, $y_{\textrm{act}}(\boldsymbol{A}_i)$ also does not depend on actions of the players.\\ \indent In the IoT game, the payoff needs to consider the inactive devices. The inactive devices with $\alpha_i = 0$ do not transmit as they do not have messages to transmit. The payoff $y_{\textrm{nt}}$ when an device $i$ does not transmit is: \vspace{-1mm} \begin{equation} y_{\textrm{nt}}(\boldsymbol{A}_i, \alpha_i) = (1 - \alpha_i)(\rho + \eta) + \alpha_i y_{\textrm{act}}(\boldsymbol{A}_i). \vspace{-1mm} \end{equation} With payoff $y_{\textrm{nt}}(\boldsymbol{A}_i, \alpha_i)$ for not transmitting, the inactive devices with $\alpha_i = 0$ do not transmit as they get payoff of $\rho + \eta$. The active devices with $\alpha_i = 1$ decide to transmit or to not transmit based on $\kappa$ and future AoI. We let $\boldsymbol{x}(t) = [x_1(t), x_2(t), \cdots, x_N(t)]$ be a vector of all actions of $N$ devices at time slot $t$. For a given $\boldsymbol{x}(t)$, the payoff function $y_i(\boldsymbol{x}(t), \boldsymbol{A}_i, \alpha_i)$ for a device $i$ at time slot $t$ is: \vspace{-2mm} \begin{multline} y_i(\boldsymbol{x}(t), \boldsymbol{A}_i, \alpha_i)\\ =\left\{ \begin{array}{ll} \rho \hfill &\text{if} \ x_i(t) \neq x_j(t) \ \forall \ j \neq i, x_i(t) \neq 0,\\ -\gamma \hfill &\text{if} \ \exists \ j \neq i \ \text{s.t.} \ x_j(t) = x_i(t) \neq 0,\\ y_{\textrm{nt}}(\boldsymbol{A}_i, \alpha_i) \hfill &\text{if} \ x_i(t) = 0.\\ \end{array} \right. \label{payoff3}\vspace{-2mm} \end{multline} In a simple game where $N = R = 2$ with $v_a = 1$, the payoffs of two devices at each time slot is summarized in Table \ref{game1}. NE in this IoT game is $\boldsymbol{x}(t) = [1, 2]$ or $\boldsymbol{x}(t) = [2, 1]$. For simple IoT game, NE is when two devices choose different RBs and get the payoff of $\rho$. If one device deviates from NE and the other device does not deviate from NE, the device deviating from NE gets the lower payoff of $-\gamma$ or $-(\gamma + \eta)$. Furthermore, in the IoT game, NE implies that a duplicate RB selection does not occur. An NE for a more general case of the IoT game can be found with certain conditions. \begin{table}[t] \centering \vspace{0mm} \caption{IoT game with $N = R = 2$.} \label{game1} \begin{tabular}{rccc} & $x_1(t) = 1$ & $x_1(t)=2$ & $x_1(t) = 0$ \\ \cline{2-4} \multicolumn{1}{r|}{$x_2(t) = 1$} & \multicolumn{1}{c|}{$(-\gamma, -\gamma)$} & \multicolumn{1}{c|}{$(\rho, \rho)$} & \multicolumn{1}{c|}{$(-(\gamma + \eta), \rho)$} \\ \cline{2-4} \multicolumn{1}{r|}{$x_2(t) = 2$} & \multicolumn{1}{c|}{$(\rho, \rho)$} & \multicolumn{1}{c|}{$(-\gamma, -\gamma)$} & \multicolumn{1}{c|}{$(-(\gamma + \eta), \rho)$} \\ \cline{2-4} \multicolumn{1}{r|}{$x_2(t) = 0$} & \multicolumn{1}{c|}{$(\rho, -(\gamma + \eta))$} & \multicolumn{1}{c|}{$(\rho, -(\gamma + \eta))$} & \multicolumn{1}{c|}{$(-(\gamma+\eta), -(\gamma + \eta))$} \\ \cline{2-4} \end{tabular}\vspace{-4mm} \end{table} \begin{theorem}\label{thm1} For the IoT game with $N$ players with action $x_i(t) \in \{0, \mathcal{R}\}$, payoff function $y_i(\boldsymbol{x}(t))$, and $|\boldsymbol{A}_i| = |\boldsymbol{A}|$ for all $i$, any vector of actions $\boldsymbol{x}(t)$ such that at most $R$ active devices with $F_i \geq \boldsymbol{A}_i(R)$ transmit, the rest of the devices do not transmit, and each of the RBs is used by at most one device is an NE. \end{theorem} \begin{proof} See Appendix \ref{app2}. \end{proof} \indent There are many sets of actions that satisfy the conditions described in Theorem \ref{thm1}, and, thus, NE in the IoT game is not unique. For instance, when the number of devices is equal to the number of RBs with $v_a = 1$ in an IoT, an NE is when each RB is used by one device, and, thus, the number of NEs in that particular IoT game is $N!$. There are many NEs, because the payoff of successful transmission does not depend on which RB is used. \emph{Although there are many NEs, the expected payoffs of devices at any given NE are the same, and, thus, one of those NEs is chosen with distributed RB allocation algorithm discussed in Section \ref{secsca}.} Similar to the simple IoT game in Table \ref{game1}, an NE for our IoT game implies that the number of transmitting devices $T_t$ is equal to the number of RBs $R$ and that a duplicate RB selection does not occur. Furthermore, at an NE, a transmitting device has one of the $R$ highest AoI, and a device that is not transmitting is inactive or has low AoI. This is because the payoff function with $|\boldsymbol{A}_i| = |\boldsymbol{A}|$ is designed to only allow the messages having the $R$ highest AoI to transmit. Therefore, the convergence of a distributed RB allocation algorithm to an NE reduces the average instantaneous AoI. However, when the devices only have partial information such that $|\boldsymbol{A}_i| < |\boldsymbol{A}|$, $\boldsymbol{x}(t)$ described in the Theorem \ref{thm1} is not necessarily an NE, because $\kappa$ is not necessarily equal to $R$.\\ \indent In addition to the NE, another solution concept is a socially optimal solution in which the overall payoff of an IoT game is maximized. In other words, a vector of actions is a socially optimal solution when the sum of payoffs of all devices is maximized. In an IoT game, a socially optimal solution is when the devices with highest future AoI $F_i$ fully utilize RBs without any duplicate RB selection. Therefore, similar to an NE in KPR game \cite{kolkata}, an NE in IoT game coincides with a socially optimal solution. A performance metric that can be used to describe an NE and a socially optimal solution is a service rate $s_r$, which is the percentage of RBs that are used by one device. NE in Theorem \ref{thm1} has a service rate of $1$, which implies that all RBs are used by one device, or the highest possible service rate of $\sfrac{T_t}{R}$.\\ \indent With the number of transmitting devices $T_t$ approximately equal to $R$ via IoT game design, a distributed RB allocation algorithm is necessary to enable the transmitting devices to share RBs autonomously. Moreover, with existence of a socially optimal NE in our IoT game, the convergence of a distributed RB allocation algorithm to an NE is crucial in minimizing the average instantaneous AoI. Therefore, to evaluate different RB allocation algorithms, the convergence to an NE and the service rates are analyzed. The service rate is an important metric to determine convergence to an NE, because a vector of actions must achieve service rate of $1$ or highest service rate to be an NE. Furthermore, the service rate is an important performance metric for the AoI, because the higher service rate implies that more devices are transmitting successfully at each time slot, reducing the average instantaneous AoI. Therefore, a distributed RB allocation algorithm must achieve a service rate of $1$ or increase the service rate as high as possible, because a high service rate is required to achieve a low average instantaneous AoI. \subsubsection{Stochastic Crowd Avoidance} \label{secsca We propose a stochastic crowd avoidance (SCA) algorithm that enables the devices to avoid using the RBs that are used by many devices stochastically and to choose an RB for a successful transmission, as shown in Algorithm 2. For the SCA algorithm, the devices need to share more information in addition to their $F_i$ and can perform a channel sensing to determine the RBs that were not used at a previous time slot \cite{aoibackoff, aoicsma, aoisleep}, and \cite{aoiinst}. At time slot $t$, the devices that transmitted at the time slot $t-1$ share their previous actions $x_i(t-1) \in \mathcal{R}$ and the previous payoff $y_i(\boldsymbol{x}(t-1))$ of their transmission. We let $\boldsymbol{X}_i$ be the vector of actions of the transmitting devices at time slot $t-1$ that a device $i$ knows and $\boldsymbol{P}_i$ be the vector of payoffs of the transmitting devices at time slot $t-1$ that a device $i$ knows. Furthermore, we let $\boldsymbol{X}_i(x)$ with $x \in \mathcal{R}$ be the number of $x$ in $\boldsymbol{X}_i$. In other words, $\boldsymbol{X}_i(x)$ is the number of devices that chose the RB $x$ at time slot $t-1$ that a device $i$ knows. Learning from $\boldsymbol{X}_i$ and $\boldsymbol{P}_i$, the proposed SCA algorithm enables a transmitting device $i$ at time slot $t$ to not use the RBs that are being used successfully by other devices and to avoid using the contended RBs stochastically.\\ \begin{algorithm}[t] \caption{SCA for device $i$ at time $t$.} \begin{algorithmic}[1]\label{distalg}\vspace{1mm} \item[1 :] \hspace{0.0cm} Receive $\boldsymbol{X}_i$, $\boldsymbol{P}_i$, $\boldsymbol{A}_i$, and $\mathcal{L}$. \item[2 :] \hspace{0.0cm} {\bf if} $x_i(t-1) \in \mathcal{R}$, $y_i(\boldsymbol{x}(t-1)) = \rho$, and $\alpha_i = 1$, \item[3 :] \hspace{0.3cm} $x_i(t) \leftarrow x_i(t-1)$. \item[4 :] \hspace{0.0cm} {\bf else if} $x_i(t-1) \in \mathcal{R}$, $y_i(\boldsymbol{x}(t-1)) = \rho$, and $\alpha_i = 0$, \item[5 :] \hspace{0.3cm} $j \leftarrow$ one neighboring device chosen with $\frac{F_j}{\sum_{F_h \in \boldsymbol{A}_i} F_h}$. \item[6 :] \hspace{0.3cm} $x_j(t) \leftarrow x_i(t-1)$. \item[7 :] \hspace{0.0cm} {\bf else if} $x_i(t-1) \in \mathcal{R}$ and $y_i(\boldsymbol{x}(t-1)) = -\gamma$, \item[8 :] \hspace{0.3cm} $z \leftarrow 1$ with probability $\boldsymbol{X}_i(x_i(t-1))^{-1}$. \item[9 :] \hspace{0.3cm} {\bf if} $z = 1$, $x_i(t) \leftarrow x_i(t-1)$. \item[10 :] \hspace{0.3cm} {\bf else} $x_i(t) \leftarrow$ randomly chosen from $\mathcal{L}$. {\bf end if}. \item[11 :] \hspace{0.0cm} {\bf else if} $x_i(t-1) = 0$, \item[12 :] \hspace{0.3cm} $x_i(t) \leftarrow$ randomly chosen from $\mathcal{L}$. \item[13 :] \hspace{0.0cm} {\bf end if.} \end{algorithmic \end{algorithm} \indent Using SCA algorithm, at time slot $t$, a transmitting device $i$ determines its RB usage based on $x_i(t-1)$ and $y_i(\boldsymbol{x}(t-1))$. If the transmission at time slot $t-1$ is successful such that $x_i(t-1) \in \mathcal{R}$ and $y_i(\boldsymbol{x}(t-1)) = \rho$, then transmitting device $i$ uses the same RB $x_i(t) = x_i(t-1)$. If the transmission at time slot $t-1$ is unsuccessful such that $x_i(t-1) \in \mathcal{R}$ and $y_i(\boldsymbol{x}(t-1)) = -\gamma$, then transmitting device $i$ uses the same RB $x_i(t) = x_i(t-1)$ with probability $\boldsymbol{X}_i(x_i(t-1))^{-1}$ or chooses an RB from a set $\mathcal{L}$ uniformly randomly. $\mathcal{L}$ is a set of the RBs that were not used by any of the device at time slot $t-1$ determined with channel sensing. If there is no transmission at time slot $t-1$ such that $x_i(t-1) = 0$, then the transmitting device $i$ chooses an RB from $\mathcal{L}$ uniformly randomly. In the case where $v_a < 1$, a device that transmitted successfully at time slot $t-1$ may no longer be active at time slot $t$. In this case, a device $i$ with $\alpha_i = 0$ and $y_i(\boldsymbol{x}(t-1)) = \rho$ chooses a neighboring device $j$ with $\alpha_j = 1$ with a probability proportional to $F_j$, such that the probability is $\sfrac{F_j}{\sum_{F_h \in \boldsymbol{A}_i} F_h}$.\\ \indent In our SCA algorithm, the RB that is used successfully at time slot $t-1$ is also used successfully at time slot $t$ if $v_a = 1$ or if there is an active neighboring device. Moreover, with $r_c$ sufficiently large, the expected number of transmitting devices using an RB that is used by more than one device at the previous time slot $t-1$ is $1$ at the current time slot $t$. This is because the probability of choosing the same RB after a transmission failure is $\sfrac{1}{\boldsymbol{X}_i(x_i(t-1))}$. The devices avoid to use the same RB stochastically even after a transmission failure, because the strict crowd avoidance causes the crowding in other RBs resulting in more transmission failures. Furthermore, when a device $i$ chooses some other RB such that $x_i(t) \neq x_i(t-1)$, device $i$ chooses from a set of RBs $\mathcal{L}$ that were not used at time slot $t-1$. This is to avoid using the RBs that are either used successfully or crowded, both of which cause the transmission failures. With SCA algorithm design to avoid duplicate RB selection, next we prove that the proposed SCA algorithm converges to an NE under certain IoT system parameters. \begin{theorem}\label{thm2} When $N$ devices are always active with full information and use $1$ out of $N$ RBs to transmit with negligible outage probability $p_{i,t}$ at each time slot, the vector of actions $\boldsymbol{x}(t)$ converges to an NE using SCA. \end{theorem} \begin{proof} See Appendix \ref{app3}. \end{proof} Under the conditions in Theorem \ref{thm2}, $\boldsymbol{x}(t)$ converges to an NE, and this implies that the service rate increases to $1$. In general, SCA algorithm increases the service rate, because an RB, which is used by $1$ device at previous time slot $t-1$, is still used by $1$ device at current time slot $t$. Therefore, SCA algorithm is effective in reducing the average instantaneous AoI. However, SCA is susceptible to the high outage probability $p_{i,t}$ based on the SNR. This is because SCA cannot distinguish the transmission failure due to the duplicate RB selection and the transmission failure due to the outage based on the SNR. Furthermore, with partial information $|\boldsymbol{A}_i| < |\boldsymbol{A}|$, the devices also have partial information of $\boldsymbol{X}_i$ and $\boldsymbol{P}_i$, and, thus, the devices cannot choose $x_i(t)$ accurately in the case of transmission failure.\\ \indent In a massive IoT with $N > R$ and partial information, the vector of actions $\boldsymbol{x}(t)$ does not converge to an NE using SCA, because it is not possible to achieve service rate of $1$. The service rate cannot be $1$, because the transmitting devices are changing every time slot and a duplicate RB selection is inevitable. Since the service rate cannot be $1$, the average instantaneous AoI in a massive IoT is higher than the average instantaneous AoI in an ideal IoT described in Theorem \ref{thm2}. However, in a massive IoT, the proposed SCA algorithm still enables the transmitting devices to stochastically avoid duplicate RB selection with available information. Therefore, the proposed SCA algorithm still increases the service rate and reduces the average instantaneous AoI. However, in that case, it does not reach an NE but rather a sub-optimal, heuristic solution. To evaluate performance of the proposed SCA algorithm, next we study a random RB selection for distributed RB allocation scheme. \subsubsection{Random RB Selection} One way for the transmitting devices to determine their RB usage is via random selection. In other words, the actions $x_i(t)$ of the transmitting devices are chosen uniformly random in $\mathcal{R}$. This random RB selection is used as a baseline. Even with $|\boldsymbol{A}_i| = |\boldsymbol{A}|$ for all $i$, the random RB selection is highly unlikely to achieve $\boldsymbol{x}(t)$ such that each of the RBs is used by at most one device, which is the requirement of $\boldsymbol{x}(t)$ to be an NE. Furthermore, the service rate $s_r$ using random RB selection for the transmitting devices is low. \begin{proposition} \normalfont At a time slot $t$, the service rate $s_r$ with $T_t$ transmitting devices using random RB selection is: \begin{equation} s_r = \frac{T_t}{R} \left(\frac{R-1}{R}\right)^{T_t - 1},\label{srr} \end{equation} and, for a massive IoT with $N$ increasing to infinity, the service rate $s_r$ is: \begin{equation} \lim_{N \rightarrow \infty} s_r = \frac{T_t}{R-1} \exp\left(\frac{-T_t}{R}\right) \label{srriot} \end{equation} \end{proposition} \begin{proof} See Appendix \ref{app4}. \end{proof} Under the conditions in Theorem \ref{thm2}, when $N$ devices are always active and use $1$ out of $N$ RBs, the number of transmitting devices $T_t$ is equal to $N$. In this case, the service rate using random RB selection is always less than $1$ even with $N = R \geq 2$. On the other hand, for a massive IoT with $N > R$, the service rate using random RB selection exponentially decreases to $0$ as $N$ increases. Therefore, the random RB selection is not suitable for a massive IoT in which the number of devices $N$ outnumbers the number of RBs $R$, Furthermore, with low service rate, the probability of a successful transmission is low for a device, and, thus, the average instantaneous AoI is high. \section{Simulation Results and Analysis} For our simulations, we consider a rectangular area with width $w$ and length $l$ within which the $N$ devices are deployed following a Poisson point process. We let $w = l = 10$ m and $R = 50$ with a $10$ MHz frequency band \cite{50rblte}, while the number of devices $N$ will be varied for analysis. We choose a time slot duration of $1$ ms \cite{1msts} and expected value of SNR of $20$ dB with $\lambda = .1$ and $\sigma^2 = 0.001$. To vary outage probability $p_{i,t}$, different values of $\epsilon$ are used. Moreover, a device is assumed to be of type $1$ with probability $0.6$ with $m_1 = 0.75$, while a device is assumed to be of type $2$ with probability $0.4$ with $m_2 = 0.75$. The average of the current AoI $C_i$ at the time slot of successful transmission is the performance metric for different RB allocation schemes, and their performances are analyzed with varying $v_a$ and $p_{i,t}$.\\ \indent For the centralized RB allocation scheme, the number of RACH preambles $P$ for the uplink transmission request is $64$ \cite{rach}. Three different kinds of priority scheduling are analyzed. Priority scheduling without learning \cite{aoischedule1, aoischedule3, multihop, adhoc} does not learn the device types, and, hence, this scheme is used for baseline comparison. The proposed priority scheduling with learning learns the device types using maximum likelihood and information on $F_i$. Priority scheduling with full information assumes that the BS always knows the types of all devices, and, hence, this scheme is used for optimal performance comparison. All three priority scheduling algorithms are analyzed with $N = 500$, while varying $v_a$ and $p_{i,t}$. \begin{figure}[t] \centering \includegraphics[width = 9cm]{cent_actprob.eps}\vspace{-.2cm} \caption{Average instantaneous AoI using centralized RB allocation schemes while varying $v_a$.}\vspace{-.5cm} \label{cpa} \end{figure} Fig. \ref{cpa} shows the average instantaneous AoI of the devices using centralized RB allocation schemes for different values of the activation probability $v_a$ with $p_{i,t} = 0.01$ and $\epsilon = 1$. The average instantaneous AoI for the no learning case quickly increases to $27.88$ and then increases slowly above $30$, while the average instantaneous AoI for both learning and full information quickly increases to $19.62$ and then increases slowly above $20$. As $v_a$ increases, the average instantaneous AoI increases for all priority scheduling algorithms, because more devices are transmitting and RACH preamble collisions are more likely to occur. However, for $v_a > 0.2$, the average instantaneous AoI flattens and increases at a much slower rate with increasing $v_a$ for all priority scheduling algorithms, because all RBs are fully saturated. Moreover, there is a significant difference between priority scheduling with learning and without learning. After the average instantaneous AoI flattens, the difference of the average instantaneous AoI between priority scheduling with learning and without learning is constantly about $8$. This implies that the proposed priority scheduling scheme with learning achieves about $26.7\%$ lower average instantaneous AoI when compared to simple priority scheduling scheme. Hence, learning the device types is important to decrease the average instantaneous AoI for priority scheduling. However, there is an insignificant difference between priority scheduling with learning and with full information, which implies that the learning is effective in learning the device types. \begin{figure}[t] \centering \includegraphics[width = 9cm]{cent_actprob_xp.eps}\vspace{-.2cm} \caption{Average instantaneous AoI using centralized RB allocation schemes with different transmit powers while varying $v_a$.}\vspace{-.5cm} \label{cpaxp} \end{figure} Fig. \ref{cpaxp} shows the average instantaneous AoI of the devices with different transmit powers using centralized RB allocation schemes for different values of the activation probability $v_a$ with $p_{i,t} = 0.01$ and $\epsilon = 1$. The devices have different transmit powers such that their SNR values are uniformly distributed random variables from $17.0$ dB to $21.8$ dB, and the only difference between Fig. \ref{cpa} and Fig. \ref{cpaxp} is assumption on the transmit powers of devices. The overall trends of the average instantaneous AoI for all three centralized RB allocation schemes are similar to the trends shown in Fig. \ref{cpa}. However, a notable difference is the average instantaneous AoI after the curves flatten. After the average instantaneous AoI flattens, the average instantaneous AoI increases slowly above $30$ for priority scheduling without learning, increases slowly to $25$ for priority scheduling with learning, and increases slowly to $23.5$ for priority scheduling with full information. With different SNR values randomly assigned to the devices, some devices have higher outage probability and other devices have lower outage probability compared to the devices in Fig. \ref{cpa}. With exponentially aging messages, an increase in the average instantaneous AoI from devices with higher outage probability outweighs a decrease in the average instantaneous AoI from devices with lower outage probability. Therefore, there is a slight increase in average instantaneous AoI when the devices have different transmit powers. However, similar to Fig. \ref{cpa}, the learning can still effectively decrease the average instantaneous AoI, and priority scheduling with learning performs similar to priority scheduling with full information even when the devices have different transmit powers. \begin{figure}[t] \centering \includegraphics[width = 9cm]{cent_eps.eps}\vspace{-.2cm} \caption{Average instantaneous AoI using centralized RB allocation schemes while varying $p_{i,t}$.}\vspace{-.5cm} \label{ceps} \end{figure} Fig. \ref{ceps} shows the average instantaneous AoI of the devices using centralized RB allocation schemes for different values of the SNR outage probability $p_{i,t}$ with $v_a = 0.2$ and varying $\epsilon$ from $1$ to $20$. Unlike in Fig. \ref{cpa}, the average instantaneous AoI does not flatten and increases at about the same rate. With $p_{i,t} = 0.02$, the average instantaneous AoI without learning is $24.34$, and the average instantaneous AoI with learning is $18.41$. With $p_{i,t} = 0.16$, the average instantaneous AoI without learning is $40.17$, and the average instantaneous AoI with learning is $27.45$. Therefore, the difference between the average instantaneous AoI with learning and without learning increases as $p_{i,t}$ increases. Furthermore, with high $p_{i,t}$, the proposed priority scheduling scheme with learning achieves about $31.7\%$ lower average instantaneous AoI when compared to simple priority scheduling scheme. For a higher $p_{i,t}$ and more frequent transmission failures, the AoI of the exponentially aging messages becomes much higher than the AoI of the linearly aging messages. In this case, the learning scheme, which enables the BS to accurately identify the messages aging faster, becomes more crucial in reducing the average instantaneous AoI. Furthermore, the difference between the average instantaneous AoI with learning and with full information also increases as $p_{i,t}$ increases. This is because it becomes increasingly difficult to learn the device types as $p_{i,t}$ increases.\\ \indent For the distributed RB allocation scheme, the communication range $r_c$ determines the information $\boldsymbol{A}_i$ that the devices have. For the given dimensions of the deployment area, $r_c \geq 15$ m is sufficiently large such that $|\boldsymbol{A}_i| = |\boldsymbol{A}|$ for any device $i$. SCA algorithm is compared against two algorithms, which are the random RB selection and the pre-determined RB selection. The pre-determined RB selection scheme \cite{kolkata} is known as the dictator's solution in the KPR game, and the RB usage for a device $i$ is pre-determined based on the rank of $F_i$. For instance, if $F_i$ is $\kappa$-th highest in $\boldsymbol{A}_i$ for $\kappa \leq R$, device $i$ uses a specific RB as previously agreed among IoT devices. The pre-determined RB allocation scheme requires full information $|\boldsymbol{A}_i| = |\boldsymbol{A}|$ for all $i$ and always achieves a service rate $s_r$ of $1$. While the pre-determined RB selection is used for optimal performance comparison, the random RB selection is used for baseline comparison. To analyze different distributed RB allocation schemes, the activation probability $v_a$, the SNR outage probability $p_{i,t}$, and the communication range $r_c$ are varied. In addition to the average instantaneous AoI, the service rate $s_r$ is evaluated for different distributed RB allocation schemes. \begin{figure}[t] \centering \includegraphics[width = 9cm]{dist_actprob.eps}\vspace{-.2cm} \caption{Average instantaneous AoI and service rate using distributed RB allocation schemes while varying $v_a$.}\vspace{-.5cm} \label{dpa} \end{figure} Fig. \ref{dpa} shows the average instantaneous AoI and the service rate of the devices using distributed RB allocation schemes for different values of the activation probability $v_a$ with $p_{i,t} = 0.01$, $\epsilon = 1$, $r_c = 10$ m, and $N = 200$. It is important to note that the expected number of newly active devices at a given time slot is $Nv_a$, and, thus, the number of active devices $N_t$ outnumbers the number of RBs $R$ for high values of $v_a$, simulating a massive IoT. Moreover, with $r_c = 10$ m, SCA only has partial information such that $|\boldsymbol{A}_i| < |\boldsymbol{A}|$ for all $i$. The service rate converges to $0.42$ for SCA with $v_a = 0.25$, $0.41$ for SCA with $v_a = 0.35$, $0.39$ for SCA with $v_a = 0.45$, and $0.35$ for random RB allocation with $v_a = 0.35$. As $v_a$ increases from $0.25$ to $0.45$, the average instantaneous AoI increases from $22.16$ to $38.82$ using SCA. As $N_t$ increases with increasing $v_a$, the transmission failure is more likely to occur due to the duplicate RB selection, because $R$ is fixed. Therefore, as $v_a$ increases, $s_r$ decreases, and the average instantaneous AoI increases. The pre-determined RB allocation scheme achieves a much lower average instantaneous AoI compared to SCA, because the pre-determined RB allocation scheme requires and uses the full information. Furthermore, the average instantaneous AoI with random RB allocation is multiple orders of magnitude higher than the average instantaneous AoI with SCA. Therefore, in a massive IoT with partial information, the proposed SCA algorithm is the most suitable algorithm to achieve low average instantaneous AoI as it balances between having full information and performing arbitrary allocations. \begin{figure}[t] \centering \includegraphics[width = 9cm]{dist_actprob_xp.eps}\vspace{-.2cm} \caption{Average instantaneous AoI and service rate using distributed RB allocation schemes with different transmit powers while varying $v_a$.}\vspace{-.5cm} \label{dpaxp} \end{figure} Fig. \ref{dpaxp} shows the average instantaneous AoI and the service rate of the devices with different transmit powers using distributed RB allocation schemes for different values of the activation probability $v_a$ with $p_{i,t} = 0.01$, $\epsilon = 1$, $r_c = 10$ m, and $N = 200$. The devices have different transmit powers such that their SNR values are uniformly distributed random variables from $17.0$ dB to $21.8$ dB, and the only difference between Fig. \ref{dpa} and Fig. \ref{dpaxp} is assumption on the transmit powers of devices. The difference in the service rates between Fig. \ref{dpa} and Fig. \ref{dpaxp} is insignificant. However, there is a notable increase in the average instantaneous AoI in Fig. \ref{dpaxp} compared to Fig. \ref{dpa}. Some devices have higher outage probability and other devices have lower outage probability, because the devices have different transmit powers. With an exponential aging function, an increase in the average instantaneous AoI with higher outage probability is more significant than a decrease in the average instantaneous AoI with lower outage probability. Therefore, similar to Fig. \ref{cpaxp}, there is a slight increase in the average instantaneous AoI when the devices have different transmit powers. Even when the devices have different transmit powers, the proposed SCA algorithm is still the most suitable algorithm to achieve low average instantaneous AoI in a massive IoT with partial information. \begin{figure}[t] \centering \includegraphics[width = 9cm]{dist_eps.eps}\vspace{-.2cm} \caption{Average instantaneous AoI and service rate using distributed RB allocation schemes while varying $p_{i,t}$.}\vspace{-.5cm} \label{deps} \end{figure} Fig. \ref{deps} shows the average instantaneous AoI and the service rate of the devices using distributed RB allocation schemes for different values of the SNR outage probability $p_{i,t}$ with $r_c = 10$ m, $v_a = 1$, $N = R = 50$, and varying $\epsilon$ from $1$ to $5$. It is important to note that the number of active devices $N_t$ is equal to $R$ with $N = R$ and $v_a = 1$, and this is the condition considered in Theorem \ref{thm2}. The service rate converges to $0.98$ for SCA with $p_{i,t} = 0.01$, $0.92$ for SCA with $p_{i,t} = 0.03$, $0.88$ for SCA with $p_{i,t} = 0.05$, and $0.37$ for random RB allocation. As $p_{i,t}$ increases from $0.01$ to $0.05$, the average instantaneous AoI increases from $1.25$ to $4.14$ using SCA, while the average instantaneous AoI increases from $5.73$ to $7.64$ using random RB allocation. With high $p_{i,t}$, the proposed SCA algorithm achieves about $45.8\%$ lower average instantaneous AoI when compared to random RB allocation. Since $T_t = N$ with $v_a = 1$ and $N = R$, the theoretical value of $s_r$ \eqref{srr} for random RB allocation case matches the simulated value of $s_r$ in Fig. \ref{deps}. As $p_{i,t}$ increases, the converged value of $s_r$ for SCA decreases, because the proposed SCA assumes that the transmission failures are caused by duplicate RB selection. Therefore, using SCA, a device $i$ stochastically avoids to use an RB even when there was no duplicate RB selection and the transmission failure is caused by SNR outage. Furthermore, the difference between the average instantaneous AoI using SCA and random RB allocation decreases as $p_{i,t}$ increases, because increasing $p_{i,t}$ has a more negative impact on SCA than on random RB allocation. However, it is important to note that SCA with low $p_{i,t}$ converges quickly to the service rate of $1$ with low $p_{i,t}$ as discussed in Theorem \ref{thm2}. \begin{figure}[t] \centering \includegraphics[width = 9cm]{dist_rc.eps}\vspace{-.2cm} \caption{Average instantaneous AoI and service rate using distributed Rb allocation schemes while varying $r_c$.}\vspace{-.5cm} \label{drc} \end{figure} Fig. \ref{drc} shows the average instantaneous AoI and the service rate of the devices using distributed RB allocation schemes for different values of the communication range $r_c$ with $p_{i,t} = 0.01$, $\epsilon = 1$, $v_a = 1$, and $N = R = 50$. The communication range $r_c$ determines the amount of information $\boldsymbol{A}_i$ that the devices have, and $r_c = 15$ m implies that the devices have full information $|\boldsymbol{A}_i| = |\boldsymbol{A}|$ for all $i$. The service rate converges to $0.981$ for SCA with $r_c = 15$ m, $0.978$ for SCA with $r_c = 10$ m, $0.967$ for SCA with $r_c = 5$ m, $0.939$ for SCA with $r_c = 1$ m, and $0.374$ for random RB allocation. As $r_c$ increases from $2$ m to $15$ m, the average instantaneous AoI decreases from $2.62$ to $1.21$ using SCA, while the average instantaneous AoI decreases from $7.19$ to $5.07$ using random RB allocation. With low $r_c$, the proposed SCA algorithm achieves about $63.6\%$ lower average instantaneous AoI when compared to random RB allocation. Similar to the Fig. \ref{deps}. the theoretical and simulated values of $s_r$ for random RB allocation are matched. As $r_c$ increases, the convergence value of $s_r$ for SCA increases, because the devices have more information $\boldsymbol{A}_i$ with higher $r_c$. As $r_c$ increases sufficiently such that $|\boldsymbol{A}_i| = |\boldsymbol{A}|$ for all $i$, the service rate converges to $1$ as discussed in Theorem \ref{thm2}. However, SCA with only partial information can still achieve $s_r$ close to $1$. Moreover, as $r_c$ increases, the average instantaneous AoI using SCA converges to the average instantaneous AoI using pre-determined RB allocation scheme.\\ \indent Next, the proposed centralized and distributed RB allocation schemes are compared in a massive IoT with $N > R$ and in an ideal IoT described in Theorem \ref{thm2}. To analyze different RB allocation schemes, the activation probability $v_a$ and the SNR outage probability $p_{i,t}$ are varied, \begin{figure}[t] \centering \includegraphics[width = 9cm]{cd_beta.eps}\vspace{-.2cm} \caption{Average instantaneous AoI using centralized and distributed RB allocation schemes while varying $\beta$ in a massive IoT.}\vspace{-.5cm} \label{beta} \end{figure} Fig. \ref{beta} shows the average instantaneous AoI of the devices using centralized and distributed RB allocation schemes for different values of $\beta$ with $p_{i,t} = 0.01$, $\epsilon = 1$, $r_c = 10$ m, $N = 100$, and $v_a = 1$. This simulates a massive IoT as the number of devices $N$ greatly outnumbers the number of RBs $R$. For the centralized RB allocation scheme, as $\beta$ increases, the average instantaneous AoI with learning decreases from $3.6$ to $3.13$, and the average instantaneous AoI with full information decreases from $3.34$ to $3.05$. However, the average instantaneous AoI without learning does not change significantly. With many type $2$ devices frequently transmitting exponentially aging messages, high values of $\beta$ can effectively reduce the average instantaneous AoI of type $2$ devices as BS learns the device types. However, without learning the device types, high values of $\beta$ are ineffective in reducing the average instantaneous AoI. For the distributed RB allocation scheme, as $\beta$ increases, the average instantaneous AoI with random selection decreases from $79.5$ to $25.1$, and the average instantaneous AoI with proposed SCA decreases from $13.4$ to $5.1$. This is because high values of $\beta$ enable the exponentially aging messages to be transmitted before their AoI increases greatly due to duplicate RB selection. However, the average instantaneous AoI with pre-determined selection does not change significantly, because most duplicate RB selection can be avoided with given $r_c$ and pre-determined selection. $\beta$ affects centralized and distributed RB selection schemes differently depending on other parameters of the IoT. \begin{figure}[t] \centering \includegraphics[width = 9cm]{cd_actprob.eps}\vspace{-.2cm} \caption{Average instantaneous AoI using centralized and distributed RB allocation schemes while varying $v_a$ in a massive IoT.}\vspace{-.5cm} \label{cdpa} \end{figure} Fig. \ref{cdpa} shows the average instantaneous AoI of the devices using centralized and distributed RB allocation schemes for different values of the activation probability $v_a$ with $p_{i,t} = 0.01$, $\epsilon = 1$, and $N = 200$. This simulates a massive IoT as the number of devices $N$ greatly outnumbers the number of RBs $R$. As $v_a$ increases, the average instantaneous AoI converges to $200$ for SCA with $r_c = 5$ m, $157$ for SCA with $r_c = 10$ m, and $145$ for SCA with $r_c = 15$ m. On the other hand, for priority scheduling, the average instantaneous AoI increases from $1.14$ to $6.03$ as $v_a$ increases from $0.1$ to $0.5$. With high $v_a$, the proposed SCA algorithm with $r_c = 15$ m achieves about $24$-fold higher average instantaneous AoI when compared to the proposed priority scheduling with learning. For almost any values of $v_a$, centralized RB allocation with priority scheduling performs much better than distributed RB allocation with SCA in terms of the average instantaneous AoI. However, centralized RB allocation scheme requires the BS to dictate the RB allocation for all devices, and, thus, centralized RB allocation scheme may not be viable for some of the IoT. Moreover, similar to Fig. \ref{cpa}, the average instantaneous AoI flattens after a certain value of $v_a$, because all RBs are fully saturated. There is a performance gap between SCA with different values of $r_c$, because $r_c$ is directly related to the amount of information that the devices have. With higher $r_c$ and more information for the devices, SCA is more effective in reducing the average instantaneous AoI. \begin{figure}[t] \centering \includegraphics[width = 9cm]{cd_eps.eps}\vspace{-.2cm} \caption{Average instantaneous AoI using centralized and distributed RB allocation schemes while varying $p_{i,t}$ in a massive IoT.}\vspace{-.5cm} \label{cdeps} \end{figure} Fig. \ref{cdeps} shows the average instantaneous AoI of the devices using centralized and distributed RB allocation schemes for different values of the SNR outage probability $p_{i,t}$ with $v_a = 0.5$, $N = 200$, and varying $\epsilon$ from $1$ to $20$. Similar to Fig. \ref{cdpa}, this simulates a massive IoT. When $p_{i,t} = 0.18$. the average instantaneous AoI is $585.59$ using SCA with $r_c = 5$ m, $529.94$ using SCA with $r_c = 10$ m, $472.81$ using SCA with $r_c = 15$ m, and $11.90$ using priority scheduling. With high $p_{i,t}$, the proposed SCA algorithm with $r_c = 15$ m achieves about $40$-fold higher average instantaneous AoI when compared to the proposed priority scheduling with learning. Similar to Fig. \ref{cdpa}, centralized RB allocation with priority scheduling performs much better than distributed RB allocation with SCA in terms of the average instantaneous AoI for all values of $p_{i,t}$. It is interesting to note that the difference in the average instantaneous AoI between SCA algorithms increases as $p_{i,t}$ increases. This implies that SCA with less information is more severely affected by increasing $p_{i,t}$ than SCA with more information. \begin{figure}[t] \centering \includegraphics[width = 9cm]{cd_epsid.eps}\vspace{-.2cm} \caption{Average instantaneous AoI using centralized and distributed RB allocation schemes while varying $p_{i,t}$ in an ideal IoT.}\vspace{-.5cm} \label{cdid} \end{figure} Fig. \ref{cdid} shows the average instantaneous AoI of the devices using centralized and distributed RB allocation schemes for different values of the SNR outage probability $p_{i,t}$ with $v_a = 1$, $N = R = 50$, and varying $\epsilon$ from $1$ to $20$. This simulates an ideal IoT for SCA as some of the conditions for NE convergence in Theorem \ref{thm2} are satisfied. When $p_{i,t} = 0.18$. the average instantaneous AoI is $25.53$ using SCA with $r_c = 5$ m, $19.96$ using SCA with $r_c = 10$ m, $17.27$ using SCA with $r_c = 15$ m, and $2.21$ using priority scheduling. With high $p_{i,t}$, the proposed SCA algorithm with $r_c = 15$ m achieves about $8$-fold higher average instantaneous AoI when compared to the proposed priority scheduling with learning. It is interesting to note that even in an ideal IoT for SCA, priority scheduling with learning performs better than SCA in terms of the average instantaneous AoI for most values of $p_{i,t}$. Moreover, similar to Fig. \ref{cdeps}, the difference in the average instantaneous AoI between SCA algorithms increases as $p_{i,t}$ increases.\\ \indent From our simulations, we observe that both priority scheduling and SCA are susceptible to high SNR outage probability $p_{i,t}$ as the average instantaneous AoI increases without flattening as $p_{i,t}$ increases. This is because the SNR outage probability is directly related to the transmission failures. However, the average instantaneous AoI increases slowly after a certain value of the activation probability $v_a$, because the RBs are fully saturated. Since increasing $v_a$ with fixed $N$ is equivalent to increasing $N$ with fixed $v_a$, the average instantaneous AoI also flattens for the case in which only the number of devices $N$ increases. Although centralized RB allocation scheme outperforms distributed RB allocation scheme in most cases, SCA can still achieve a high service rate $s_r$ and low average instantaneous AoI only with partial information. Furthermore, communication range $r_c$ and information availability are critical to the performance of SCA. \section{Conclusion} In this paper, we have proposed centralized and distributed approaches for allocating the limited communication resources based on the aging function and the current AoI of IoT devices. In the presence of both linear and exponential aging functions, we have shown that comparing the future AoI achieves a lower average instantaneous AoI at the BS than comparing the current AoI. For the centralized approach, we have introduced a priority scheduling scheme with learning, which enables the BS to allocate the limited RBs to the heterogeneous devices based on their future AoI. For the distributed approach, we have formulated the problem of autonomously allocating the limited RBs to the devices using game theory, and we have designed payoff functions to encourage the devices with high AoI to transmit, while discouraging the devices with low AoI to not transmit. Furthermore, we have proposed a novel SCA algorithm such that the heterogeneous devices can allocate the RBs in a self-organizing manner to avoid the duplicate RB selection and to minimize the AoI. We have proved the conditions that a vector of actions in the IoT game must satisfy to achieve an NE. Furthermore, we have proved that the actions of devices using our proposed SCA algorithm converge to an NE, if the devices have sufficient information under certain network parameters. Simulation results have shown that the average instantaneous AoI is an increasing function of the activation probability and the SNR outage probability. Moreover, the simulation results have shown that the service rate is an increasing function of the communication range and a decreasing function of the activation probability and the SNR outage probability. We have compared our centralized and distributed RB allocation schemes, and we have shown that our centralized RB allocation scheme outperforms our distributed RB allocation scheme in most cases. However, our proposed SCA algorithm has shown to be effective in reducing the AoI and increasing the service rate only with partial information. With high SNR outage probability, the proposed priority scheduling scheme with learning has shown to achieve about $31.7\%$ lower average instantaneous AoI when compared to simple priority scheduling scheme. Furthermore, with high SNR outage probability, the proposed SCA algorithm has shown to achieve about $45.8\%$ lower average instantaneous AoI when compared to random RB allocation. \section*{Acknowledgment} This research was supported by the U.S. Office of Naval Research (ONR) under Grant N00014-19-1-2621.
{'timestamp': '2021-01-05T02:21:24', 'yymm': '2101', 'arxiv_id': '2101.00543', 'language': 'en', 'url': 'https://arxiv.org/abs/2101.00543'}
arxiv
\section*{Disclaimer} \addcontentsline{toc}{section}{Disclaimer} The views expressed herein are those of the authors and do not reflect the position of the United States Military Academy, the Department of the Army, or the U.S. Department of Defense. \section{Introduction}\label{s.introduction} \IEEEPARstart{T}he System Usability Scale (SUS) has been employed for over 20 years as a reliable end-of-test subjective assessment tool to evaluate the perceived usability of a system \citep{brooke2013sus}. First introduced by \cite{brooke1996sus}, it has been used extensively in industry to provide valid and consistent design feedback for assessing the usability of human-machine systems, software, and websites \citep{peres2013validation}, as well as everyday products \citep{kortum2013usability}. Usability in these settings encompass a broader scope than ``ease of use'' or ``user friendliness'' \citep{ISO9241}, dimensions of usability that affect system technical acceptance by end users \citep{King2006}. Among the SUS's greatest strengths is the simplicity of its design. As seen in Table 1, the SUS is a Likert scale-based survey composed of ten questions with five levels of response used to elicit a user’s level of agreement concerning system characteristics. \begin{table}[ht] \begin{center} \begin{tabular}{| p{0.5cm} | m{10cm} |} \hline Q1 & I think that I would like to use this system frequently. \\ Q2 & I found the system unnecessarily complex. \\ Q3 & I thought the system was easy to use. \\ Q4 & I think that I would need the support of a technical person to be able to use this system. \\ Q5 & I found the various functions in this system were well integrated. \\ Q6 & I thought there was too much inconsistency in this system. \\ Q7 & I would imagine that most people would learn to use this system very quickly. \\ Q8 & I found the system very cumbersome to use. \\ Q9 & I felt very confident using the system. \\ Q10 & I needed to learn a lot of things before I could get going with this system. \\ \hline \end{tabular} \vspace{0.25cm} \caption{Standard SUS questions.} \textsuperscript{a}Respondents indicate their agreement with each statement from ``1 = Strongly Agree" to ``5 = Strongly Disagree." \label{sample-table} \end{center} \end{table} Post-survey analysis regarding individual SUS questions typically proceeds by treating responses as interval data and using appropriate parametric analysis \citep{likertexplored, boone2012analyzing, carifio2008resolving}. Of primary interest in systems analysis is the aggregate of each respondent's answers, dubbed a \textit{SUS score}. This SUS score estimates an individual's subjective judgment regarding the usability of a system. The SUS score is obtained by converting each question's response $x_{i} \in \{1, 2, 3, 4, 5\}$, for $i=1,\dots,10$, into a single value depending on whether the question was positively worded (the odd numbered questions): $(x_i - 1)$, or negatively worded (the even numbered questions): $(5 - x_i)$, and then multiplying the sum of these by 2.5, thus bounding a respondent's SUS score to the interval [0, 100] in increments of 2.5 units. The sample average of SUS scores across all $n$ SUS respondents yields a \textit{SUS study score}. The overall SUS results for a system are often reported as a single SUS study score \citep{koltringer2004comparing, lewis2018item, tullis2004comparison}, a SUS study score with a standard error \citep{everett2006measuring, kortum2015measuring, bangor2009determining}, or a standard confidence interval (CI) for the mean of the SUS study score constructed from a \textit{z} or \textit{t} statistic \citep{blavzica2015slovene, borsci2015assessing, orfanou2015perceived}. \begin{figure} \centering \includegraphics[width=1\linewidth]{tdist_sus_n20.png} \caption{SUS scores mapped to published usability scales, namely: acceptability ranges (from Figure 13 of Bangor et al. \citeyearpar[p.~592]{bangor2008empirical}), letter grades (from Table 8.5 of Sauro and Lewis \citeyearpar[p.~204]{sauro2016quantifying}), adjective ratings with 95\% CIs (derived from Table 3 of Bangor et al. \citeyearpar[p.~118]{bangor2009determining}), and score percentiles (from Table 8.4 of Sauro and Lewis \citeyearpar[p.~203]{sauro2016quantifying}).} \label{f:SUSscoreMapping1} \end{figure} In some applications, organizations establish specific descriptors associated with numerical results based on past experience with similar systems. When organizations map SUS study scores to pre-defined usability labels in this manner using acceptability ranges \citep{bangor2008empirical}, letter grades \citep{sauro2016quantifying}, adjective ratings \citep{bangor2009determining}, or score percentiles \citep{sauro2016quantifying}, SUS study scores can be communicated to project managers and acquisition officials in an intuitive and actionable way. Figure~\ref{f:SUSscoreMapping1} shows an example mapping of SUS scores to all four of the noted usability labels. Here, all four mappings are shown for convenience in exposition as typically an organization would adopt only one for their use. Mapping the CI bounds of the SUS study score to usability labels adds further insights into survey results by portraying underlying uncertainty associated with SUS study results. When the CI for the SUS study score is mostly contained in a single usability label's interval, sufficient evidence supports the usability characterization associated with that label. For example, Figure~\ref{f:SUSscoreMapping1} SUS results support the associated system's usability being labeled as nearly 100\% acceptable with little data in the category labeled `Marginal'. On the other hand, CIs that cross interval bounds can complicate one's usability interpretation. Returning to Figure~\ref{f:SUSscoreMapping1}, mapping the same CI to letter grades indicates that the system's usability ranges between a high C and low A, adjective ratings indicate the results existing mostly in the category labeled `Good' with high side spillover into `Excellent', and Score Percentiles are concentrated between roughly 50 and 90\% when compared to previously evaluated similar systems. One can see from this example that tighter CIs are more desirable when SUS results are used in this context because they narrow the range of mapped SUS score interpretations. The SUS has undergone extensive psychometric evaluation since its introduction, consistently demonstrating its reliability \citep{Lucey1991,bangor2008empirical,lewissauro2009,sauro2016quantifying} and content validity \citep{finstad2010, lewisplus2013}. Moreover, these favorable characteristics appear to persist despite language translations \citep{dianat2014psychometric, blavzica2015slovene, katsanos2012perceived}, using English language versions with non-native English speakers \citep{finstad2006}, modifications that use an all-positive version of the survey \citep{sauro2011designing}, as well as removing a single test item from the questionnaire \citep{lewis2017can} if deemed inappropriate for use with the system at-hand. In this last instance, practitioners must adjust the multiplier from 2.5 to 2.78 to accommodate the reduction in test items from 10 to 9. SUS scores have been shown to be sensitive to types of interfaces and changes to a product \citep{bangor2008empirical}, the task order used for assessment \citep{tullis2004comparison}, user experience \citep{kortum2013usability, mclellan2012effect}, and differences in user age but not gender \citep{bangor2008empirical}. Moreover, the SUS has been evaluated for efficacy against other known methods for testing usability such as the Computer System Usability Questionnaire (CSUQ) and the Usability Metric for User Experience (UMUX) \citep{lewis2018measuring, tullis2004comparison, borsci2015assessing}. Interest in capturing, confirming, and expounding on SUS utility through research continues to grow. Brooke's \citeyearpar{brooke1996sus} seminal article on the SUS reported 8,948 Google Scholar citations as of 20 May 2020, a gain of 3,284 since reported by \cite{lewis2018past} two years earlier. While the vast majority of research efforts have focused on validating the SUS as a sound methodology and leveraging its normative data to evaluate system usability, there remains opportunity to improve the analysis and reporting of SUS study scores when practitioners are faced with very small sample ($n \leq 10$) and extremely small sample ($n \leq 6$) circumstances. In practice, this most often happens when cost constraints, security considerations, system operational complexity, or the limited availability of users with highly specialized skills impose on the system assessment process \citep{chen1995}. When the system under assessment represents a capability gap-filling, new technology prototype, it tends to also receive more enthusiastically positive responses from users who quickly comprehend the system's potential to solve or partially-solve nagging operational deficiencies. This effect, along with its counterpart, introduces skewness in the data that further complicates statistical methods. The challenge is exacerbated still when assumptions regarding the continuity of the underlying distribution are not appropriate. In this context, we have two concerns. Firstly, the distribution of historical SUS study scores is skewed \citep{bangor2008empirical, sauro2016quantifying}, violating symmetry assumptions that call into question methods relying on the central limit theorem (CLT) when the sample size is small. Historically, SUS study scores across all usability studies \textcolor{black}{analyzed for this paper} have an average skewness of about -0.4 \citep{lewis2009factor}, as given in \cite{sauro2016quantifying}. Data from \cite{bangor2008empirical} demonstrate that for a \textcolor{black}{single} study, this skewness can range from highly negative to highly positive. \textcolor{black}{One logical explanation for this characteristic is that} by the time users engage with system prototypes, features are refined to a point that a majority of users will find the system under investigation to be reasonably simple to use. Secondly, SUS study scores are bounded to the interval $[0, 100]$ in discrete increments of 2.5. Therefore, a system perceived as highly usable will tend to produce SUS scores closer to the upper bound. The theory allowing practitioners to use standard methods for constructing confidence intervals relies on asymptotics that manifest slowly when skewness is present, a condition exacerbated when skewness is high. The resulting negative skewness in SUS studies causes the upper bounds of CIs to violate the parameter space of the scoring interval in small sample studies where higher levels of variability are expected. Figure~\ref{f:SUSscoreBoundViolation1} shows an example of this for a SUS study with 6 participants, where 4 of the 6 SUS scores were near the upper bound of 100, yielding a sample skewness of -0.9. \begin{figure}[h] \centering \includegraphics[width=1\linewidth]{tdist_sus_n6.png} \caption{Upper CI bound for the mean SUS score violating the upper bound of the parameter space.} \label{f:SUSscoreBoundViolation1} \end{figure} From a practical perspective, if small sample SUS studies were uncommon, the concerns identified would be real but somewhat irrelevant. This is not the case. In particular, determining the usability of highly complicated or complex systems tends to be restricted to small sample sizes, mainly due to limited accessibility to these systems and cost considerations involving highly specialized test subjects. As some datasets suggest (e.g., \cite{bangor2008empirical}), very small and extremely small SUS studies are effectively the rule rather than the exception, and in such situations, reporting a standard error or using traditional confidence intervals neglects potential statistical issues that exist in the data. Ultimately, the method of CI construction should generate narrow confidence intervals with nominal coverage of the underlying population mean. In this paper, the impact of very small sample ($n \leq 10$) SUS study results are examined with specific focus on achieving desirable characteristics for a reported SUS study confidence interval, and the accessibility of potential SUS study scores given the discrete nature of the underlying survey scale for individual responses. The results are intended to assist usability professionals in increasing the accuracy and validity of their SUS results when faced with a very small number of SUS respondents. In Section~\ref{s:methods}, two alternatives to the common practice of using \textit{t} distribution-based confidence intervals for small sample SUS study scores are examined to assess their efficacy towards achieving the previously stated desirable characteristics. Section~\ref{s:simulation_study} applies these alternative approaches to a repository of data from actual SUS studies used with permission from the owners. Results demonstrate achievable improvements in reporting accuracy regarding SUS study results. In Section~\ref{s:app}, a publicly available, custom R-based application that implements the three major computational approaches presented in this paper is described. This application is intended to enable practitioners to leverage the recommendations provided herein in an efficient manner. Section~\ref{s:conclusions} summarizes this paper's major results and recommendations along with potential future opportunities. \section{Methods for Quantifying Uncertainty}\label{s:methods} Generally speaking, the CLT states that the distribution of the sample mean approximates a normal distribution as the sample size becomes large, regardless of the shape of the population's distribution. Oftentimes, sample sizes greater than 30 are considered sufficient for the CLT to hold. In such cases, a CI that reflects a range of plausible values for the population mean ($\mu$) can be calculated using the standard expression: \[{\bar{x}} \pm z_{{{\alpha}/2}} \frac{s}{\sqrt{n}}\] \noindent where ${\bar{x}}$ is the sample mean, $z_{{\alpha}/2}$ is the critical value from the standard normal distribution evaluated at ${\alpha}/2$ when $1-{\alpha}$ is the confidence level, $s$ is the sample standard deviation, and $n$ is the sample size. For the reasons mentioned earlier, the distribution of the sample mean $\bar{X}$ is likely not symmetric for small samples. To demonstrate this, assume that the underlying distribution of SUS scores follows Azzalini's \citeyearpar{azzalini2005skew} skew-normal distribution with a population mean ($\mu$), standard deviation ($\sigma$), and skewness ($\lambda_3$) of 65, 20, and -0.4, respectively. Due to the upper truncation of the distribution at 100, these correspond to $\mu = 63$, $\sigma = 19$, and $\lambda_3 = -0.45$, which closely mirror the values reported in Lewis and Sauro \citeyearpar{lewis2009factor}. To visualize the distribution of the sample mean when $n=5$, 100,000 random samples from this skew-normal parent distribution were generated with realizations rounded to the nearest 2.5 to match the domain of observable SUS scores. As seen in the blue density plot shown in Figure~\ref{fig:simmeans}, the sample mode sits to the right of the sample mean and the skewness of $\bar{X}$ is approximately -0.22. Moreover, as the population mean gets closer to the SUS score's upper bound, the magnitude of $\bar{X}$'s skewness increases. For instance, if the mean shifts to 81, the skewness of $\bar{X}$ becomes roughly -0.38, which is noticeable in Figure~\ref{fig:simmeans}'s red density plot. While rules of thumb suggest that skewness values between -1 and 1 are acceptable, normal-based confidence intervals often fail to achieve nominal coverage within this range. \begin{figure} \centering \includegraphics[width=0.8\linewidth]{Figure_3_400dpi.png} \caption{Density plots of the sample means from 100,000 samples of size $n=5$ from skew-normal distributions.} \label{fig:simmeans} \end{figure} To understand why the CLT may be inadequate for very small sample SUS studies, it is beneficial to consider the Edgeworth expansion for the studentized sample mean: $n^{1/2} \frac{(\bar{X}-\mu)}{\sigma}$. As given in \cite{hall2013bootstrap}, the probability density function (PDF) of this statistic can be expressed by: \begin{equation} f(x) = \phi(x)-\frac{1}{\sqrt{n}}\frac{\lambda_3}{6}\phi ^{(3)}(x) + O(n^{-1})\label{eq:edgeworth} \end{equation} \noindent where $\phi^{(i)}(x)$ is the $i$th derivative of the standard normal distribution and $\lambda_3$ is the third central moment (i.e., skewness) over the standard deviation cubed. Therefore, with skewness present the distribution of the sample mean approaches a standard normal at a rate of $n^{-1/2}$, whereas in the absence of skewness it approaches a standard normal at a rate of at most $n^{-1}$. Practically, this means that if $n$ is small (i.e., few respondents participating in a SUS study), the distribution of the sample mean should still have some amount of skewness present. When sample sizes are small, the standard normal distribution is often replaced with the Student's \textit{t} distribution to generate the critical value to construct the CI: \[{\bar{x}} \pm t_{{{\alpha}/2,n-1}} \frac{s}{\sqrt{n}}\] \noindent where $t_{{{\alpha}/2,n-1}}$ corresponds to the $\alpha/2$ quantile from a $t$ distribution with $n-1$ degrees of freedom. In such situations, a symmetric CI such as one formed using the \textit{t} distribution, may be inappropriate, with this condition becoming exacerbated as $n$ approaches one. On the other hand, when $n$ is large, the $\frac{1}{\sqrt{n}}$ term in \eqref{eq:edgeworth} goes to zero, meaning the distribution of the sample mean becomes symmetric. \subsection{Options for Confidence Interval Formulation}\label{ss.options} Despite the lack of evidence supporting a CLT assumption for small sample data, it does not necessarily mean that using the CLT is categorically bad or always inappropriate in such cases. Several researchers have proposed modifications to the $t$ distribution approach when sample sizes are as small as 13 \citep{johnson1978, sutton1993}, although as researchers note, results can be quite inaccurate. And, although the \textit{t} distribution has nice coverage properties, it is not guaranteed to obey the parameter space. For example, consider the case when $n = 5$. Suppose that among the five SUS responses, three respondents find the product exceptional, and two rate it as good, resulting in potential SUS scores of \njc{97.5, 97.5, 97.5, 80, and 80}. In this case, the 95\% CI formed by using a \textit{t} distribution is \njc{(78.5, 102.4)}, which is nonsensical as $\mu$ cannot be greater than 100. As described earlier, this occurs because using the \textit{t} distribution assumes that the distribution of $\bar{X}$ is symmetric, and when $n$ is small this is not guaranteed to be true. \textcolor{black}{While it is tempting to truncate the above CI to (78.5, 100), the result is no longer a valid 95\% confidence interval. In general, a confidence interval of a parameter, $\mu$, is of level $1-\alpha$ if $P(L(X)<\mu<U(X))=1-\alpha$ \citep{casella2002statistical}. Using the \textit{t} distribution in the above example yields a 95\% CI with $L(x) = 78.5$ and $U(x) =102.4$. Inherent to this construction is the belief that $P(\bar{X} \in (100,102.4)|\mu)>0$, and in this case, the confidence interval calculation used implies $P(\bar{X} \in (100,102.4)|\mu)\approx 0.045$. Simply truncating the interval at 100 renders the probability that $\bar{X}$ is above 100 to be zero, resulting in a confidence interval with less than its nominal coverage \citep{agresti1998approximate}, perhaps significantly \citep{mandelkern2002setting}. Under these conditions, a practitioner should not be comfortable reporting results at the nominal level. In order to guarantee a 95\% confidence interval in this instance, the lower bound must be shifted left to account for the missing 4.5\% probability. In other words, a properly constructed CI requires a $L_{\mbox{shifted}}(X)$ such that $P(L_{\mbox{shifted}}(X)<\mu<100)=1-\alpha$. In the above example, this would result in an interval of (70, 100). Depending on the adjective label intervals being used, the usability of a system might easily be considered marginal instead of acceptable.} \textcolor{black}{An additional detractor to a truncating approach is that the distribution for $\bar{X}$ is no longer valid. To fix this, one might abandon the belief that $\bar{X}$ follows a non-central \textit{t} distribution and instead assume that it follows a truncated \textit{t} distribution, and hence formulate a one-sided confidence interval. While explorations involving the truncated \textit{t} distribution are beyond the scope of this paper, preliminary simulations suggest that using this distribution may have benefits. Additional alternate ways to form a confidence interval on a bounded parameter space are given in Wu and Neale \citeyearpar{wu2012adjusted}, Bebu and Mathew \citeyearpar{bebu2009confidence}, and Andrews \citeyearpar{andrews1999estimation}.} In sum, while the \textit{t} distribution may validly address some issues with small samples, it fails to account for bounds on the underlying sample space for $\mu$ in SUS applications, and it does not account for potential skewness in the distribution of the sample mean. As demonstrated in Section~\ref{s:simulation_study} that follows, many SUS studies limited to small sample sizes encounter this issue \citep{bangor2008empirical}. Fortunately, two alternatives offer relief: an expanded version of the bias-corrected accelerated bootstrap approach \citep{efron1987better} and uncertainty bounds created using a Bayesian credible interval. \subsection{CIs Built Using the Expanded Bias-Corrected Accelerated Bootstrap}\label{ss.expandedBCa} In general, bootstrap methods are empirical statistical sampling approaches used to estimate characteristics of unknown distributions when faced with small sample sizes or inappropriate use of parametric assumptions. In parametric bootstrap methods, random samples are generated from a parametric model fit to the data. In non-parametric resampling, bootstrap samples are constructed using resampling with replacement from the original sample \citep{EfronTib1986, Kysely2010}. Given the limitations noted earlier, a non-parametric random sampling approach is warranted for this exploration \citep{diciccio1988, Flowers2018}. In comparison to the detractors present in a \textit{t} distribution approach noted earlier, a percentile bootstrap CI for the population mean ($\mu$) is simple to form, easy to understand, and guaranteed to obey bounds on a parameter space. It uses the ${100({\alpha/2})}$ and the ${100(1-{\alpha/2})}$ percentiles of the bootstrap distribution as its bounds, where ${\alpha}$ is the likelihood that $\mu$ lies outside of the CI. For example, to construct a 95\% CI using the percentile bootstrap method, ${\alpha} = 0.05$, and the CI would be constructed using the 2.5 and 97.5 percentiles of the bootstrap distribution. To generate sufficient realizations of a SUS sample mean, the percentile bootstrap CI for $\mu$ resamples from SUS score data with replacement $B$ times to form $B$ bootstrap samples. At each iteration, the sample mean is calculated for each bootstrap sample. Taken together, these $B$ realizations of the sample mean approximate a sampling distribution for the population mean by ordering them from smallest to largest such that: \[{\hat{\theta^*}_{(1)}} \leq {\hat{\theta^*}_{(2)}} \leq {\hat{\theta^*}_{(3)}} \leq ... \leq {\hat{\theta^*}_{(B)}},\] where ${\hat{\theta^*}_{(i)}}$ represents $i^{th}$ smallest sample mean for $i= 1, 2, \ldots, B$. Using this approach, the corresponding 95\% confidence interval for the population mean is given by: \[[{\hat{\theta^*}_{(0.025B)}},{\hat{\theta^*}_{(0.975B)}}].\] \noindent As an illustration, consider the small SUS score dataset introduced earlier, namely \{97.5, 97.5, 97.5, 80, 80\}, and set $B = 1,000$. The percentile bootstrap with $B = 1,000$ resamples 1,000 datasets with $n = 5$, subsequently calculating the sample mean for each dataset. With resampling with replacement, it is possible to obtain bootstrap samples with many repeated values, such as \{80, 80, 80, 80, 80\}, which would result in a mean of 80. Once resampling is complete and 1,000 sample means are calculated, the 2.5\textsuperscript{th} and 97.5\textsuperscript{th} smallest values would be extracted and used as the 95\% confidence interval's lower and upper bounds, respectively. To account for potential skewness in data, \cite{efron1987better} introduced a bias-corrected and accelerated (BCa) bootstrap methodology for both parametric and nonparametric situations, improving an earlier percentile method \citep{efron1981}. Similar to confidence intervals constructed using the percentile bootstrap method, bias-corrected and accelerated (BCa) bootstrap CIs are formed using percentiles of the bootstrap distribution. However, unlike the percentile bootstrap method, the choice of which percentiles to use is more complicated and requires one to calculate two additional factors: a bias correction factor $b$ and an acceleration factor $a$. The bias correction factor $b$ is calculated as $b=\Phi^{-1}(p)$, where $\Phi$ is the cumulative distribution function of a standard normal random variable and $p$ is the proportion of bootstrap samples less than the average. This factor estimates the difference between the median of the bootstrap distribution and $\bar{X}$. Clearly, if there is no skew to the sampling distribution of $\bar{X}$, this bias correction factor will be zero on average. The acceleration factor $a$ is obtained by jackknife resampling of the $n$ original data to estimate the second term in \eqref{eq:edgeworth} using the following relation: \begin{equation} a= \frac{1}{\sqrt{n}}\frac{\lambda_3}{6}\phi ^{(3)}(x). \end{equation} \noindent This involves generating $B$ replicates of the original sample. The first jackknife sample leaves out the first value of the original sample, the second by leaving out the second value, and so on until $B$ samples of size $(n-1)$ are obtained \citep{Carpenter2000}. Once this term is estimated, both the bias correction and the acceleration terms can be used to make a bootstrap estimate that converges at a rate of $O(n^{-1})$ rather than $O(n^{-1/2})$ as shown in \cite{hall2013bootstrap}. Although the BCa bootstrap method is an improvement over the percentile bootstrap technique, the CIs produced by the BCa bootstrap method tend to be too narrow for small samples and may fail to achieve their nominal coverage probability. In other words, when the sample size is small, BCa bootstrap CIs may not cover their parameters' true values as often as they claim to. One approach to addressing this issue is given in \cite{hesterberg2015teachers} and adopted herein, which is similar to using a \textit{t} distribution instead of the CLT-based normal distribution to form traditional CIs. Using a \textit{t} distribution instead of a normal distribution is the same as multiplying the length of a CI by $\displaystyle (s \times t_{\alpha/2,n-1})/(\hat{\sigma} \times z_{\alpha/2})$. If the underlying distribution is not normally distributed, applying this correction is not theoretically sound, but it is a commonly used correction factor in practice. This same approach can be applied to bootstrap CIs in a straightforward manner, most easily explained using the percentile bootstrap as an example. The percentile bootstrap uses the $100(\alpha/2)$ and the $100(1-\alpha/2)$ highest values from the bootstrap sample to form a $100(1-\alpha)\%$ CI. The expanded percentile bootstrap sets $\alpha'/2= \Phi (-\sqrt{\frac{n}{(n-1)}} t_{\alpha/2,n-1})$, where $\Phi$ is the standard normal CDF and $t_{\alpha/2,n-1}$ is the critical value found from the t distribution. The expanded bootstrap then uses the $100(\alpha'/2)$ and the $100(1-\alpha'/2)$ values from the bootstrap sample. This expansion can also be easily applied to the BCa bootstrap using the \texttt{resample} library \citep{resample} within the statistical software R. \njc{When applied to the example dataset introduced earlier: \{97.5, 97.5, 97.5, 80, 80\}, the expanded BCa bootstrap yields an interval of (80, 97.5) and thereby supporting the conclusion that the system's usability is acceptable.} Additionally, Figure~\ref{f:SUSscoreBCa} illustrates a 95\% expanded BCa bootstrap CI for the same SUS study highlighted in Figure~\ref{f:SUSscoreBoundViolation1}. \begin{figure} \centering \includegraphics[width=1\linewidth]{BCa_sus_n6.png} \caption{95\% expanded BCa bootstrap CI for the mean SUS score of the survey highlighted in Figure~\ref{f:SUSscoreBoundViolation1}.} \label{f:SUSscoreBCa} \end{figure} Comparing the \textit{t} distribution CI in Figure~\ref{f:SUSscoreBoundViolation1} to the expanded BCa bootstrap CI in Figure~\ref{f:SUSscoreBCa} reveals two important differences. First, unlike the upper bound of the CI derived from the \textit{t} distribution (106.16), the upper bound of the BCa bootstrap CI (97.50) abides the parameter space of the SUS score. In essence, a CI represents a plausible range of values for a parameter of interest. CIs that exclusively cover the feasible values for this parameter should be preferred. In the case of mean SUS scores, values below 0 or above 100 are not realizable, and hence not feasible. Additionally, the width of the expanded BCa bootstrap CI (51.67) is slightly narrower than the \textit{t} distribution CI (53.99). In general, when choosing between multiple valid CIs, the narrowest interval is preferred, assuming that the CI's construction method preserves the nominal coverage probability. While in this instance the practical conclusions would not change if an analyst selected the expanded BCa CI over the \textit{t} distribution CI, in some instances they would. For example, consider the small dataset presented earlier (i.e., \{97.5, 97.5, 97.5, 80, 80\}). After proper truncation the adjusted lower bound of the \textit{t} distribution CI would lead a practitioner to conclude that the system's usability is unacceptable, whereas the expanded BCa CI would not. The above discussion indicates the expanded BCa bootstrap CI is the better option for this small sample SUS study, and Section \ref{s:simulation_study} investigates the generalizability of these results using simulation. However, before moving on, there is a final, more subtle point worth mentioning. When confronted with small samples, using the \textit{t} distribution assumes the distribution of the underlying data is normally distributed or at least reasonably symmetric and continuous. As noted earlier, SUS scores often lack symmetry; case in point, the sample skewness of the SUS scores in Figure~\ref{f:SUSscoreBoundViolation1} is -0.9. Moreover, while SUS scores are clearly discrete, leading SUS literature currently suggests the sampling distribution of the mean SUS score is effectively continuous, stating ``the combination of average SUS scores for a study is virtually infinite” \citep[p. 202]{sauro2016quantifying}. Figure~\ref{f:DistinctSUSMeans} suggests otherwise, especially for small \textit{n}. \begin{figure}[h] \centering \includegraphics[width=0.6\linewidth]{distinct_SUS_means_v4.png} \caption{Possible mean SUS scores for samples of size \textit{n}, where \textit{c} is the number SUS score combinations of size \textit{n} and \textit{m} is the number of distinct mean SUS scores.} \label{f:DistinctSUSMeans} \end{figure} As seen in Figure~\ref{f:DistinctSUSMeans}, when $n=6$ over 9 million SUS score combinations are possible, but there are only 241 distinct SUS means available. Increasing the sample size to $n=10$ produces more than 10 billion SUS score combinations. However, these combinations yield a mere 401 distinct SUS means. This is far from infinite, and the counter-intuitive result is a function of the SUS scores' special structure. Specifically, prior to scaling an individual SUS score by 2.5, the 41 possible scores are $S=\{0,1,2,...,40\}$, which can be rewritten as $S=\{s+id:i=0,1,...,k-1\}$ with $s=0$, $d=1$, and $k=41$. With $s \in S$ and $d \geq 1$, $S$ is a 41-term arithmetic progression. Leveraging a result from number theory, the mean SUS score for a sample of size \textit{n} is simply an n-fold \textit{sumset} of $S$ (scaled by $2.5/n$), and when $n \geq 2$ this sumset's cardinality is $41n-(n-1)$ \citep[p. 335]{mistri2014generalization}. Each time the sample size increases 1, the number of distinct SUS means increases by 40. When \textit{n} is small, these means are sparsely distributed along the real line between 0 and 100. Accordingly, treating the SUS mean as continuous and using a CI construction method that relies on this continuity, such as the \textit{t} distribution, appears ill-advised. This sentiment is reinforced in recent literature, notably \citet{liddell2018analyzing}. Fortunately, the expanded BCa bootstrap CI accommodates discrete data and provides a defensible alternative CI construction both in theory and practice. \subsection{Credible Intervals Constructed Using an Empirical Bayesian Approach}\label{ss.empiricalBayes} Although the expanded BCa bootstrap method is an attractive option as it obeys the parameter space for $\mu$, it does ignore any preconceived belief or historical evidence regarding a given system's mean SUS score. For example, it fails to account for the extremely low probability that the population mean is 0 or 100. Furthermore, as we show in Section~\ref{s:simulation_study}, when $n$ is less than 5, CIs formed using even the expanded BCa bootstrap method do not cover the true mean as often as they purport to do. Bayesian inference offers an approach that both takes advantage of prior information and properly facilitates inference when $n$ is extremely small by relying on prior beliefs to inform posterior probabilities regarding a parameter of interest. While in some cases this might appear superfluous, historical SUS scores can meaningfully inform inference regarding sample means. Notably, \cite{bangor2008empirical} demonstrated that for 206 usability studies using the SUS, there was never a mean SUS score below 30 or one above 95. Moreover, their data would suggest a prior distribution (density) regarding the true SUS score mean $\pi(\mu)$ similar to the empirical density denoted by the blue line in Figure~\ref{fig:prior}, created by assuming $\bar{X}$ follows a truncated normal distribution and matching moments. This yields a truncated normal distribution with mean 70 and standard deviation 12 as indicated by the thick pink line in Figure~\ref{fig:prior}. This choice appears to align with the empirical distribution of $\bar{X}$ fairly well, as does a non-truncated normal distribution with mean of 70 and standard deviation of 12. Thus, as can be seen in Figure~\ref{fig:prior}, although the truncated normal prior distribution is theoretically sound, including truncation in the model to construct a prior density on $\mu$ increases the model's complexity without substantively improving the results. The largest difference between the two exists in the region above 100, and this is only 0.007\% of the data. Lest this appear contradictory to earlier evidence against relying on the CLT, the concern here is on a prior distribution of $\mu$ rather than a sampling distribution of $\bar{X}$. \begin{figure}[!t] \centering \includegraphics[width=0.65\linewidth]{SampleMeansPriors.png} \caption{Two choices of priors for $\mu$ overlayed on top of the empirical distribution.} \label{fig:prior} \end{figure} The marginal posterior distribution for $\mu$ given the data from any given usability assessment can be estimated by appealing to Bayes theorem as follows: \begin{align} \pi(\boldsymbol{\mu},\sigma | \textbf{y}) &\propto \prod_{i,j} f(y_{i,j}|\mu_i,\sigma) \pi(\mu_i)\pi(\sigma) \label{eq:Gen Bayes}. \end{align} Here $f(y_{i,j})$ is the likelihood function for observation $j$ within test $i$ assuming a truncated Normal distribution. Letting $\pi(\mu_i)$ denote the prior distribution of the true average score of test $i$, $\pi(\mu_i)$ can be determined from the data in Bangor et al. \citeyearpar{bangor2008empirical}. Similarly, letting $\pi(\sigma)$ denote the prior distribution for the population standard deviation, which is assumed to be Uniform(0,30) as it is highly unlikely that the standard deviation is greater than 30. The joint posterior distribution for $\mu$ and $\sigma$, $\pi(\boldsymbol{\mu},\sigma | \textbf{y})$, can then be used to find credible intervals for either both parameters, or by integrating out $\sigma$, a marginal posterior distribution for $\mu$. Typically, \eqref{eq:Gen Bayes} is too complex to evaluate directly without the use of specialized software such as Stan \citep{stan2019}, which relies on Markov Chain Monte Carlo (MCMC) techniques to simulate from the posterior distributions. Practically, an empirical Bayesian approach prevents reporting values for CI or credible interval bounds on $\mu$ that are unrealistic. This is done above by assuming that a truncated normal distribution applies as opposed to a distribution that has support outside of (0,100). Figure~\ref{f:SUSscoreBayes} shows a 95\% empirical Bayesian credible interval for the same SUS study highlighted earlier in Figure~\ref{f:SUSscoreBoundViolation1}. As demonstrated in what follows, using empirical Bayesian techniques dictate that a practitioner believes that the current study's SUS scores are likely similar to those that have been collected in the past. When sample sizes are extremely small, the mean SUS scores will shift towards the historical norms. It is also important to note that the resulting intervals are not confidence intervals but rather credible intervals that yield a true probability for $\mu$, a useful distinction when communicating results. \begin{figure} \centering \includegraphics[width=1\linewidth]{bayes_sus_n6.png} \caption{95\% empirical Bayesian credible interval for the mean SUS score of the survey highlighted in Figure~\ref{f:SUSscoreBoundViolation1}.} \label{f:SUSscoreBayes} \end{figure} \section{Simulation Study}\label{s:simulation_study} A simulation experiment was conducted to assess the coverage of the expanded BCa bootstrap and \textit{t} distribution CI approaches on very small SUS study results to determine whether 95\% CIs cover the true mean 95\% of the time, and the proportion of CI bounds that fall outside of the SUS score's parameter space. \subsection{Simulation Methodology and Results}\label{ss.method_results} Small sample SUS studies with 4 to 10 respondents were created using a skew normal distribution \citep{azzalini2005skew} with a mean of 68, a standard deviation of 20, and a skewness ranging between -0.99 and 0.99. These choices mirror those seen in practice \citep{bangor2008empirical, lewis2009factor} while abiding the theoretical bounds for skewness appearing in the skew normal distribution \citep{azzalini1985class}. For each combination of sample size and skewness, 500 sets of scores were generated, along with 95\% CIs for each set using the expanded BCa bootstrap and the \textit{t} distribution techniques. The results of this experiment are summarized in the four panels shown in Figure~\ref{f:SimulationResults}. \begin{figure} \centering \includegraphics[width=1\linewidth]{Figure_8.png} \caption{Summary of 95\% CI performance for a simulation of 500 samples of size $n \in \{4, 5, \ldots, 10\}$ from a skew normal distribution with a mean of 68, a standard deviation of 20, and a skewness ranging between -0.99 and 0.99. Panel (a) highlights the proportion of the \textit{t} distribution CIs that exceed the bounds of the SUS score's parameter space. Panel (b) shows the ratio of the mean CI widths, where values less than 1 indicate the BCa bootstrap (with Hesterberg's expansion (\citeyear{hesterberg2015teachers})) is narrower. Panels (c) and (d) give the observed coverage for the BCa bootstrap and \textit{t} distribution CIs, respectively.} \label{f:SimulationResults} \end{figure} The results illustrated in Panel (a) of Figure~\ref{f:SimulationResults} show that the \textit{t} distribution CIs begin violating the SUS score's parameter space at $n=8$, and the situation gets progressively worse as $n$ decreases. At a skewness of -0.39, the average skewness observed in real-world SUS studies \citep{sauro2016quantifying}, roughly 30\% of the \textit{t} distribution CIs exceed the SUS score's upper bound when $n=4$. As seen earlier, the expanded BCa bootstrap CI's bounds are percentiles of the bootstrap sample drawn with replacement from the observed scores. As a consequence, the expanded BCa bootstrap CI always abides the parameter space. Moreover, as seen in Panel (b), for $n \leq 6$ the expanded BCa bootstrap also tends to produce much narrower intervals. However, Panel (c) demonstrates that this narrowness comes at the expense of coverage, and for $n\leq 5$ the expanded BCa bootstrap CI fails to cover the true mean at an unacceptable rate. The results in Panel (d) shows that the \textit{t} distribution CI's coverage performance is significantly better for extremely small samples, but this is not surprising given its considerably wider intervals - intervals that often violate the SUS score's parameter space. In summary, the following decision rules apply: \begin{enumerate} \item $n \leq 5$: With 5 or fewer respondents, both the expanded BCa bootstrap and the \textit{t} distribution CI have significant shortcomings. Additional information is at a premium, and the empirical Bayesian approach offers a way to harness it, albeit at a cost of having to assume that the current study's mean SUS score will follow similar patterns as previously recorded studies. \item $n \in \{6, 7, 8\}$: When compared to the \textit{t} distribution, the expanded BCa bootstrap CI offers acceptable, comparable coverage and narrower or similar widths. It also abides the SUS score's parameter space, and its bounds represent feasible realizations of the true mean SUS score for a sample of size $n$. \item $n\geq 9$: With 9 or more respondents, Figure~\ref{f:SimulationResults} suggests the \textit{t} distribution CI abides the parameter space, is slightly narrower than the expanded BCa bootstrap CI, and has good coverage. Based on this finding, one could argue that a practitioner should strive for at least 9 participants when conducting a SUS study, as it would allow for safely constructing traditional CIs using the \textit{t} distribution. Although this logic has merit, being narrower on average does not imply \textit{always} narrower, and it is easy to construct pathological representative SUS score examples where a \textit{t} distribution CI will exceed the SUS score's upper bound. With this in mind, it appears prudent to construct CIs using both the expanded BCa bootstrap and the \textit{t} distribution, and to subsequently pick the one that is both narrower and abiding of the parameter space. Simulation validated this methodology, yielding observed coverage probabilities ranging from a low of 0.92 to a high of 0.96 with an average of 0.943. In short, nominal coverage is preserved. \end{enumerate} Although it may seem contrary to the philosophy of Bayesian statistics, for completeness the simulation described above was repeated using credible intervals from the empirical Bayesian methodology outlined in Section~\ref{ss.empiricalBayes}. Echoing a comment made earlier, unlike a traditional confidence interval, a Bayesian credible interval allows for a probabilistic statement to be made directly about the parameter of interest. For example, if $[L, U]$ is a $100(1-\alpha)\%$ credible interval for $\mu$, then there is a $(1-\alpha)$ probability that the population mean lies between $L$ and $U$. To verify that such probabilistic statements are reasonable, the percentage of Bayesian credible intervals that covered $\mu = 68$ over the values of $n$ and skewness used in Figure~\ref{f:SimulationResults} were calculated. These percentages ranged from 92\% to 99\%, which agrees nicely with the intended 95\% chance of the credible intervals containing $\mu$. Nonetheless, this level of agreement should be expected, as the simulation was run with a mean that is close to the mean of the prior distribution, which is 70. If the true mean happened to be far from the mean of the prior distribution, this would not be the case. That said, in the absence of additional SUS scores, the Bayesian approach assumes the system under consideration will most likely have a mean similar to other systems that have been previously studied. \subsection{Implications for a Practitioner} While the above simulations appear academic in nature, there are several practical reasons to care about the reporting of the upper confidence bound for SUS study scores. In practice, a usability practitioner can make one of two errors when conducting a SUS study. One could fail to conclude a system is acceptable when it is acceptable, or one could fail to conclude a system is unacceptable when it is unacceptable. The latter appears to be a graver error in the context of assessing usability, as it potentially places an unacceptable system in the hands of the target user base, or it wastes additional resources on further confirmatory studies. Examining the upper bound of a SUS study score's confidence interval helps the practitioner to avoid this type of error. For example, if the true SUS study score is indeed unacceptable, say 50, one would not want to conclude that the product's usability is acceptable. To test whether earlier results hold in this regard, SUS study scores for $n\in \{4,5,6,7,8,9,10\}$ over a range of skewness were simulated, and the number of times that the upper bounds exceeded 70 for both the \textit{t} distribution and the expanded BCa bootstrap were counted. Overall, 40\% of the \textit{t} distribution confidence intervals contained 70, while the expanded BCa bootstrap intervals contained 70 only 31\% of the time. Furthermore, over the range of the skewness tested, the expanded BCa bootstrap intervals reported fewer errors than the \textit{t} distribution intervals in 62\% of the simulations. Although the focus here is on the upper bound, if a practitioner's primary concern is with reporting an acceptable system as unacceptable, the lower bound should be emphasized. In such circumstances, simulation testing suggests the \textit{t} distribution and expanded BCa bootstrap intervals perform similarly for $n\in \{6,7,8\}$. Although beyond the scope of this paper, preliminary analysis indicates that truncated \textit{t} distribution intervals are a promising alternative. \subsection{Validation of Decision Rules against Actual SUS Studies}\label{ss.validation} The effectiveness of the decision rules introduced in the previous section was assessed using a dataset of 206 SUS studies \citep{bangor2008empirical}. As seen in Panel (a) of Figure~\ref{f.DescriptiveStats}, these SUS studies range from a minimum of 3 usability respondents to a maximum of 32 with a median of 10, as indicated by the dashed vertical red line. Additionally, 15 of the studies (7.2\%) had sample sizes of 3 to 5, and 44 (21.4\%) had sample sizes of 6 to 8. Moreover, as Panel (b) of Figure~\ref{f.DescriptiveStats} shows, for the 109 studies with 10 or less respondents, the sample skewness ranged from -2.06 to 0.85 with a mean of -0.43. Taken together, these observations suggest small sample SUS studies are common, and the range of sample skewness simulated earlier is reasonable. Hence, when practitioners find themselves confronted with small sample SUS studies, the procedures outlined above are recommended. \begin{figure*}[!t] \centering \subfloat[Stacked dot plot of sample sizes.]{\includegraphics[width=3in]{SampleSize.png} \label{f.SampleSize}} \hfil \subfloat[Density of sample skewness for small sample SUS studies.]{\includegraphics[width=3in]{SampleSkewness.png} \label{f:SampleSkewness}} \centering \caption{Sample sizes and skewness of the 206 SUS studies in Bangor et al. (\citeyear{bangor2008empirical}).} \label{f.DescriptiveStats} \end{figure*} To investigate Bangor et al.'s (\citeyear{bangor2008empirical}) dataset further, 95\% CIs for the mean of each SUS study were constructed using the \textit{t} distribution, expanded BCa bootstrap, and empirical Bayesian methods. Panels (a) and (b) of Figure \ref{f.new_methods_performance2} show the upper confidence bounds (UCBs) of these CIs for the \textit{t} distribution and the expanded BCa bootstrap methods, respectively. Additionally, within each plot, the blue colored points denote that the associated CI construction method is preferred based on the decision rules outlined in the previous section. \begin{figure*}[!t] \centering \subfloat[UCBs using the \textit{t} distribution]{\includegraphics[width=6in]{206_t-dist2.png} \label{fig:UCB2}} \hfil \subfloat[UCBs using BCa]{\includegraphics[width=6in]{206_BCa2.png} \label{fig:BCUCB2}} \centering\caption{Plot of sample sizes vs. upper confidence bounds for the data of \cite{bangor2008empirical}, where the sample sizes have been jittered for readability. For each of the 206 SUS studies represented in these plots, a blue colored point denotes that the associated CI construction method is preferred based on the decision rules outlined in the previous section. As seen in Panel (a), it is common for the \textit{t} distribution CIs' upper confidence bounds to exceed the parameter space for $n \leq 8$. Additionally, there are two studies with $n>25$; in both cases, the \textit{t} distribution CI is preferred.} \label{f.new_methods_performance2} \end{figure*} Applying the first decision rule, for $n \in \{3,4,5\}$ neither the \textit{t} distribution nor the expanded BCa bootstrap methods should be trusted to generate 95\% CIs that abide the SUS score's parameter space and attain the nominal coverage. Accordingly, none of the points for $n \leq 5$ are colored blue in either of Figure \ref{f.new_methods_performance2}'s panels. Moving to the second decision rule, for samples with 6 to 8 respondents Panel (a) shows that the UCBs of the \textit{t} distribution CIs often exceed the SUS score's maximum value of 100, while Panel (b) highlights that the UCBs of the expanded BCa bootstrap CIs abide the parameter space. In accordance with the second decision rule, all of the points in Panel (b) for $n \in \{6,7,8\}$ are blue. Finally, for samples with 9 or more respondents, the third decision rule implies that if the \textit{t} distribution CI abides the parameter space and is narrower than the expanded BCa bootstrap CI, its representative point in Panel (a) will be blue. Otherwise, the expanded BCa bootstrap CI is the better option, and the associated point in Panel (b) will be blue. Notably, the expanded BCa bootstrap CI is the preferred option in 53 of the 147 SUS studies (36\%) with $n \geq 9$, including several of the studies with the largest number of respondents. Clearly, the expanded BCa bootstrap method is not simply a small sample solution. \begin{figure}[!t] \centering \includegraphics[width=1\linewidth]{Figure_11.png} \caption{Comparison of the labels corresponding to the 95\% CI bounds of the gray points in Panel (a) of Figure \ref{f.new_methods_performance2}, where U = unacceptable, M = marginal, and A = acceptable. Specifically, for $n \leq 5$, the \textit{t} distribution CI is compared to the empirical Bayesian CI, and for $n \geq 6$, it is compared to the expanded BCa bootstrap CI. The numbers in the cells represent counts, and pink colored cells highlight SUS studies where the acceptability labels corresponding to the CIs' bounds disagree.} \label{fig:labels} \end{figure} Figure \ref{fig:labels} provides a tabular summary of the practical consequences of utilizing the empirical Bayesian or expanded BCa bootstrap methods in lieu of the commonly used \textit{t} distribution. In particular, it displays the agreement between the acceptability labels corresponding to the bounds of the \textit{t} distribution CI and the alternative CI suggested by the decision rules, where the numbers in the cells represent counts. For example, when $n \leq 5$ the first decision rule suggests the empirical Bayesian method should be applied. In Bangor et al.'s (\citeyear{bangor2008empirical}) dataset, there are 15 SUS studies that fall into this category. After applying both the \textit{t} distribution and empirical Bayesian methods, there are 7 SUS studies where the acceptability labels disagree. As seen in Panel (a), in 5 of these studies the \textit{t} distribution CI suggests the system's usability ranges from unacceptable to acceptable, while the empirical Bayesian CI sees it as marginal to acceptable. Although the underlying reason for the extremely small number of respondents is unknown, it is reasonable to assume that one or more of the practical limitations mentioned earlier are present. Applying the more appropriate empirical Bayesian method has returned tighter results and sharpened the conclusiveness of the studies. For the remaining two studies in Panel (a), the opposite is true, as the empirical Bayesian method suggests the plausible range of acceptability labels should be loosened to include marginal. Moving to the second decision rule, in Panel (b) of Figure \ref{fig:labels} the agreement between the acceptability labels improves, as only 6 of 44 SUS studies (13.6\%) disagree. In all 6 cases, the expanded BCa bootstrap method returned a more pessimistic usability result than the \textit{t} distribution, and in 3 of the 6 the upper bound of the \textit{t} distribution CI exceeded 100. Finally, after applying the third decision rule, there are 53 SUS studies where the expanded BCa bootstrap CI is preferred over the \textit{t} distribution CI. Among these 53 studies, Panel (c) shows only 5 (9.4\%) disagree, and once again, each disagreement is due to the more pessimistic usability result of the expanded BCa bootstrap CI. \section{Discussion and Custom Application}\label{s:app} While oftentimes the boundaries of the confidence interval shift only slightly, Figure \ref{fig:labels} highlights that such shifts may affect the usability labels assigned to system usability constructs. Given that practitioners make decisions based on these labels, accurately calculating the boundaries of the confidence interval has practical significance. To this end, the empirical Bayesian or expanded BCa bootstrap methods should be used in practice; however, the statistical acumen necessary for a usability practitioner to employ them presents a potential barrier. With this in mind, the authors developed an intuitive, freely accessible online application that automates the calculation of and the decision rules for these alternative CIs (available at \url{http://sus.dse-apps.com}). The user interface accepts and processes SUS data, provides a recommendation for which method(s) to use, and creates effective visualizations to communicate results to both technical and non-technical clients. This application complements a recently introduced free mobile device application called \textit{SUSapp} \citep{xiong2020} that helps practitioners administer the SUS and collect data for later analysis. While the full code base is available under an open source license, the application removes the tasks of configuring and running the code which can be complicated by dependencies (e.g., the need to work with Stan \citep{stan2019} for Bayesian computation). Furthermore, correctly interpreting the direct code output can be difficult without prior knowledge of each method. \begin{figure}[htbp] \centering \includegraphics[width=15cm]{splash_page.png} \caption{The System Usability Scale (SUS) Analyzer application splash page.} \label{fig:sc_main} \end{figure} The application accepts data in CSV format where each row represents an individual's response to the SUS questionnaire. As seen in Figure \ref{fig:sc_main}, a sample data set showing the required formatting is available on the welcome page via the blue hyperlink. After loading data using the ``Upload File" button, a facility is provided for users to view and confirm that data were loaded correctly (see Figure \ref{fig:sc_validate}). Once complete, users select the appropriate button to either edit input data or submit their data for the decision rules to be applied as described in this paper (see Figure \ref{fig:sc_reco}). Recommended methods that adhere to these decision rules appear as blue tabs. If a particular method is not recommended (e.g., an option of using the \textit{t} distribution method with a sample size lower than 5), the tab will display as grey, and a user will not be able to select it. \begin{figure}[htbp] \centering \includegraphics[width=15cm]{verify_data.png} \caption{Users are able to verify their data were loaded correctly before proceeding to the recommendations and visualizations.} \label{fig:sc_validate} \end{figure} \begin{figure}[htbp] \centering \includegraphics[width=15cm]{decision_rules.PNG} \caption{The app recommends which method(s) to use based on the decision rules presented in this paper.} \label{fig:sc_reco} \end{figure} A user can move between the recommended tabs to see visualizations for Bayesian, expanded BCa bootstrap, and $t$ distribution frequency plots, resulting means and confidence intervals, and appropriate mapping to the four common scales mentioned in Section~\ref{s.introduction}. All visualizations can be exported in high resolution images using the ``Save as PNG" button at the bottom of each plot (see Figure \ref{fig:sc_bayes}). \begin{figure}[htbp] \centering \includegraphics[width=15cm]{app_results.PNG} \caption{Results of empirical Bayesian analysis on SUS data showing a 95\% credible interval.} \label{fig:sc_bayes} \end{figure} While there are many additional features that could be included in this application to meet the needs of specific user bases, the version available is intended as a general purpose tool for usability practitioners. Because the source code is available under MIT open source license, practitioners needing to modify the application, its underlying analysis options, decision rules, or output visualizations can do so to add features or modify any of the methods to accommodate specific needs. \section{Conclusions}\label{s:conclusions} The effectiveness of the SUS for assessing usability of systems is well-established among usability practitioners. When a sufficient number of survey respondents are available to leverage the central limit theorem for analyzing and reporting SUS study uncertainties, current practices invoking either a normal distribution or $t$ distribution for constructing confidence intervals are sound. However, when only a small number of users are surveyed, as in cases in which the desired user pool is not available or affordable, reliance on the central limit theorem yields confidence intervals that suffer from parameter bound violations and interval widths that confound mappings to adjective and other constructed scales that organizations rely upon for decision making. These shortcomings are especially pronounced when the underlying SUS score data is skewed, as it is in many instances. Using actual SUS data made available for this study, the $t$ distribution's specific inadequacies are illustrated. Unfortunately, when the sample size is small there is not a single tool that a user can apply in all situations. This paper helps to remedy this by introducing two attractive alternatives that improve the accuracy and reporting of SUS study results when practitioners are faced with very small ($n \leq 10$) and extremely small ($n \leq 5$) samples, namely the expanded BCa bootstrap and an empirical Bayesian approach. These alternative approaches facilitate three novel decision rules when constructing confidence or credible intervals on small sample SUS study means. Additionally, a freely accessible, online application for the usability practitioner to implement these decision rules and produce effective visualizations is developed and presented for general use. It is important to note that for the empirical Bayesian approach the interpretation of the resultant interval is not the same as parametric or non-parametric confidence intervals. In fact, under this paradigm the definition of probability itself is different. Specifically, Bayesian inference relies on subjective probability, meaning it is a measure of belief rather than the long-run frequency. As such, the posterior distribution and associated statistics represent a belief in the population mean, and probabilities can be directly calculated from it. So, if the interval for a mean SUS score is, for example, (45, 75), then it would be correct to conclude that there is a 95\% probability that the population mean is between 45 and 75. While this interpretation is only available when using the empirical Bayesian construction and not the expanded BCa bootstrap technique, it does provide a much more intuitive and natural interpretation regarding uncertainty than a confidence interval, offering a small but significant advantage when communicating SUS results to a non-technical client. While this paper expands the current options for practitioners in reporting SUS scores, there are several questions yet to be explored. Particularly, the current empirical Bayesian approach does not account for the differing types of systems whose usability is assessed using the SUS. For example, a software program may have important inherent differences than a cellphone. To account for system-to-system differences, a hierarchical Bayesian model could potentially be useful. However, recognizing that more nuanced models such as this require additional data to develop, practitioners should be encouraged to share their SUS data to the maximum extent possible for the benefit of the broader usability community. In this spirit of continuous improvement, the authors welcome any feedback or suggestions for improving the online application. Ultimately, our hope is that usability practitioners will gain value from its use in this setting or in other topical areas which exhibit the type of problem characteristics addressed in this paper. \section*{Data Availability} \addcontentsline{toc}{section}{Data_Availability} The data that support the findings of this study were obtained from the corresponding author of Bangor et al. (2008). Restrictions apply to the availability of these data, and it is unavailable.
{'timestamp': '2021-01-19T02:11:44', 'yymm': '2101', 'arxiv_id': '2101.00455', 'language': 'en', 'url': 'https://arxiv.org/abs/2101.00455'}
arxiv
\section{Introduction} \begin{comment} Malwares are often created by attackers to carry out malicious acts on or by compromised victim devices on a massive scale. To perform such malicious activities, a communication channel must be established between a victim machine and a C\&C server. Using these communication channels, botnets are remotely controlled by the attackers. Many different types of cyber-attacks can be performed through botnets, such as stealing users' sensitive information, sending spam, and denial-of-service attacks. According to a study, the number of exploited computers used in a botnet can be more than a million \cite {rossow2014amplification}, which demonstrates the level of danger and damage caused by these armies of zombie machines. \end{comment} \par Security researchers have developed many different defense mechanisms in order to protect computer systems against malware and malicious botnet C\&C communications. Blacklists of malicious websites are one of the most commonly used defense mechanisms where lists of domain names or IP addresses that are flagged as harmful are maintained. Any messages to/from these listed sites are feared to host potential C\&C servers and hence blocked to prevent any further communications. As a counterattack, attackers developed DGAs as a measure to thwart blacklist detection \cite{DGA}. \begin{figure*} \centering \includegraphics[width=16cm]{dga5final.png} \caption{Overview of the Proposed Methodology.} \label{augmented} \end{figure*} \par In recent years, hacker communities have been utilizing DGAs as the primary mechanism to produce millions of malicious domain names automatically through pseudo-random domain names in a very short time period \cite {yadav2010detecting}. Subsets of these malicious domain names are utilized to map to the C\&C servers. These dynamically created domain names successfully evade static blacklist-checking mechanisms. Additionally, as one domain gets recognized and blocked, the C\&C server can easily switch to another one. \par To overcome the limitations of static domain blacklists, machine learning (ML) techniques have been developed to detect malicious domain names and these techniques have yielded mostly promising results \cite {woodbridge2016predicting}, \cite {yilmaz2020addressing}, \cite {yilmaz2020practical}. However, the ML models do not perform well with never-seen-before DGA families when an unrepresentative or imbalanced training dataset is used. To address this problem, we propose a novel approach to generate a rich set of training data representing malicious domain names using a data augmentation technique. Data augmentation of an existing training dataset is one way to make ML models learn better and, as a result, perform more robustly. Nevertheless, classic data augmentation merely creates a restricted reasonable alternative. In our approach, as illustrated in Figure \ref{augmented}, an adversarial machine learning technique is used to generate a diverse set of augmented data by means of data perturbation. The generated adversarial domain names are extremely difficult to differentiate from benign domain names. As a result, the machine learning classifier misclassifies malicious domains as benign ones. Afterwards, these adversarial examples are correctly re-labeled as malicious and reintroduced into the existing training dataset (see Figure \ref{augmented}). In this way, we augment the blacklist with diverse data to effectively train the machine learning models and increase the robustness of the DGA classifiers. In addition, we devise a secure container to store and transfer the blacklists of malicious domain names in encrypted form as a Protected Spreadsheet Container with Data (PROSPECD), presented in \cite{CBMS2020}. PROSPECD provides confidentiality and integrity of the blacklists so that they can be used as training data to build a secure model. In addition to data integrity, PROSPECD provides origin integrity. This container protects the adversarial samples, used to teach the model, from unknown adversarial perturbations. The protected blacklist can be marketed commercially \cite{profit} to internet service providers and companies who need to maintain their own internal blacklists. \subsection{Our Contributions} Blacklist is a security strategy that keeps network flow and computer environments secure \cite{Blacklists}. Typical network traffic blacklists include malicious IP addresses or domain names, which are blocked from communication attempts in both directions. However, the coverage of blacklists is insufficient and unreliable because adversarial hacker communities can compromise a system by generating malware domains dynamically using DGAs that easily bypass the static blacklist. Kuhrer et al. \cite {kuhrer2014paint} evaluated 15 public malware blacklists as well as 4 blacklists, served by antivirus vendors. Their findings show that blacklists fail to protect systems against prevalent malware sites generated by DGAs. In order to address the shortcomings of the above problem, researchers have mostly proposed solutions based on reverse engineering techniques to identify and block bot malware \cite{ligh2010malware}. However, such solutions are not always feasible due to the obfuscation of underlying algorithms, as hackers adapt their algorithms swiftly to exploit the vulnerabilities in the system. Other alternative solutions require auxiliary contextual information. One of these alternative solutions focuses on the network traffic analysis \cite {zhang2011detecting}, \cite {yen2010your} or broad network packet examination \cite {manni2015network}, \cite{aziz2018electronic}. However, these techniques may not be able to keep up with large-scale network traffic. Therefore, there is a need for a sophisticated network traffic analysis tool for effective blacklisting. In response to the above issues, detection of malicious domains has increasingly evolved towards usage of machine learning techniques. Performance of the solutions proposed to automatically detect malicious domains mostly suffers from never-seen-before malicious domains. This is due to the lack of generalization when a model is not trained effectively with representative or balanced training dataset. For this reason, blacklists must be constantly updated in order to identify and prevent DGA generated malicious domain connections. Data augmentation is an approach where more data is created from existing data in a way that can enhance the usefulness of the application. Anderson et al. \cite{anderson2016deepdga} demonstrated how data can be augmented more effectively by using an adversarial machine learning technique. The researchers enhanced adversarial domain names using Generative Adversarial Network (GAN) methodology. In their approach, two neural networks are trained simultaneously, and later trained with a dataset which includes adversarial samples to harden the DGA classifier. However, the main drawback of this approach is unpredictability of desirable results because of difficulties of controlling both classifiers at the same time, even though a good optimization algorithm is used. As a result, it fails to always converge to a point of equilibrium to generate new domain names. Additionally, controlling the diversity of produced samples is challenging with GAN models \cite {berthelot2017began}, \cite{yilmaz2019expansion}. In such cases, the newly generated data do not add to the diversity of the current data. Hence, this solution alone cannot increase the malicious detection capabilities of blacklists against never-before-seen DGA families. To improve the accuracy of such detection mechanisms, we propose a new technique based on data perturbation without relying on a fresh public blacklist or external reputation database. In our approach, we observe how the model works and use the knowledge to mislead the DGA classifier. To do this, a noise, carefully calculated from the observation is added to the DGA based malicious domains to appear non-malicious. These adversarial samples are then predicted as benign by the machine learning (ML) model. Such adversarial attack can be addressed with an adversarial training \cite{goodfellow2014explaining}. Therefore, after correctly labeling these seemingly benign adversarial samples, the ML model is trained with the augmented dataset. The experimental results demonstrate that the retrained ML model is able to detect never-before-seen DGA malwares better than any other similar approaches. Our work has the following contributions: \begin{itemize} \item Using a machine learning technique based on the Long Short-Term Memory (LSTM) model for automatic detection of malicious domains using a DGA classifier that analyses a massive labeled DGA dataset, character by character over. \item \textit{To the best of our knowledge} it is the first study to propose the generation of malicious domain names using a data perturbation approach in order to expand the training dataset with adversarial samples. \item Demonstrating that, as expected, the LSTM model fails to recognize newly introduced adversarial samples in augmented training dataset. \item Applying an adversarial training to train the model with correct labelling of the adversarial samples in the training dataset to increase the model's generalization ability. \item Demonstrating that the augmented training dataset can help the LSTM model to detect not only never-seen-before DGAs, but also novel DGA families. \end{itemize} \par The rest of this paper is organized as follows: the literature review in the context of our work is discussed in section \ref{related}. The necessary background for DGA-based malicious domain models is reviewed in Section \ref{background}. The core design of our system, including the adversarial machine learning models to generate malicious domain names and data containers to store them, are presented in Section \ref{design}. We discuss the implementation of the adversarial machine learning models in Section \ref{implementation}. The evaluation results of our study are presented in Section \ref{evaluation}. Section \ref{conclusion} concludes the paper. \section{Related Work} \label{related} \par Domain Generation Algorithms and detection of malicious domain names have been previously analyzed by different researchers for a number of years. Daniel et al. \cite{plohmann2016comprehensive} presented a taxonomy of DGA types by analyzing characteristics of 43 different DGA-based malware families and compared the properties of these families. They also implemented previous studies with 18 million DGA domain data that was created to identify malicious domains. They reported further progress in DGA detection. Detection of DGA botnets became feasible with the implementation of powerful machine learning models. Lison et al. \cite{lison2017automatic} implemented a recurrent neural network model for the detection of DGAs. Their empirical study detected malicious domain names with high accuracy. Justin et al. \cite{ma2009beyond} defined several models to detect malicious web sites, including a logistic regression, support vector machine, and bayesian model. They used the DMOZ dataset for benign websites while PhishTank and Spamscatter were used for malicious websites. Bin et al. \cite{yu2018character} addressed the same issue using different machine learning classifiers for the detection of DGAs. They created a convolutional neural network (CNN) and a recurrent neural network (RNN) machine learning model for the classification of malicious and benign domain names. They compared the results of both models in terms of their performance and reported that both models performed comparably. Duc et al. \cite{tran2018lstm} dealt with the multiclass imbalance problem of LSTM algorithms for the detection of malicious domain names by generating DGAs. The authors claimed that the LSTM algorithms performed poorly with imbalanced datasets. To tackle this imbalanced dataset problem, they proposed a Long Short-Term Memory Multiclass Imbalance (LSTM.MI) algorithm and showed that their proposed algorithm provided more accurate results by implementing different case studies. \par In addition, Mayana et al. \cite{pereira2018dictionary} introduced a WordGraph method to recognize dictionary based malicious domains. The authors asserted that more sophisticated DGAs are able to avoid detection of conventional machine learning classifiers. They carried out their experiments by extracting dictionary information without using reverse engineering. Bin et al. \cite{yu2017inline} defined a deep neural network model as an inline DGA detector. They caution about most of the available datasets not being good representations for malicious domains or outdated. Hence, machine learning models' perform poorly when trained using such datasets. Furthermore, they explained that reverse engineering was a difficult method for training models. To tackle these problems, the researchers offered a novel detector for malicious domains without the need for reverse engineering. Their proposed technique was based on real traffic and reported to detect malicious domains in real time. Woodbridge et al. \cite{woodbridge2016predicting} created a machine learning classifier based on the LSTM network to detect malicious domain names in real time. Their classifier detected multiclass domains by categorizing them into particular malware families. The model predicted a domain name as malicious or benign according to this domain name without any additional information. However, although these studies achieved high detection rates for particular DGA families, the performance of machine learning based detection systems are poor with new DGA variants when the models are trained with unrepresentative or imbalanced training datasets. To handle this issue, Anderson et al. \cite{anderson2016deepdga} offered a GAN algorithm to generate new domain names. In their GAN approach, they implemented two different deep neural network classifiers named discriminator and generator. According to this GAN methodology, new malicious domain names are generated by the generator, which evades the discriminator's detection. Their case studies demonstrated that new malicious domain names also bypass a random forest classifier. Once the model was trained with adversarial samples, it hardened the model against new DGA families. However, the authors did not test it on DGA families created using a dictionary. Additionally, implementation of this approach is challenging due to the need of controlling two machine learning models, which might be unsuitable for detecting malware-related domain names. Unlike this approach, we propose to augment data by using an efficient data perturbation technique that generates hard-to-detect DGA families and identifies DGA types that are created either randomly or using a dictionary. To overcome limitations of machine learning models in aforementioned circumstances, Curtin et al. \cite{curtin2019detecting} proposed to combine a neural network model with domain registration supplementary information. This additional information, which is known as WHOIS data, helped the neural network model to efficiently identify the most difficult samples that were generated using English words. However, cybercriminals take advantage of bulk registration services by registering thousands of domain names in a short time, several months before the start of nefarious activities \cite{zhauniarovich2018survey}. In addition, unauthorized people can access this information and falsify it by impersonating as legitimate users. This makes the information questionable. Compared to this, our approach efficiently detects DGA families solely based on the domain names, without relying on any supplementary information. PROSPECD container used to store and transfer blacklisted malicious domain names, is presented in \cite{CBMS2020}. Compared to the privacy-preserving data dissemination concept as proposed by Lilien and Bhargava \cite{lilien2006}, it has the following features: \begin{itemize} \item Detection of several types of data leakages that can be made by authorized entities to unauthorized ones; \item Enforcement of access control policies either on a central server or locally on a client's side in a Microsoft Excel\textsuperscript{\textregistered}\footnote{This paper is an independent publication and is neither affiliated with, nor authorized, sponsored, or approved by, Microsoft Corporation \cite{microsofttrademark} } Add-in or in a cross-platform application \cite{CBMS2020}. \item Container implementation as a digitally signed watermarked Microsoft Excel\textsuperscript{\textregistered}-compatible spreadsheet file with hidden and encrypted data and access control policies worksheets. \item On-the-fly key derivation mechanism for data worksheets. \end{itemize} The primary difference between PROSPECD and an Active Bundle \cite{othmane2010thesis}, \cite{othmane2009}, \cite{ranchal2015cross} is that PROSPECD does not store an embedded policy enforcement engine (Virtual Machine). In contrast with a solution to encrypt the desired cells in a spreadsheet file, proposed by Tun and Mya in \cite{tun2010}, in PROSPECD all the data worksheets are encrypted with the separate keys, generated on-the-fly. PROSPECD supports role-based and attribute-based access control. Furthermore, digital and visual watermarks are embedded in PROSPECD to enable detection of data leakages. A Secure Data Container, proposed in \cite{secureICS} to store device state information, only supports centralized policy enforcement. PROSPECD supports both centralized and local policy enforcement mechanisms \cite{CBMS2020}. \section{Background} \label{background} In this section, we review background information related to our research. \subsubsection{\textbf{Domain Generation Algorithm (DGA)}} Domain generation algorithms are primary means to connect various families of malware with new or never-before-seen domains to avoid detection. There are many such DGA-based malware families (malware that connect to DGA generated domain names). According to a study, the five most known families are \textit{Conficker}, \textit{Murofet}, \textit{BankPatch}, \textit{Bonnana}, and \textit{Bobax} \cite{top}. Although many DGA-based domain names are produced randomly, some are generated using a dictionary. The detection of these types of domain names is more difficult because of their similarity to legitimate domains. \subsubsection{\textbf{Gradient Descent Algorithm}} The gradient descent algorithm is the most popular optimization method for using machine learning classifiers to minimize errors. It takes into account the first derivative when modifying all parameters under considerations \cite{gradient}. Gradient descent always strives to find the most appropriate way to minimize errors. The learning process starts with randomly producing weight values. Most of the time, these values are set to an initial value of zero and are used to calculate the lost function value. It then uses the gradient descent algorithm to find a way to reduce the lost function. All weights are updated through the backpropagation process based on the gradient descent algorithm. We generate new adversarial domain names in our data augmentation method by utilizing and modifying the gradient descent algorithm's behavior. In Section \ref{implementation}, explanation of how such adversarial samples are created is discussed in detail. \subsubsection{\textbf{Long Short-Term Memory (LSTM) Model}} The LSTM model, a specialized Recurrent Neural Network (RNN), is used in our approach for automatic detection of malicious domains. RNNs are known as supervised machine learning models that are commonly used to handle the processing of sequential data \cite {hochreiter1997long}. An RNN takes the previous and current inputs into account while the traditional networks consider all inputs independently. In our study, we implement the model on a character by character basis, so that it captures the importance of the order of the characters' occurrence in the word. Essentially, the model learns the occurrences of the characters in a sequential way. For example, for the domain name \textit{google}, without the top-level domain, the model first learns the character \textit{g}, then \textit{o}, predicting that it succeeds \textit{g}. However, traditional neural networks do not take the position of the characters into account. In addition, the traditional neural networks process fixed-sized input. Similarly, they can create fixed-size output, whereas RNN does not have such limitations. When input data like domain names have long term sequences, traditional RNN struggles to learn such long data dependencies, which is known as the vanishing gradient problem \cite{hochreiter1998vanishing}. In order to avoid this problem, LSTM, which is a special kind of RNN, was introduced in \cite{hochreiter1997long}. LSTM relies on the gating mechanisms, where the information can be read, written or erased via a set of programmable gates. This allows recurrent nets to keep track of information over many time-steps and gain the ability to preserve long term dependencies. For example, \textit{47faeb4f1b75a48499ba14e9b1cd895a} is a malicious domain name, which has a 32 character length. LSTM keeps track of the relevant information about these characters throughout the process. Furthermore, a study has shown LSTMs outperform previous RNNs for the solution of both context-free language (CFL) and regular language problems \cite{gers2001lstm}. Researchers have reported that LSTMs generalize better and faster, leading to the creation of more effective models. In our study, the LSTM model learns how to detect DGA-based malicious domains in a similar way to what is mentioned above. \section{Core Design} \label{design} \subsection{Generating New Malicious Domain Names} Machine learning models' performances substantially rely on the training dataset crucial for building effective classifiers. However, one of the biggest challenges with any ML model is accumulating a training dataset that is representative and balanced enough to enable the creation of an effective machine learning model. This process might be costly or time-consuming or both. A restrictive training dataset can lead to poor performance of the ML model and that is the primary reason DGA classifiers do not work well with automated malicious domain name detection. With traditional blacklists used in training, ML classifiers cannot detect never-before-seen DGA families. The model needs to be readjusted constantly with new variations of training data for effective threat detection. To address this issue, we propose to create a blacklist with domain names using a novel adversarial machine learning technique. Our adversarial approach is based on data perturbation techniques inspired by \cite{goodfellow2014explaining}, where domain names are influenced based on the gradient descent algorithm of a targeted DGA classifier with regards to the classifier loss. Changing the gradient of the classifier maximizes loss function instead of minimizing it can mislead the malware detection classifiers. Even though these domains are malicious, the DGA classifier, based on the LSTM model, predicts them as benign. As a result, new adversarial domain are generated that can seem benign by not matching the blacklist data. Our method is clarified mathematically below \cite{goodfellow2014explaining}. Let \textit{x} be a given malicious domain name, \textit{y} be labeled as malicious, \textit{M} be a DGA classifier that M(x): x $\rightarrow$ y, \textit{$\hat{x}$} is crafted domain name using our adversarial attack and \textit{$\hat{y}$} is the class label that M(x): $\hat{x}$ $\rightarrow$ $\hat{y}$ \begin{equation} \hspace{0.3cm} objective \hspace{0.6cm} max \hspace{0.1cm}l(M,\hat{x},y) \end{equation} \begin{equation} \hspace{1cm} y \neq \hat{y} \end{equation} \begin{equation} subject \hspace{0.1cm} to \hspace{0.5cm} \hat{x} = x + \delta x \end{equation} Here \textit{l(M.x,y)} is the loss function of the DGA classifier in (1). A newly created adversarial domain name is predicted as benign by the DGA classifier in (2). \textit{$\delta$x} in (3) represents perturbation added to a vector form of the given domain name. $\delta$x is calculated below \cite{goodfellow2014explaining}: \begin{equation} \hspace{0.3cm} \delta x = \epsilon \hspace{0.1cm} sign(\nabla x \hspace{0.1cm}l(M,x,y)) \end{equation} Here \textit{sign} ($\nabla$x l(M,x,y) ) represents the direction of the loss function, which minimizes the loss function of the DGA classifier, and $\epsilon$ controls the expansion of the noise in (4). The smaller epsilon value perturbs the original feature vector slightly, while the larger one perturbs the original feature vector significantly. This misleads the DGA classifier to a great extent. On the other hand, a larger perturbation can be more easily detected than a smaller one by human eyes. The calculated noise is included in each character embedding of input data. The resulting embedding characters with noisy calculations are compared to each character's embedding using \textit{cosine similarity} \cite {cosine_similarity} to measure each distance. The final character is chosen based on this operation. The design of the model is demonstrated in Figure 2. According to the example in the figure, character g turns to c with our use of adversarial learning. Our adversarial domain name generation algorithm is summarized in Algorithm 1. \begin{figure}[!ht] \centering \includegraphics[width=8cm]{proposed_scheme.pdf} \caption{Generation of Adversarial Samples Using Character-Level Transformations.} \label{DDOS} \end{figure} \begin{algorithm} \caption{Pseudocode of our proposed \textit{adversarial domain name generation} approach} \label{alg:generator} \SetKwProg{generate}{Function \emph{generate}}{}{end} \noindent \textbf{Input:} \\- Train data pair $\{X_{i},Y_{i}\}$ where $X_{i}$ = Each domain name and $Y_{i}$ = Corresponding ground-truth label\\ - X =($x_{1}$ || $x_{2}$ ||...|| $x_{n}$) where $x_{i}$ = Each character of a given input domain name\\ - Training iteration number $N_{itr}$, Number of adversarial examples $N_{adv}$, Number of training samples $N_{train}$, Number of character of a given input domain name $N_{total}$\\ - Test data pair $\{X_{j},Y_{j}\}$\\ \generate{domain names}{ \For {iteration = 0, ..., $N_{itr}$}{ \indent \indent Update all parameters based on gradient descent \newline } \For {iteration = 0, ..., $N_{adv}$}{ \For {iteration = 0, ..., $N_{total}$}{ \vspace{2mm} \indent \indent $\delta_{x_{i}}$ = $\epsilon \times sign (\nabla_{x_{i}}l(M,x_{i},y_{i}))$ \newline \indent \# Calculate penetration for each character \vspace{2mm} \newline \indent \indent ${z_{i}}$= $x_{i}$ + $\delta_{x_{i}}$ \vspace{2mm} \indent \indent$ \underset{max} {\hat{x}}= \frac{ {z_{i}} \bullet x_{}} {\sqrt{{z_{i}} ^ 2 \times {x_{i}} ^ 2}} \vspace{2mm} $ \newline \indent \# New characters are generated through our proposed method\newline } \noindent \textbf{Output:} $\hat{X}$ =($\hat{x}_{1}$ || $\hat{x}_{2}$ ||...|| $\hat{x}_{n}$) \newline \indent \# New malicious samples are generated\newline } } \end{algorithm} The DGA detectors can be seen as black-box devices in real-world settings. Since, in the black-box scenario, an adversary does not have any knowledge about the inner workings of the target model. Nevertheless, for the sake of simplicity, we implement our proposed technique under the white-box assumption, where we obtain optimum perturbation by accessing the target model so that we can compute gradients. Although the black-box assumptions can be perceived as more realistic for this work, it is important to keep in mind that previous studies showed that adversarial samples have the \textit{transferarability property} \cite {papernot2016transferability}. This means that an adversarial example generated for one DGA model is more likely to be misclassified by another DGA detector as well, since when different ML models are trained with the similar dataset from the same source, they learn similar decision boundaries. We leave testing adversarial examples the under black-box settings for future work. \subsection{Protected Spreadsheet Container with Data (PROSPECD) for Domain Names Blacklists} We propose to use a PROSPECD data container, presented in \cite{CBMS2020}, to securely store and transfer blacklisted malicious domain names. In our use case, PROSPECD, implemented as an encrypted and digitally signed spreadsheet file, contains the following watermarked data worksheets: \begin{itemize} \item{"Domain Blacklist" to store encrypted malicious domain names, detected by our classifier;} \item{"Metadata" to store encrypted metadata, which include access control policies;} \item{"General Info" to store encrypted information about the classifier used to detect the malicious domain names and its execution details.} \end{itemize} PROSPECD provides data confidentiality and integrity, origin integrity, role-based and attribute-based access control and centralized and decentralized enforcement of access control policies. Digital and visual watermarks, embedded into a PROSPECD spreadsheet file, enable detection of several types of data leakages that can be made behind-the-scenes by authorized parties to unauthorized ones \cite{CBMS2020}. \\ \textit{\textbf{PROSPECD Generator.}} The malicious domain names classifier runs on a trusted server. Once the blacklist of domain names is generated, the dedicated process writes it, as well as the relevant information, in a spreadsheet file. Then the PROSPECD generator, currently implemented as a command line utility, is called. It takes a spreadsheet file with the "Domain Blacklist" worksheet and two other worksheets ("General Info" and "Metadata") in a plaintext form, as an input, and generates a separate spreadsheet file with encrypted worksheets. Each separate worksheet is encrypted with a separate symmetric 256-bit AES key, generated on-the-fly \cite{CBMS2020}. \textit{\textbf{PROSPECD Data Access on a Trusted Server.}} The PROSPECD container, stored on a trusted server, can be accessed remotely from a web viewer. The client opens the Authentication Server (AS)'s URL in a web browser, selects the data subset to retrieve (”Domain Blacklist”, "General Info" or "All") and enters their credentials: username (role) and password. The accessible worksheets from PROSPECD are decrypted, using the on-the-fly AES key derivation scheme, based on the client's role and attributes. These attributes include versions of a web browser and an operating system, as well as the type of device the client uses. Decrypted worksheets are sent to the client as a JSON object via https communication channel \cite{CBMS2020}. PROSPECD supports RESTful API. Table \ref{access-control-table} shows the access control policies. The role "User" can only access blacklisted domain names from the "Domain Blacklist" worksheet. The role "Administrator" is allowed to access all the worksheets and also to download the PROSPECD file from the server to their local device, to access the data locally or transfer it to other parties. \begin{table}[!h] \centering \caption{PROSPECD Access Control Policies} \sisetup{per-mode=symbol} \begin{tabular}{||c c c c||} \hline & Domain Blacklist & General Info & Metadata \\ [0.5ex] \hline\hline Administrator & YES & YES & YES \\ \hline User & YES & NO & NO \\ \hline \end{tabular} \label{access-control-table} \end{table} \textit{\textbf{Local PROSPECD Data Access.}} Authorized parties can access PROSPECD data locally, either from the Microsoft Excel\textsuperscript{\textregistered} Add-in or from the standalone cross-platform application. For the first option, a user needs to "download and install the Microsoft\textsuperscript{\textregistered} Excel Add-in" \cite{CBMS2020}, written in C\#\textsuperscript{\textregistered}, open a PROSPECD container and enter valid credentials. Then the PROSPECD's digital signature is verified. If it is valid, the "Metadata" worksheet is decrypted and access control policies, stored in this worksheet and shown in Table \ref{access-control-table}, are evaluated. Then the decryption keys for accessible data worksheets are derived \cite{CBMS2020}. To prevent unauthorized data disclosures, the authenticated user is not allowed to print or save the opened spreadsheet file once the Add-in has been launched. When a user closes an application, all the data are encrypted back to their original values and the visibility of all the worksheets is reset back to VeryHidden\textsuperscript{\textregistered}, after which the application closes. In addition to the Microsoft\textsuperscript{\textregistered} Excel Add-in, a cross-platform application was developed to view PROSPECD data \cite{CBMS2020}. This application provides a graphical user interface and does not allow the user to store the decrypted PROSPECD files locally, to prevent possible data leakages. \section{Experimental Methodology} \label{implementation} This section describes the dataset used to build a DGA classifier based on an LSTM model, along with the explanation of the model implementation. \subsection{Dataset} The experimental dataset includes one non-DGA (benign domain names) and 68 DGA families (malicious domain names). Data is collected from two different sources, which are publicly available \cite{majestic}, \cite{plohmann2016comprehensive}. For benign domains, we use the Majestic top 1 million dataset \cite{majestic}. This dataset includes the top one million website domain names all over the world and the dataset is updated daily. For malicious domains, we obtain data from the DGArchive, which is a web repository of DGA-based malware families \cite{plohmann2016comprehensive}. This repository has over 18 million DGA domains. We have worked on 68 DGA malware families with some being generated by traditional DGAs. The remaining families were produced by dictionary DGAs. We used both traditional-based DGAs and dictionary-based DGAs with over a hundred thousand malicious domains. To ensure a fair comparison, we used a subset of 135K samples from the Majestic top 1 million dataset so that the classifier does not bias towards the majority class and thus, prevent occurrence of overfitting. \subsection{ML Model Implementation} We implement our LSTM model in Python using Pytorch \cite{pytorch}. We use the LSTM at character level with application of character embeddings (vector forms of the characters). This means that we every character is encoded to a representative vector. We convert from the word spaces to vector spaces to extract better features for the machine learning classifier. Each ASCII character (total number is 256) represents a vector whose size is set to 256. In this way, we create a 256 by 256 embedding matrix where each row represents a character and character embeddings are represented by column vectors in the embedding matrix. Once the perturbation technique is employed, embedded vectors of the character of malicious domains are transformed into word space again. We divided the dataset into training and test data. We use 90\% of the dataset for training and remaining is reserved for testing. The training is used by the model to learn detection of DGA-based malicious domains. In our implementation, only the domain names are considered by the model, and the characters are pulled from the domain names character by character. At each time interval, one character's corresponding vector is fed into the LSTM model. The character embeddings are randomly initialized at the beginning. The model is able to learn through the dependencies that is has with each other and the conditional probabilities of the aforementioned characters. Thus, each character's embedding is learned by the LSTM model itself and the matrix is filled with these embeddings. In the test phase, the unseen data is predicted by the model as malicious or benign. The model's performance is analyzed in section \ref{evaluation} in detail. In this work, our main goal is to augment the training dataset to increase the model's resiliency and improve performance for detection of never-before-seen or yet-to-be-observed DGA families. To do this, an optimally calculated noise is added to each character embedding of the input data by the data perturbation technique. The newly created embedding with the addition of noise may not be assigned to any character. Therefore, the model looks for the closest embedding character and assigns it as the character to that corresponding embedding. Here we use \textit{approximate similarity search} \cite {patella2009approximate} by applying c\textit{osine similarity} \cite {cosine_similarity} that takes dot products between newly created embedding and each row of the embedding matrix to calculate the similarity. The new character is assigned to the row matrix's corresponding character, yielding maximum similarity value. Technically speaking, the LSTM model consists of two hidden layers along with the input and output layers. The \textit{drop out}, a known regularization technique, is used with a rate of 0.5 in order to avoid overfitting. The fine-tuned parameters are found by using a batch size of 128 and a learning rate of 0.001 along with an epoch number of 6. To achieve learning rates lower than this, more iterations may be needed. In addition, we use the \textit{adam optimization algorithm} an extension to stochastic gradient descent, to minimize the error by adjusting network hyper parameters in an iterative way. Furthermore, \textit{binary cross entropy} utilized for binary classification, is used as the loss function in order to measure the cost over probability distribution of malicious and benign domain names. \section{Evaluation} \label{evaluation} The results of our experiments are divided into two sections. Firstly, we evaluate the performance of the newly proposed LSTM model and compare it with a previous work known as DeepDGA in terms of model accuracy \cite{anderson2016deepdga}. In addition, we report on how the model accuracy changes against tempering of input samples in order to generate adversarial instances. Finally, we analyze the DGA classifier before and after adversarial augmentation of training data. At first, a binary classification, which simply predicts between DGA-based malicious or benign (Alexa top 135K) samples are applied. Table \ref{comparison} demonstrates a comparison between the performance of the Deep-DGA model and our LSTM-based model. The detection rates of Cryptolocker and Dicrypt is higher with DeepDGA than our DGA classifier with the available samples. On the other hand, Locky V2, Pykspa, Ramdo and Simda are detected with better accuracy by our classifier, and the rest of the cases show the same detection rate for both. Even though the results demonstrated that the improvement was not substantial, the results could have turned out to be different, since we used a different dataset than DeepDGA. \begin{table}[!h] \centering \caption{Deep-DGA and the Proposed Model Comparison} \sisetup{per-mode=symbol} \begin{tabular}{||c c c||} \hline & Deep-DGA & The Proposed DGA Detector \\ [0.5ex] \hline\hline Corebot & 1.0 & 1.0 \\ \hline Cryptolocker & \textbf{1.0} & 0.98 \\ \hline Dircrypt & \textbf{0.99} & 0.98 \\ \hline Locky V2 & 0.97 & \textbf{0.99} \\ \hline Pykspa & 0.85 & \textbf{0.90} \\ \hline Qakbot & 0.99 & 0.99 \\ \hline Ramdo & 0.99 & \textbf{1.0} \\ \hline Ramnit & 0.98 & 0.98 \\ \hline Simda & 0.96 & \textbf{0.98} \\ \hline Average & 0.97 & \textbf{0.98} \\ \hline \end{tabular} \label{comparison} \end{table} \begin{comment} \begin{table}[!t] \centering \includegraphics[width=8cm\linewidth]{comparison_1.pdf} \caption{ Comparison Between the Deep-DGA and the Proposed Model.} \label{comparison} \end{table} \end{comment} \subsection{ LSTM model results} \begin{table*} \begin{center} \scalebox{.9}{ \begin{minipage}[b]{0.5\textwidth} \begin{center} \includegraphics[width=\textwidth]{result_1.pdf} \caption{Detection Rate of DGA Malware Families Using the LSTM Model.} \label{fig:1} \end{center} \end{minipage} \begin{minipage}[b]{0.50\textwidth} \begin{center} \includegraphics[width=\textwidth]{result_3.jpg} \caption{Detection Rate of DGA Malware Families Before and After Training Data Augmentation.} \label{fig:2} \end{center} \end{minipage} } \end{center} \end{table*} \begin{table*}[!ht] \begin{center} \includegraphics[width=12cm]{transformation.pdf} \caption{Transformation of Alexa Domain Name Samples.} \end{center} \label{transformation} \end{table*} \begin{table*}[!ht] \begin{center} \includegraphics[width=11cm]{malben16.pdf} \caption{Performance of the DGA Classifier vs. Penetration Coefficient for Both Benign and Malicious Domains.} \end{center} \label{accuracy} \end{table*} Table \ref{fig:1} shows the resulting detection rates for our model for 68 DGA families. Our findings show that our method performed with high accuracy (usually above the 0.97 accuracy margin) for most of the DGA-based malware families. \begin{comment} \begin{figure}[!ht] \centering \includegraphics[width=5.5cm]{figures/malicious2.eps} \caption{Accuracy vs. Penetration Coefficient for Malicious Domain Names.} \label{malicious} \end{figure} \begin{figure}[!ht] \centering \includegraphics[width=5.5cm]{figures/benign.eps} \caption{Accuracy vs. Penetration Coefficient for Benign Domain Names.} \label {benign} \end{figure} \end{comment} We also evaluate the DGA classifier performance considering standard metrics such as precision, recall, F1-score, false positive rate (FPR), false negative rate (FNR) and area under the receiver operating characteristic curve (AUC). These evaluation metrics are widely used to measure the quality of the ML model. Using the proposed algorithm, we craft domain names from both benign (Alexa 135K) and DGA-based malicious samples. Based on different epsilon values, the changes in these evaluation metrics of the model can be viewed in Table VI. Initially, we set the epsilon value to zero to observe the actual performance of the model. Our findings show that the model performs well in terms of the aforementioned metrics. In case of the adversarial samples that were generated from malicious domain names, the accuracy rate of the LSTM model degrades with increase in epsilon value until it stabilizes at an equilibrium, because, at that point, the model has been trained well enough to recognize malicious domains. In addition, the dissimilarities between the benign class and the malicious class drastically increase. This indicates the limit of misclassification, even with increasing epsilon values. \begin{comment} Figure \ref{malicious} demonstrates how the addition of noise at different levels to the malicious samples helps to create the adversarial instances with the proposed algorithm. \end{comment} We also consider benign instances as an input to corrupt the benign samples for creating the adversarial domain names. Subtle perturbations do not decrease an accuracy much, since the injected epsilon values do not manipulate the original data sufficiently to cause misclassification. When we continue to increase the penetration coefficient that causes slight differences to the original benign data, the model fails to recognize these changes. Therefore, the model performance is dramatically impaired. As we further scale up the noise, the model starts to predict these drastic modifications more accurately, due to severe degradation of the input. Table V shows how the domain name samples are transformed by the epsilon values. It is noteworthy to observe the decreasing accuracy of our DGA classifier as we add perturbations because adversarial examples mislead the model into making incorrect decisions that increase the number of false positives and false negatives. The various adversarial samples that are created by injecting noise has the potential to deceive the LSTM model even more than the adversarial samples generated by GAN. In the study of Anderson et al. \cite{anderson2016deepdga}, it was found that the detection rate of the model is 48.0\%, which means that they achieved an attack success rate of about 53\%. Table VI shows instances of LSTM model's accuracy to be around 45\% with different perturbation coefficients. We achieved the highest attack success rate of 56\%, which is higher than the GAN approach by 3\%, indicating that our model generated DGA families are able to deceive the ML model more effectively. \begin{comment} \begin{table}[!ht] \includegraphics[width \caption{Accuracy vs. Penetration Coefficient Results for Both Benign and Malicious Domains.} \label {accuracy} \end{table} \end{comment} \subsection{Improving the LSTM Model with Augmented Training Data} As discussed above, we are able to successfully produce adversarial domain names that can bypass detection by the LSTM model. We show that successful augmentation of training data samples can be done with our proposed method. Changes in penetration coefficients can impact the DGA classifier to different extents in terms of the model accuracy. We later modify the dataset by injecting correctly labelled adversarial domains. We replace every malicious training samples with its adversarial counterpart including the top Alexa 135K in the training set, and re-train the model. Table \ref{fig:2} illustrates the differences before and after training with adversarial samples when the epsilon value is 11. Our reason for selecting the value 11 for the epsilon is to illustrate the maximum damage to the well-trained LSTM model and how training the model with augmented data performs much better. When the model is trained with adversarial samples, the model is able to detect unseen malicious samples in the training set to a larger extent. The hardened classifier increases the model's detection ability for each DGA family, as can be seen from Table \ref{fig:2}. As noted for some family groups, such as Bamital, Gspy, and Ud2, the adversarial manipulation did not have any significant impact on model accuracy (within 1\%). However, for most others, the training with augmented data boosted accuracy immensely, on some occasions reaching up to 100\%. As a result, the model trained with adversarial samples has shown to perform much more accurately, close to the performance of the model before adversarial manipulation. \begin{comment} \subsection{PROSPECD Performance Evaluation} In this section, we evaluate the performance of a PROSPECD container by measuring Round-Trip Times (RTT) for data requests sent by a domain name service (client), as HTTPS GET requests, to a PROSPECD, similarly to \cite{CBMS2020} and \cite{secureICS}. We collect RTTs by measuring the time starting from the client's data request to the PROSPECD and ending with the receipt of the response from the PROSPECD. "RTT is the sum of times spent for authentication, evaluation of access control policies and the client’s attributes, decryption key derivation, data decryption and retrieval." \cite{CBMS2020} The ApacheBench\textsuperscript{\textregistered}\footnote{We do not claim association or endorsement of\textbackslash for\textbackslash by the Apache Software Foundation (ASF) \cite{apachetrademark} } utility was used to measure RTT as an average of 1000 data requests, varying requested data size from 0.5 to 842 kilobytes and number of concurrent data requests from 1 to 100. "As a baseline experiment, the same amount of data is retrieved, using one thread, from an encrypted JavaScript Object Notation (JSON) file instead of a PROSPECD, where Excel® data are decompressed to XML first and then to JSON." \cite{CBMS2020}. To eliminate network-related delays from the RTT measurements, the domain name service, the AS and the PROSPECD file are hosted on the same server with the following configuration: \\ CPU: Intel®6 Xeon 1241-v3 @ 3.9 GHz; RAM: 32GB DDR3 @ 2400 MHz; Network Interface: Intel® 1000Base-T; \\ OS: Microsoft® Windows® 10 Pro, 64 Bit; \\ Software: ApacheBench\textsuperscript{\textregistered}, version 2.3; Node.js\textsuperscript{\textregistered}\footnote{We do not imply sponsorship or endorsement by Node.js Foundation \cite{nodejstrademark} }, v10.16.3. \\ As we see in Fig.\ref{PROSPECD-evaluation}, the average RTT for 100 concurrent threads is up to 5.8\% smaller than for one thread. Having 100 concurrent threads in ApacheBench® makes 100 data requests open in a single experiment with 1000 total requests. "Node.js® is a single threaded language which in background uses multiple threads to execute asynchronous code." \cite{node-multithreading} Compared to a baseline solution, where encrypted data are stored in a JSON file, PROSPECD adds 324\% performance overhead for retrieving 0.5 kilobytes of data and only 6\% overhead for retrieving 421.1 kilobytes. However, compared to an encrypted JSON file, PROSPECD offers more protection layers for data, including on-the-fly key generation, so that keys are not stored anywhere, and an attribute-based access control. Furthermore, PROSPECD is implemented as a spreadsheet file and can be opened in Microsoft\textsuperscript{\textregistered} Excel, which would allow to visualize data and run data analysis. \begin{figure} \centering \includegraphics[width=8.4cm]{figures/Evaluation-PROSPECD.png} \caption{PROSPECD Data Request Round-Trip Time.} \label{PROSPECD-evaluation} \end{figure} \end{comment} \section{Conclusions} \label{conclusion} In this paper, we presented a novel detection system based on an LSTM model for the detection of both traditional and dictionary-based DGA generated domains using the character-by-character approach. Our experimental findings show that the LSTM-based model can detect malicious domains with a trivial margin of error. However, machine learning models are unable to learn the characteristic behaviors of DGA-based malicious domains if there are new or never-seen-before data in the testing dataset. In this study, we highlight this issue with an adversarial manipulation using different data perturbation cases. According to our findings, newly generated domains using the proposed perturbation approach could not be detected by the DGA classifier. After we trained the model with the augmented training dataset, including adversarial samples, the experimental results show that the LSTM model was able to detect previously unobserved DGA families. We store malicious domain names, detected by our model, in a Protected Spreadsheet Container with Data (PROSPECD). It provides data confidentiality and integrity, as well as origin integrity, role-based and attribute-based access control. PROSPECD protects the domain names in transit and at rest against adversarial access and modifications. \bibliographystyle{IEEEtran}
{'timestamp': '2021-01-05T02:19:58', 'yymm': '2101', 'arxiv_id': '2101.00521', 'language': 'en', 'url': 'https://arxiv.org/abs/2101.00521'}
arxiv
\section{Introduction} Named entity recognition (NER) is a fundamental task which is often used as a first step in numerous natural language processing (NLP) tasks, including relation extraction\cite{li2016biocreative,ren2017cotype} and knowledge graph construction\cite{lin2015learning,luan-etal-2018-multi}. Most existing NER approaches such as neural network-based methods\cite{lample-etal-2016-neural,ma-hovy-2016-end,liu2018empower}, often require a large amount of training data (annotated entity spans and types) to achieve satisfactory performance. It is clearly expensive, and sometimes impossible, to obtain a large amount of annotated data in a new domain for the NER task. Under such circumstance, low-resource NER has attracted much deserved attention recently, which aims to build reliable NER systems using limited annotated data. Many approaches have been proposed to address low-resource NER. Early works are mainly based on hand-crafted rules\cite{collobert2011natural,yang2012extracting,luo2015joint}, but they suffer from limited performance in practice. More recently, researches on low-resource NER focus on learning information and knowledge from extra domain-specific resources to improve the NER performance. According to the required resources, they can be divided into two types: learning-based methods\cite{luan-etal-2018-multi,zhou-etal-2019-dual,shang-etal-2018-learning} and domain-specific pre-training methods\cite{beltagy-etal-2019-scibert,lee2020biobert}. Learning-based methods belong to supervised learning in some sense, such as transfer learning, multi-task learning and distantly-supervised learning, which leverage information and knowledge provided by external lexicons and knowledge bases. In fact, it needs extensive amount of experts effort to construct such resources. Unlike learning-based methods, domain-specific pre-training methods adopt transfer-based pre-training (unsupervised learning) on large amount of in-domain corpora to enable knowledge transfer. Domain-specific pre-training methods need less manual effort, but GPU clusters or TPUs (quite expensive) are required to speed up the training process. Both kinds of methods utilize extra knowledge, either from experts or in-domain corpora, which have been shown to be effective for low-resource NER. \begin{table*}[t] \caption{Summarization of the existing low-resource NER methods.} \label{tal:resources} \setlength{\tabcolsep}{9pt} \centering \begin{tabular}{l|c|c} \hline \multicolumn{1}{c|}{Methods} & \multicolumn{1}{c|}{Required resources} & \multicolumn{1}{c}{Limitations} \\ \hline Transfer learning\cite{zhou-etal-2019-dual,chaudhary-etal-2019-little} & Parallel corpora, dictionary & \multirow{3}{*}{\begin{tabular}[c]{@{}c@{}}Difficult to obtain and\\ expensive to construct\end{tabular}} \\ Multi-task learning\cite{luan-etal-2018-multi,wadden-etal-2019-entity,eberts2019span} & Annotations for other tasks & \\ Distantly supervised learning\cite{liu-etal-2019-knowledge-augmented,fries2017swellshark,shang-etal-2018-learning} & Knowledge bases, lexicons & \\ \hline Domain-specific pre-training\cite{beltagy-etal-2019-scibert,lee2020biobert} & Pre-trained language models & \begin{tabular}[c]{@{}c@{}}Time-consuming and\\ expensive to pre-train\end{tabular} \\ \hline \end{tabular} \end{table*} Most existing methods for low-resource NER are summarized in Table~\ref{tal:resources}. From the table, we observe that these methods highly dependent on the availability of domain-specific resources. However, these resources are often not available, meanwhile it's difficult and expensive to construct them, which has become a key obstacle to wider adoption. For example, it's easy to obtain a general domain knowledge base (like Wikipedia), but we could hardly find a publicly financial knowledge base. In fact, it requires large amounts of experts effort and money to build a domain-specific knowledge base. To tackle the problem, we propose a novel robust and domain-adaptive approach \textsc{RDANER}\xspace for low-resource NER only using cheap and easily obtainable resources. Specifically, the proposed approach consists of two steps: transformer-based language model fine-tuning (LM fine-tuning) and bootstrapping. Here, LM refers specifically to the transformer-based language model. Firstly, we fine-tune a general domain pre-trained LM on in-domain corpora to make it fit on the target domain. Fortunately, it's easy to obtain a general domain pre-trained LM and a large amount of unannotated in-domain corpora. Then we perform a bootstrapping process, starting from an initial NER model trained on the small fully-annotated seed data, and then we use it to predict on an unannotated corpus which is further used to train the model iteratively until convergence. Our proposed approach alleviates the requirements of difficultly obtainable domain-specific resources, and builds reliable NER systems under low-resource conditions, which is a trade-off between effectiveness and efficiency. To evaluate our proposed approach, we conduct low-resource experiments on three benchmark datasets in two challenging domains: computer science and biomedical. Extensive experiments demonstrate that our proposed approach is not only effective but also efficient. When only using cheap and easily obtainable resources, our approach outperforms baselines with an average improvement of 3.5 F1. Beside, the proposed approach achieves competitive performance against the state-of-the-art methods which utilize difficultly obtainable domain-specific resources. \section{Related Work} Named entity recognition (NER) has been studied widely for decades. Traditionally, NER is concerned with identifying general named entities, such as person, location, and organization names in unstructured text. Nowadays, researches have been extended to many specific domains, including biomedical, financial and academic. Most early NER works are based on hand-crafted rules designed by experts\cite{collobert2011natural,yang2012extracting,luo2015joint}. Recently, neural network-based NER models\cite{ma-hovy-2016-end,lample-etal-2016-neural,liu2018empower} have yielded great improvement over the early features-based models, meanwhile, requiring little feature engineering and domain knowledge\cite{yang2012extracting,ma-hovy-2016-end}. The biggest limitation of such neural models is that they highly dependent on large amounts of annotated data. As a result, the performance of these models degrades dramatically in low-resource settings. Low-resource NER, which aims to build reliable NER systems, has attracted much attention in recent times. Researches on low-resource NER mainly focus on utilizing extra domain-specific resources to improve the performance. There are mainly two types methods: learning-based methods and domain-specific pre-training methods. We introduce the related works of them respectively as follows. \subsection{Learning-based Methods} Learning-based methods for low-resource NER assume some domain-specific resources are available, such as lexicons, parallel corpora and knowledge bases. These methods can be divided into three types: transfer learning (TL), multi-task learning (MTL) and distantly-supervised learning (DSL). TL has been extensively used for improving low-resource NER\cite{li2012joint, yang2017transfer}. Most of them focus on transferring cross-domain knowledge into NER, which rely on annotation projection methods where annotations in high-resource domains are projected to the low-resource domains leveraging parallel corpora\cite{chen2010jointly, ni-etal-2017-weakly} and shared representation\cite{zhou-etal-2019-dual,chaudhary-etal-2019-little,cao-etal-2019-low}. In fact, many TL methods are designed for general domain NER tasks, because it is easier to obtain parallel corpora or bilingual dictionaries from the general domain than from a specific domain. Similarly, MTL utilizes knowledge from extra annotations provided by the dataset, and adopts jointly training on multiple tasks to help improve NER performance\cite{luan-etal-2018-multi,eberts2019span,wadden-etal-2019-entity}. Different from TL, MTL aims at improving the performance of all the tasks instead of low-resource task only. The requirements of MTL methods for low-resource NER are manual-labeled annotations for other tasks. Another trend for better low-resource NER performance is DSL, which has attracted many attentions to alleviate human efforts. DSL methods use domain-specific dictionaries and knowledge bases to generate large mount of weakly-annotated data. SwellShark\cite{fries2017swellshark} and AutoNER\cite{shang-etal-2018-learning} use dictionary matching for named entity span detection. Reference\cite{mathew2019biomedical} combines bootstrapping and weakly-annotated data augmentation by using a reference set. Their approaches work well only when domain-specific resources are available. \subsection{Domain-specific Pre-training Methods} Transformer-based pre-training have been shown to be powerful for NLP tasks\cite{devlin2018bert,yang2019xlnet}, including low-resource NER. But most publicly pre-trained LMs (like GPT, \textsc{Bert}\xspace) are trained on general domain corpora, they often yields unsatisfactory results in many specific domains. A solution for this problem is domain-specific pre-training, which trains LMs on in-domain corpora. \textsc{SciBert}\xspace\cite{beltagy-etal-2019-scibert} and \textsc{BioBert}\xspace\cite{lee2020biobert} are two domain-specific \textsc{Bert}\xspace variants for scientific text and biomedical text respectively, showing powerful performance in corresponding domains. Different from learning-based methods, pre-training doesn't dependent on the resources required experts effort to construct. Unfortunately, it is quite expensive to pre-train LMs from scratch, needing GPU clusters or TPUs to speed up the training processes. Most existing works heavily rely on difficultly obtainable domain-specific resources, requiring either experts effort or high-performance hardware. However, they are often not available or cost lots of money to construct them. Without corresponding domain-specific resources, it's hard for these methods to be applied in a new domain. To solve this problem, we propose a novel robust and domain-adaptive approach \textsc{RDANER}\xspace for low-resource NER, which only uses cheap and easily obtainable researches. The most related works to ours are semi-supervised methods, which have been explored to further improve the accuracy by either augmenting labeled datasets or bootstrapping techniques\cite{he2017unified,chaudhary-etal-2019-little,mathew2019biomedical}. Reference\cite{chaudhary-etal-2019-little} uses a combination of cross-lingual transfer learning and active learning for bootstrapping low-resource entity recognizers. Reference\cite{mathew2019biomedical} combines bootstrapping and weakly-annotated data augmentation by using an external lexicon to improve NER performance. Different from \cite{chaudhary-etal-2019-little,mathew2019biomedical}, our proposed approach assumes no parallel corpora or lexicons in the target domain. We describe our approach \textsc{RDANER}\xspace in detail as follows. \section{Approach: \textsc{RDANER}\xspace} For a specific low-resource NER task, we assume to have (1) a small fully-annotated seed dataset $\mathcal{D}_s$ that has every token tagged by entity type, (2) a small in-domain corpus $\mathcal{D}_c$, which is used to generate weakly-annotated data, (3) a general domain pre-trained language model $\mathbf{LM}$ and (4) a large-scale in-domain corpus $\mathcal{C}_T$ of the target domain $T$. As noted in the introduction, \textsc{RDANER}\xspace consists of two processes: LM fine-tuning and the bootstrapping. Fig.~\ref{fig:architecture} shows the architecture of the proposed approach. We will describe each of them in follow sections. \begin{figure}[!t] \centering \includegraphics[width=0.48\textwidth]{./figures/architecture.pdf} \caption{Architecture of \textsc{RDANER}\xspace: LM fine-tuning + Bootstrapping.} \label{fig:architecture} \end{figure} \subsection{LM Fine-tuning} Given a general domain pre-trained language model $\mathbf{LM}$ and a domain-specific corpus $\mathcal{C}_T$, our goal is to make $\mathbf{LM}$ fit on the target domain $T$. In this work, $\mathbf{LM}$ is \textsc{Bert}\xspace, and we follow the work of pre-training \textsc{Bert}\xspace\cite{devlin2018bert}. Before feeding word sequences into \textsc{Bert}\xspace, 15\% of the words in each sequence are replaced with a {\tt [MASK]} token at random. \textsc{Bert}\xspace attempts to predict the original value of the masked words, based on the context provided by the other non-masked words in the sequence. The objective is masked language modeling (MLM) cross-entropy\cite{devlin2018bert}, which measures the likelihood of predictions for masked words. When fine-tuning has completed, we get a \textsc{Bert}\xspace variant, $\textsc{Bert}\xspace_T$. \subsection{Bootstrapping} Bootstrapping is proposed to further improve the accuracy. First, we train an initial NER model $\mathcal{M}_0$ using the small seed dataset $\mathcal{D}_s$. We use $\textsc{Bert}\xspace_T$ as the word-level encoder, and a linear-chain CRF after a softmax layer. For an input sequence $ \mathbf{X} = (\mathbf{x}_1, \mathbf{x}_2, ..., \mathbf{x}_n) $ and a sequence of tag predictions $ \mathbf{y} = (y_1, y_2, ..., y_n) $, $\textsc{Bert}\xspace_T$ converts $\mathbf{x}_i$ into a fixed-length vector $\mathbf{w}_i$, and outputs the probability distributions $\mathbf{h}$ on $\mathbb{R}^K$: \begin{equation} \mathbf{h}= \softmax(\mathbf{w}) \end{equation} where $ \mathbf{w} = (\mathbf{w}_1, \mathbf{w}_2, ..., \mathbf{w}_n) $, $K$ is the number of tags and depends on the the number of classes and on the tagging scheme. The linear-chain CRF model defines the posterior probability of $\mathbf{y}$ given $\mathbf{X}$ to be: \begin{equation} p(\mathbf{y}|\mathbf{X};\mathbf{A}) = \frac{1}{Z(\mathbf{X})}\exp \left(\sum_{k=0}^{n} h^{k}(y_{k};\mathbf{X}) + \sum_{k=1}^{n-1} \mathbf{A}_{y_k,y_{k+1}} \right) \end{equation} where $Z(\mathbf{X})$ is a normalization factor over all possible tags of $\mathbf{X}$, $h^k(y_k;\mathbf{X})$ indicates the probability of taking the $y_k$ tag at position $k$, $y_0$ and $y_{n+1}$ are start and end tags. $\mathbf{A}$ is the transfer matrix, and $\mathbf{A}_{y_k,y_{k+1}}$ means the probability of a transition from tag states $y_k$ to $y_{k+1}$. The most likely tag sequence of $\mathbf{X}$ is represented as follows: \begin{equation} \mathbf{y}^{*} = \arg\max_{\mathbf{y} \in \mathbb{R}^K} p(\mathbf{y}|\mathbf{X};\mathbf{A}) \end{equation} $\mathbf{A}$ is learnt through the maximum log-likelihood estimation, which maximizes the log-likelihood function $\mathbb{L}$ of training set sequences in seed dataset $\mathcal{D}_s$: \begin{equation} \mathbb{L}(\mathcal{D}_s, \mathbf{A}) = \sum_{m=1}^{M}\log p(\mathbf{y^{(m)}}|\mathbf{X^{(m)}};\mathbf{A}) \end{equation} where $M$ is the size of the fully-annotated seed dataset $\mathcal{D}_s$. Then, we use the initial NER model $\mathcal{M}_0$ to assign labels on $\mathcal{D}_c$, and get a weakly-annotated dataset $\mathcal{D}^{*}_{c}$. Moreover, we combine $\mathcal{D}_{s}$ with $\mathcal{D}^{*}_{c}$ and get an augmented dataset. Different from training, we set thresholds $\boldsymbol{\theta}$ to filter tags with low probabilities outputted by the softmax layer. Finally, we iteratively train the NER model with $\mathcal{D}^{*}_{c}$, until the model has achieved an acceptable level of accuracy, or until the maximum number of iterations. Algorithm\ref{alg:method} show the overall process of assigning weakly labels, where {\tt O} stands for none tag. \begin{algorithm}[h] \caption{Weakly labels assignment} \label{alg:method} \SetAlgoNoLine \KwIn{Annotated seed data ($\mathcal{D}_{s}$)} \KwIn{Unannotated corpus ($\mathcal{D}_{c}$)} \KwOut{NER model ($\mathcal{M}_{K}$)} Train NER model $\mathcal{M}_0$ on $\mathcal{D}_{s}$ \\ \For{i in 1 \ldots K}{ $\mathcal{D}^{(i-1)*}_{c} \gets$ Predict using $\mathcal{M}_{i-1}$\\ $\mathcal{D}^{(i-1)}_{c} \gets$ Relabel $\mathcal{D}^{(i-1)*}_{c}$ \\ \textbf{s.t.}\\ \If{ $p(\mathbf{y}^{*}_{k}) < \theta$}{ $ \mathbf{y}^{*}_{k} \gets$ {\tt O} } Train model $\mathcal{M}_{i}$ on $\mathcal{D}_{s}$ + $\mathcal{D}^{(i-1)}_{c}$ } \Return{$\mathcal{M}_{K}$} \end{algorithm} \section{Experiments} We conduct experiments on three benchmark datasets in two challenging domains to evaluate and compare our proposed approach with state-of-the art methods. We further investigate the effectiveness of LM fine-tuning and the bootstrapping process respectively. \subsection{Datasets} \begin{itemize} \item SciERC\cite{luan-etal-2018-multi} annotates entities, their relations, and coreference clusters. Four relations are annotated. \item BC5CDR\cite{li2016biocreative} is from the most recent BioCreative V Chemical and Disease Mention Recognition task. Two relations are annotated. \item NCBI-Disease\cite{dougan2014ncbi} focuses on Disease Name Recognition. Only 1 relation is annotated. \end{itemize} Table~\ref{tal:datasets} gives the statistics of the datasets used in this work. To be directly comparable with previous works, we used the official train/dev/test set splits on all datasets. \begin{table}[t!] \centering \caption{Datasets overview.} \label{tal:datasets} \begin{tabular}{c|ccc} \toprule Seed & \textsc{S}ci-\textsc{erc}\xspace & BC5CDR & NCBI-Disease \\ \hline 10\% & 189 & 485 & 626 \\ 20\% & 359 & 960 & 1,171\\ 30\% & 540 & 1,348 & 1,737\\ 50\% & 895 & 2,319 & 2,943\\ 100\% & 1,857& 4,611 & 5,825 \\ \hline Domain & CS & Biomedical & Biomedical\\ \hline Entity types & 6 & 2& 1\\ \bottomrule \end{tabular} \end{table} \subsection{Cheap and Easily Obtainable Resources} \begin{itemize} \item General Domain Pre-trained LM: We use $\bert_{\textsc{Base}}$\xspace\footnote{\url{https://github.com/google-research/bert}}, which trained on a general domain corpora including English Wikipedia and BooksCorpus. \item In-domain Corpora: We construct two in-domain corpora, $\mathcal{CS}$\xspace and $\mathcal{BIO}$\xspace, to fine-tine $\bert_{\textsc{Base}}$\xspace. The $\mathcal{CS}$\xspace consists 40k papers from AI conference proceedings and 87k papers in AI community from arXiv. The $\mathcal{BIO}$\xspace consists 200k abstracts which are randomly sampled from PubMed. \end{itemize} \subsection{Evaluation Metric} Following previous works\cite{zhou-etal-2019-dual,beltagy-etal-2019-scibert,chaudhary-etal-2019-little}, the micro-averaged F1 score is used as the evaluation metric. \subsection{Baselines} We evaluate our proposed approach \textsc{RDANER}\xspace with $\bert_{\textsc{Base}}$\xspace, which is the strongest baseline in our work. Then, we compare \textsc{RDANER}\xspace against two domain-specific \textsc{Bert}\xspace variants to show the effectiveness of LM fine-tuning. Furthermore, we show the performance of bootstrapping process and compare \textsc{RDANER}\xspace with state-of-the art learning-based methods which use difficultly obtainable domain-specific resources. More details are as follows. \begin{itemize} \item $\bert_{\textsc{Base}}$\xspace\cite{devlin2018bert} is a transformer-based language model which has been shown to be powerful for general domain NER tasks. \item \textsc{SciBert}\xspace\cite{beltagy-etal-2019-scibert} is trained on scientific corpora including 18\% papers from the computer science domain and 82\% from the broad biomedical domain. \item \textsc{BioBert}\xspace\cite{lee2020biobert} is initialized with \textsc{Bert}\xspace, then fine-tuned on PubMed abstracts and PMC full text articles. \item DyGIE++\cite{wadden-etal-2019-entity} has achieved best performance on NER, especially on \textsc{S}ci-\textsc{erc}\xspace dataset. However, DyGIE++ requires extra annotations including relation, coreference and event labels. \item SpERT\cite{eberts2019span} is an attention model for span-based joint entity and relation extraction. It requires relation annotations for training. \item SwellShark\cite{fries2017swellshark} is an excellent distantly supervised model in the biomedical domain, which needs no human annotated data. However, it requires extra expert effort for designing effective regular expressions. \item AutoNER\cite{shang-etal-2018-learning} circumvents the requirements of extra human effort, however, it needs large high-quality dictionaries to achieve satisfactory performance. \end{itemize} \subsection{Implementation Details} Our model is implemented with AllenNLP\footnote{\url{https://github.com/allenai/allennlp}}. For all pre-trained \textsc{Bert}\xspace variants, we use PyTorch version of them and the original code released publicly. All experiments are conducted on a single GTX 1080Ti GPU (12GB). We fine-tune $\bert_{\textsc{Base}}$\xspace on two large-scale in-domain corpora: $\mathcal{CS}$\xspace and $\mathcal{BIO}$\xspace using transformers library\footnote{\url{https://github.com/huggingface/transformers}}, and get two \textsc{Bert}\xspace variants $\bert_{\textsc{CS}}$\xspace and $\bert_{\textsc{BIO}}$\xspace respectively. We initialize $\bert_{\textsc{CS}}$\xspace and $\bert_{\textsc{BIO}}$\xspace with weights from $\bert_{\textsc{Base}}$\xspace, and we use the same vocabulary as $\bert_{\textsc{Base}}$\xspace. Different from original \textsc{Bert}\xspace code, we set a maximum sentence length of 120 tokens for $\mathcal{CS}$\xspace corpus and 80 tokens for $\mathcal{BIO}$\xspace corpus, which are in line with most sentence length in the corresponding corpus. Both of them are fine-tuned for 1 epoch, and we don't continue train the model allowing longer sentence length as \textsc{Bert}\xspace does. To simulate a limited annotated data setting, we randomly select subsets of training data as seed training datasets with varying data ratios at 10\%, 20\%, 30\%, 50\% and 100\%. The remaining training data simulate small in-domain corpora. Numbers of sentences of each ratio are shown in Table~\ref{tal:datasets}. The maximum number of iterations is set to 10, and we take the average of last 5 iterations as the result of each model. In order to reduce training time, we set different epochs for different seed training datasets, epochs decrease as seed increase. To investigate the effectiveness of the proposed approach, all parameters are fine-tuned on the dev set and we do not perform extensive hyperparameter search. For all compared methods, we use the code published in their papers, and follow the same experimental settings. We add a CRF layer after the softmax layer for all \textsc{Bert}\xspace variants. \section{Results and Discussion} In this section, we evaluate our proposed approach from the following aspects. First, we evaluate the proposed approach against $\bert_{\textsc{Base}}$\xspace to investigate the effectiveness of LM fine-tuning process. Second, we show the performance of the bootstrapping process and investigate the impact of the threshold $\theta$. Furthermore, we compare our proposed approach with domain-specific \textsc{Bert}\xspace variants and state-of-the-art learning-based methods which use difficultly obtainable domain-specific resources. \begin{table} \caption{NER F1 scores of LM fine-tuning on \textsc{S}ci-\textsc{erc}\xspace, BC5CDR and NCBI-Disease with varying training data ratios. }\label{tal:results} \centering \begin{tabular}{c|c|ccc} \toprule Dataset & Seed & $\bert_{\textsc{Base}}$\xspace & LM fine-tuning & \textsc{RDANER}\xspace \\ \hline \multirow{5}{*}{\textsc{S}ci-\textsc{erc}\xspace} & 10\% & 54.07 & 57.39 & \textbf{58.83} \\ & 20\% & 57.15 & 61.64 & \textbf{62.28} \\ & 30\% & 60.09 & 63.33 & \textbf{64.61} \\ & 50\% & 62.25 & 64.73 & \textbf{65.48} \\ & 100\% & 65.24 & 68.46 & \textbf{68.96} \\ \hline \multirow{5}{*}{BC5CDR} & 10\% & 74.21 & 76.61 & \textbf{78.25} \\ & 20\% & 78.43 & 80.51 & \textbf{82.35} \\ & 30\% & 79.39 & 81.70 & \textbf{83.55} \\ & 50\% & 82.19 & 84.25 & \textbf{85.26} \\ & 100\% & 85.61 & 86.87 & \textbf{87.38} \\ \hline \multirow{5}{*}{NCBI-Disease} & 10\% & 73.03 & 76.09 & \textbf{78.14} \\ & 20\% & 79.56 & 80.20 & \textbf{83.46} \\ & 30\% & 83.79 & 84.37 & \textbf{85.46} \\ & 50\% & 84.88 & 85.70 & \textbf{86.80} \\ & 100\% & 86.37 & 87.49 & \textbf{87.89} \\ \bottomrule \end{tabular} \end{table} \subsection{Effectiveness of LM Fine-tuning} Table~\ref{tal:results} shows the test set evaluation results of LM fine-tuning on the three datasets. The reported results are the mean across five different runs with different random seeds. As introduced before, we use $\bert_{\textsc{CS}}$\xspace for \textsc{S}ci-\textsc{erc}\xspace dataset, $\bert_{\textsc{BIO}}$\xspace for BC5CDR and Disease datasets. We observe that LM fine-tuning consistently outperform $\bert_{\textsc{Base}}$\xspace on all three datasets. More specifically, LM fine-tuning gains an average improvement of 3.35 F1 on \textsc{S}ci-\textsc{erc}\xspace, 2.02 F1 on BC5CDR and 1.24 F1 on NCBI-Disease. It indicates that LM fine-tuning on in-domain corpora is effective and domain-adaptive. We also note that there is performance gap degradation when training data increase for each dataset, which indicates that LM fine-tuning works better on less training data. This is due to the text representation has greater impact on NER models when less training data are provided. \subsection{Performance of Bootstrapping} Table~\ref{tal:results} shows the performance of the \textsc{RDANER}\xspace on the three datasets. \textsc{RDANER}\xspace consists two processes: LM fine-tuning and bootstrapping. We observe that the bootstrapping process can always further improve the accuracy of NER models, which indicates the bootstrapping process is reliable. Based on LM fine-tuning, the bootstrapping process gains an average improvement of 1.29 F1. Using only 50\% of training data, \textsc{RDANER}\xspace achieves reasonable performance, which $\bert_{\textsc{Base}}$\xspace needs 100\% of training data to achieve. \begin{table*}[t!] \caption{Performance of iterative bootstrapping process using 10\% training data. (P: Precision, R: Recall)} \label{tal:iterations} \centering \setlength{\tabcolsep}{9.5pt} \small{ \begin{tabular}{@{}cccccccccccc@{}} \toprule & \multicolumn{3}{c}{\textsc{S}ci-\textsc{erc}\xspace} && \multicolumn{3}{c}{BC5CDR} && \multicolumn{3}{c}{NCBI-Disease} \\ \cmidrule{2-4} \cmidrule{6-8} \cmidrule{10-12} Iter & P & R & F1 && P & R & F1 && P & R & F1\\ \midrule 0 & 53.84 & 61.44 & 57.39 && 77.42 & 75.82 & 76.61 && 75.62 & 76.56 & 76.09 \\ \hline 1 & 55.26 & 61.84 & 58.36 && 76.87 & 77.40 & 77.13 && 76.72 & 77.56 & 77.14 \\ 2 & 55.34 & 61.62 & 58.31 && 77.13 & 78.65 & 77.88 && 77.23 & 77.71 & 77.47 \\ 3 & 55.00 & 62.76 & 58.63 && 78.65 & 76.88 & 77.75 && 76.43 & 77.71 & 77.07 \\ 4 & 55.18 & 62.10 & 58.43 && 78.26 & 77.28 & 77.76 && 75.22 & 80.31 & 77.68 \\ 5 & 55.14 & 62.22 & 58.47 && 78.41 & 77.14 & 77.77 && 77.04 & 77.60 & 77.32 \\ 6 & 55.69 & 62.64 & 58.96 && 77.14 & 77.77 & 77.45 && 78.12 & 77.25 & 77.68 \\ 7 & 55.30 & 63.00 & 58.90 && 77.40 & 77.13 & 77.26 && 78.59 & 76.88 & 77.73 \\ 8 & 55.23 & 62.16 & 58.49 && 77.77 & 78.26 & 78.01 && 78.16 & 77.19 & 77.67 \\ 9 & 56.24 & 62.28 & 59.11 && 76.88 & 77.75 & 77.31 && 78.06 & 77.81 & 77.93 \\ 10 & 55.69 & 63.18 & \textbf{59.20} && 77.75 & 78.41 & \textbf{78.08} && 80.33 & 76.56 & \textbf{78.40} \\ \bottomrule \end{tabular} } \end{table*} In order to get a further understanding of the bootstrapping process, the iteratively training process with 10\% of the training data is shown in Table~\ref{tal:iterations}. Iteration 0 is the initial model trained on seed dataset, and we use the model to predict labels for unknown tokens repeatedly, which yields a jump in performance in the first iteration (Iter 1), since the predicted labels are informative. We observe that the bootstrapping process gains an average improvement of 1.86 F1 on initial models across the three datasets. The improvement achieved on \textsc{S}ci-\textsc{erc}\xspace and BC5CDR is mainly due to the gain in recall. On the contrary, the improvement achieved on NCBI-Disease is mainly due to the gain in precision. Because there is only 1 type of entity needed to be recognized on NCBI-Disease dataset, NER on NCBI-Disease is more likely to achieve a high precision. \begin{figure*}[tb] \centering \subfigure[\textsc{S}ci-\textsc{erc}\xspace]{ \includegraphics[width=0.32\textwidth]{./figures/SciERC.pdf}} \subfigure[BC5CDR]{ \includegraphics[width=0.32\textwidth]{./figures/BC5CDR.pdf}} \subfigure[NCBI-Disease]{ \includegraphics[width=0.32\textwidth]{./figures/NCBI-Disease.pdf}} \caption{F1 scores curves on development set vs. thresholds of label assignment probability.} \label{fig:thresholds} \end{figure*} \textbf{Impact of $\boldsymbol{\theta}$:} Fig.~\ref{fig:thresholds} shows the F1 scores curves on development sets with different thresholds of label assignment probability. This experiment is to find the optimal thresholds for different ratios of training data. Theoretically, increasing the threshold does result in a lower number of false positives, leading to higher precision. Instead, lower thresholds lead to higher recalls. For \textsc{S}ci-\textsc{erc}\xspace, slowly increasing the threshold results in a slightly more balanced F1 measure. But the F1 scores start decreasing when precision is higher than a threshold. We observe that the less training data, the smaller the optimal thresholds, indicating recall has a greater impact on F1 under lower resources. Different from \textsc{S}ci-\textsc{erc}\xspace, curves on BC5CDR and NCBI-Disease are more stable, increasing the threshold does little impact on F1 scores except using 10\% of the training data. This demonstrates that entity annotated by models have a very high accuracy. We attribute this to the fact that BC5CDR and NCBI-Disease have fewer entity types, resulting in high accuracy of classification. \subsection{Comparison with Domain-specific Pre-training Methods} \begin{table}[t!] \caption{NER F1 scores of domain-specific \textsc{Bert}\xspace variants on \textsc{S}ci-\textsc{erc}\xspace, BC5CDR and NCBI-Disease with varying training data ratios.}\label{tal:domain-specific} \centering \begin{tabular}{c|c|ccc} \toprule Dataset & Seed & \textsc{SciBert}\xspace & \textsc{BioBert}\xspace & \textsc{RDANER}\xspace \\ \hline \multirow{5}{*}{\textsc{S}ci-\textsc{erc}\xspace} & 10\% & 57.59 & 57.68 & \textbf{58.83} \\ & 20\% & 62.05 & 61.84 & \textbf{62.28} \\ & 30\% & \textbf{65.63} & 63.35 & 64.61 \\ & 50\% & \textbf{66.95} & 64.66 & 65.48 \\ & 100\% & 68.55 & 67.89 & \textbf{68.96} \\ \hline \multirow{5}{*}{BC5CDR} & 10\% & 81.92 & \textbf{83.56} & 78.25 \\ & 20\% & 84.85 & \textbf{85.57} & 82.35 \\ & 30\% & 86.14 & \textbf{86.87} & 83.55 \\ & 50\% & 87.50 & \textbf{87.94} & 85.26 \\ & 100\% & \textbf{90.01} & 89.11 & 87.38 \\ \hline \multirow{5}{*}{NCBI-Disease} & 10\% & 80.82 & \textbf{81.08} & 78.14 \\ & 20\% & 83.69 & \textbf{85.82} & 83.46 \\ & 30\% & 86.35 & \textbf{87.02} & 85.46 \\ & 50\% & 87.37 & \textbf{88.53} & 86.80 \\ & 100\% & 88.57 & \textbf{89.36} & 87.89 \\ \bottomrule \end{tabular} \end{table} \begin{table}[t!] \caption{Resources required by domain-specific \textsc{Bert}\xspace variants and \textsc{RDANER}\xspace. $\rdaner_{\textsc{CS}}$\xspace use $\bert_{\textsc{CS}}$\xspace and $\rdaner_{\textsc{Bio}}$\xspace use $\bert_{\textsc{BIO}}$\xspace as the text encoder. (B: billion, M: million; d: day, h: hour)} \label{tal:pre-trained-models} \centering \setlength{\tabcolsep}{5.5pt} \begin{tabular}{c|cc|cc} \toprule Variants & \textsc{SciBert}\xspace & \textsc{BioBert}\xspace & $\rdaner_{\textsc{CS}}$\xspace & $\rdaner_{\textsc{Bio}}$\xspace \\ \hline Tokens & 3.2B & 18.0B & 17.2M & 37.7M \\ GPU Time & 42d & 254d & \textbf{2.5h} & \textbf{3.5h}\\ \bottomrule \end{tabular} \end{table} Table~\ref{tal:domain-specific} shows the performance of domain-specific \textsc{Bert}\xspace variants on the three datasets. We observe that \textsc{SciBert}\xspace and \textsc{BioBert}\xspace perform well on their corresponding domains. \textsc{SciBert}\xspace achieves satisfactory F1 scores on \textsc{S}ci-\textsc{erc}\xspace (computer science), and \textsc{BioBert}\xspace performs best on BC5CDR and NCBI-Disease (biomedical). Unfortunately, it is very expensive to obtain such domain-specific \textsc{Bert}\xspace variants because the training processes are computationally expensive, which require high-performance hardware. As reported in previous works\cite{beltagy-etal-2019-scibert,lee2020biobert}, it takes 1 week to train \textsc{SciBert}\xspace from scratch on a single TPU v3 with 8 cores, and 23 days to fine-tune \textsc{BioBert}\xspace on eight NVIDIA V100 (32GB) GPUs. Resources required by domain-specific \textsc{Bert}\xspace variants and \textsc{RDANER}\xspace are summarized in Table~\ref{tal:pre-trained-models}. To facilitate comparison, GPU time is converted roughly to the time to train on a single GTX 1080Ti GPU (12GB). We note that it is very time-consuming to train a domain-specific \textsc{Bert}\xspace variant from scratch on a single GPU, about 4 months or more. However, \textsc{RDANER}\xspace costs only several hours and achieves satisfactory performance. It shows that our proposed approach obtains a trade-off between effectiveness and efficiency. Compared with domain-specific \textsc{Bert}\xspace variants, there is only a performance drop of 1.87 F1 scores on average for \textsc{RDANER}\xspace. That is totally acceptable as it is much cheaper and more efficient. Surprisingly, \textsc{RDANER}\xspace outperforms \textsc{SciBert}\xspace on \textsc{S}ci-\textsc{erc}\xspace when using 10\%, 20\%, 100\% of the training data. Note that \textsc{SciBert}\xspace is the best \textsc{Bert}\xspace variant in computer science domain currently. We attribute this to the fact that \textsc{S}ci-\textsc{erc}\xspace is a small dataset with only 1,857 annotated sentences. Unfortunately, bootstrapping is prone to over-fitting on small dataset. What's more, NER on \textsc{S}ci-\textsc{erc}\xspace is very challenging because it consists 6 entity types and the definitions of entities are ambiguous, such as \textit{Other Scientific Term} and \textit{Method}. Unlike \textsc{S}ci-\textsc{erc}\xspace, BC5CDR and NCBI-Disease are two larger datasets with no more than 2 entity types, thus NER on the two biomedical datasets is much easier. \textsc{BioBert}\xspace, as the best \textsc{Bert}\xspace variant in biomedical domain currently, almost beats all other \textsc{Bert}\xspace variants. Although there is still a significant gap between \textsc{RDANER}\xspace and \textsc{BioBert}\xspace, \textsc{RDANER}\xspace obtain satisfactory F1 scores costing less money and time. Furthermore, we observe that \textsc{SciBert}\xspace and \textsc{BioBert}\xspace perform similarly on the three datasets. The reason is that \textsc{SciBert}\xspace is trained on a corpus 82\% from biomedical domain and 18\% from computer science. It indicates that introducing large-scale in-domain unannotated text for pre-training and fine-tuning can significantly improve performance. In some sense, \textsc{BioBert}\xspace is an enhanced version of $\bert_{\textsc{BIO}}$\xspace , and the difference between them is that \textsc{BioBert}\xspace uses a much larger corpus than $\bert_{\textsc{BIO}}$\xspace (18B tokens vs. 37.7M tokens). LM fine-tuning gains more improvement with larger in-domain corpora, and we can choose the size of in-domain corpora for LM fine-tuning on needs. \subsection{Comparison with State-of-the-art Learning-based Methods} \begin{table}[t] \caption{NER F1 scores of state-of-the-art learning-based methods using full training data. AutoNER and SwellShark require domain-specific lexicons that are unavailable for \textsc{S}ci-\textsc{erc}\xspace.} \label{tal:sota} \centering \begin{tabular}{lccc} \toprule Models & \textsc{S}ci-\textsc{erc}\xspace & BC5CDR & NCBI-Disease \\ \hline AutoNER\cite{shang-etal-2018-learning} & - & 84.80 & 75.52 \\ SwellShark\cite{fries2017swellshark} & - & 84.23 & 80.80 \\ \hline SpERT\cite{eberts2019span} & 67.62 &86.65 & 86.12 \\ DyGIE++\cite{wadden-etal-2019-entity} & \textbf{69.80} & 85.44 & 84.11 \\ \hline \textsc{RDANER}\xspace & 68.96 & \textbf{87.38} & \textbf{87.71} \\ \bottomrule \end{tabular} \end{table} In this section, we exploit all training data and use the perfect thresholds of label assignment probability to improve the performance of \textsc{RDANER}\xspace. The averaged results over 5 repetitive runs are summarized in Table~\ref{tal:sota}. We observe that \textsc{RDANER}\xspace performs reasonably well when compared to various state-of-the-art methods that use difficultly obtainable domain-specific resources, including distantly supervise learning-base (DSL) methods and multi-task learning-based (MTL) methods. Because we can't find any parallel resources in computer science and biomedical domains, we don't compare \textsc{RDANER}\xspace with transfer learning methods. AutoNER and SwellShark are two DSL methods, and we observe that \textsc{RDANER}\xspace consistently outperforms them. We can't apply AutoNER and SwellShark on \textsc{S}ci-\textsc{erc}\xspace dataset, because the domain-specific lexicons are unavailable. This also shows DSL methods are highly dependent on the availability of domain-specific resources. Although AutoNER and SwellShark claim that they don't use any human annotated data, they actually leverage the information of large domain-specific lexicons. For example, AutoNER uses a lexicon contains 322,882 chemical and disease entity surfaces, and SwellShark uses ontologies for generating weakly-annotated data. Such resources are often not available, leading DSL methods less adaptable. Interesting, we notice that our approach achieves close results to AutoNER and SwellShark using 20\% of the training data (960 sentences) of BC5CDR, and 10\% of the training data (626 sentence) of NCBI-Disease. Since it is much more challenging to construct big domain-specific lexicons, we suggest using \textsc{RDANER}\xspace to build reliable NER systems when domain-specific lexicons are unavailable. DyGIE++ and SpERT are two latest state-of-the-art MTL methods, and both of them are built on top of \textsc{Bert}\xspace encodings and utilize extra annotations of other tasks. DyGIE++ achieves best F1 score on \textsc{S}ci-\textsc{erc}\xspace, indicating that the extra annotations for other tasks, such as relation, event and coreference labels are helpful to improve performance. However, DyGIE++ perform mediocrely on BC5CDR and NCBI-Disease dataset, due to the lack of extra annotations of the two datasets. We note that SpERT performs better than DyGIE++ on BC5CDR and NCBI-Disease. This is partly due to SpERT only uses relation labels, lacking of extra annotations has less impact on SpERT than DyGIE++. Surprisingly, without extra annotations, \textsc{RDANER}\xspace achieves the second best F1 score on \textsc{S}ci-\textsc{erc}\xspace. Besides, \textsc{RDANER}\xspace outperforms DyGIE++ and SpERT on BC5CDR and NCBI datasets. It demonstrates our proposed approach is not only effective but also domain-adaptive. \section{Conclusions} In this paper, we propose a novel robust and domain-adaptive approach \textsc{RDANER}\xspace for low-resource NER only using cheap and easily obtainable resources. We conduct low-resource experiments in two challenging domains and find that: 1) \textsc{RDANER}\xspace is effective and efficient for low-resource NER, and it achieves competitive performance against the state-of-the-art methods which utilize difficultly obtainable domain-specific resources. 2) Beside, \textsc{RDANER}\xspace is domain-adaptive, which can be easily applied to a new domain. \section*{Acknowledgments} The work is supported by National Key R\&D Plan (No. 2018YFB1005100), NSFC (No. 61772076, 61751201 and 61602197), NSFB (No. Z181100008918002) and the funds of Beijing Advanced Innovation Center for Language Resources (No. TYZ19005). Xian-Ling Mao is the corresponding author. \bibliographystyle{IEEEtran}
{'timestamp': '2021-01-05T02:14:12', 'yymm': '2101', 'arxiv_id': '2101.00388', 'language': 'en', 'url': 'https://arxiv.org/abs/2101.00388'}
arxiv
\section{A Simple Full Library Classifier} \subsection{Extreme Variation in Few-Shot Quality} There is not a clear pattern to which of the library-based classifiers tends to perform best, and which tends to perform worst. Consider the complete set of results, over all of the library-based few-shot learners, for the 5-way, 5-shot problem, shown in Table \ref{tab:complete-5-5}. For ``out-of-the-box'' use, where no validation data are available, it is very difficult to see any sort of pattern that might help with picking a particular library-based classifier. The DenseNet variations sometimes do better than ResNet (on the Aircraft data set, for example), but sometimes they do worse than the ResNet variations (on the FC100 data set, for example). And within a family, it is unclear which library-based CNN to use. As mentioned before, ResNet18 provides the best ResNet-based few-shot learner for two of the data sets, but it forms the basis of the worst ResNet-based learner on another two. \input{tables/table_complete_5_5} \subsection{Combining Library-Based Learners} Given the relatively high variance in accuracies obtained using the library deep CNNs across various data sets, it is natural to ask: Is it perhaps possible to use all of these library feature extractors in concert with one another, to develop a few-shot learner which consistently does as well as (or even better then) the best library CNN? Given the lack of training data in few-shot learning, the first idea that one might consider is some simple variant of ensembling: given a few-shot learning problem, simply train a separate neural network on top of each of the deep CNNs, and then use a majority vote at classification time (hard ensembling) or we can average the class weights at classification time (soft ensembling). Another option is to take all of the library deep CNNs together, and view them as a single feature extractor. Using the nine models considered thus far in this paper in this way results in 13,984 features. We then train an MLP on top of this, using $L_2$ regularization. Again using the Caltech-UCSD Birds 200 data set for validation, we perform hyperparameter search to build a few-shot learner for $5$-way, $20$-way, and $40$-way classification problems. We test both of these options over the eight test sets, and give a synopsis of the results in Table \ref{tab:ensemble}. We find that across all 24 test cases (eight data sets, three classification tasks), the best single learner was \emph{never} able to beat the best method that used all nine deep CNNs. All of the tested methods had similar performance on the 5-way classification task, though the best single learner was generally a bit worse than the other methods. Where the difference becomes more obvious is on the classification tasks with more categories. For the $20$-way and $40$-way problems, the two ensemble-based methods had a small but consistent drop in accuracy, and building a single network on top of all nine deep CNNs is clearly the best. This may be somewhat surprising; for the 40-way problem, hyperparameter search on the Caltech-UCSD Birds 200 data set settled on a single network with 1024 neurons in a hidden layer; this means that more than 14 million parameters must be learned over just 200 images. Clearly, the neural network is massively over-parameterized, and yet the accuracies obtained are remarkable, with over 90\% accuracy on two of the data sets. \input{tables/table_ensemble} \section{Conclusions} We have examined the idea of using a library of deep CNNs as a basis for a high-quality few-shot learner. We have shown that a learner built on top of a high-quality deep CNN can have remarkable accuracy, and that a learner built upon an entire library of CNNs can significantly outperform a few-shot learner built upon any one deep CNN. While we conjecture that it will be hard to do better than using a library of high-quality deep CNNs as the basis for a few-shot learner, there are key unanswered questions. First, future work should study if the accuracy continues to improve as the library is made even larger. Also, it may be expensive to feed a test image through a series of nine (or more) deep CNNs. It would be good to know if the computational cost of the library-based approach can be reduced. Finally, it would be good to know if there are better methods to facilitate transfer than learning a simple MLP. \vspace{5 pt} \noindent \textbf{Acknowledgments.} The work in this paper was funded by NSF grant \#1918651; by NIH award \# UL1TR003167, and by ARO award \#78372-CS. \balance \section{Data vs. Diversity: Who Wins?} The results from the last section clearly show that an MLP learned on top of a library of high-quality, deep CNNs makes for an excellent, general-purpose, few-shot learner. This leaves open the question. When basing a few-shot learner on a fairly simple, transfer-based approach, which is more important, diversity or size, when constructing the few-shot learner? That is, is it better to have a large variety of deep CNNs to combine together, each of which is trained on a smaller $\mathcal{D}_\mathit{trn}$, or is it preferable to base a few-shot learner on a single, deep CNN that has been trained on a larger and more diverse $\mathcal{D}_\mathit{trn}$? To answer this question, we compare the single MLP built upon all nine of the library deep CNNs with an MLP built upon a high-quality deep CNN that was \emph{itself} constructed upon an even larger data set: the full ImageNet data set, with more than 20,000 categories. High-quality, publicly available deep CNNs for this data set are rare, but Google recently released a set of deep CNNs trained on the full ImageNet, specifically for use in transfer learning\cite{kolesnikov2019big}. We consider three of their deep CNNs. Each is a ResNet: BiT-ResNet-101-3 (``BiT'' stands for ``Big Transfer''; ``101-3'' is a ResNet101 that has $3X$ the width of a standard ResNet), BiT-ResNet-152-4, and BiT-ResNet-50-1. For each of these Big Transfer models, we perform a full hyperparameter search using the Caltech-UCSD Birds data set for validation, as we did for each of the deep CNNs trained on ILSVRC2012. Interestingly, the Google models tend to do better with a much larger $L_2$ regularization parameter weight (0.5 to 0.7) compared to the other deep CNNs trained on ILSVRC2012 (which typically performed best on the validation set using a weight of around 0.1). Results are shown in Table \ref{tab:vs-bigt}. The headline finding is that the single model utilizing a library of nine, ILSVRC2012-trained CNNs, is the best model. It did not not always perform the best on each data set. In fact, on four of the data sets (FC100, Texture, Fungi, and VGG Flower) at least one of the Google Big Transfer models outperformed the single model consisting of nine ILSVRC2012-trained CNNs. In each of the those cases, the performance was comparable across models, except, perhaps, for the VGG Flower data set, where the best Big Transfer models always obtained more than 99\% accuracy. However, on the other data sets (Aircraft, Omniglot, Trafic Sign, and QuickDraw) the combined model far outperformed any of the Big Transfer models. The gap was often significant, and the combined model outperformed the best Big Transfer-based model by an average of more than 11\% for the 40-way task. It was also interesting that while the Big Transfer models were generally better than the ILSVRC2012-trained library CNNs, this varied across data sets. On the Aircraft and Omniglot data sets, for example, even the best \emph{individual} ILSVRC2012-trained library CNNs outperformed the Big Transfer models. All of this taken together seems to suggest that, when building a transfer-based few-shot learner, having a large library of deep CNNs is at least as important---and likely \emph{more} important---than having access to a CNN that was trained on a very large $\mathcal{D}_\mathit{trn}$. \section{Introduction}\label{sec:intro} There has been a lot of recent interest in few-shot image classification \cite{fei2006one, lee2019meta, li2019finding, finn2017model, finn2018probabilistic, kim2018bayesian, nichol2018reptile, lee2018gradient}. Various papers have explored different formulations of the problem, but in one general formulation, we are given a data set $\mathcal{D}_\mathit{trn}$ of (image, label) pairs sampled from a distribution $\mathbb{P}_\mathit{trn}$. The goal is to devise a method that uses $\mathcal{D}_\mathit{trn}$ to learn a function $f$ that is \emph{itself} a few-shot learner. The few-shot learner $f$ takes as input a new labeled data set $\mathcal{D}_\mathit{few}$ consisting of a set of samples from a new distribution $\mathbb{P}_\mathit{few} \neq \mathbb{P}_\mathit{trn}$. $f$ then returns a classification function $g$, which is targeted at classifying samples from the distribution $\mathbb{P}_\mathit{few}$. The process of learning $f$ is often referred to as \emph{meta-learning} in the literature. Learning to classify samples from $\mathbb{P}_\mathit{few}$ is a ``few shot'' problem when $\mathcal{D}_\mathit{few}$ is small, perhaps having only one example for each class produced by $\mathbb{P}_\mathit{few}$. In the most difficult and generally applicable variant of the few-shot problem---which we consider in this paper---$\mathbb{P}_\mathit{few}$ has no known relationship to $\mathbb{P}_\mathit{trn}$ (this is ``cross-domain'' few-shot learning) and $\mathcal{D}_\mathit{few}$ is not available while learning $f$. Thus, the meta-learning process has no access to information about the eventual application. The only information we have about $\mathbb{P}_\mathit{few}$ is the set $\mathcal{D}_\mathit{few}$, and this is available only when constructing $g$. We cannot, for example, choose any hyperparameters controlling the learning of $g$ using information not extracted from $\mathcal{D}_\mathit{few}$. Our goal is to devise a learner $f$ that works well, out-of-the-box, on virtually any new distribution $\mathbb{P}_\mathit{few}$. We argue that in such a scenario, developing novel meta-learning methods to learn $f$ from scratch on given $\mathcal{D}_\mathit{trn}$ may not be the most productive direction of inquiry. Because no information about $\mathbb{P}_\mathit{few}$ is available during meta-learning, it makes sense to choose a $\mathcal{D}_\mathit{trn}$ that has many different types of images, so it is likely to contain some images with features similar to those produced by $\mathbb{P}_\mathit{few}$, whatever form this distribution takes. Fortunately, in computer image classification, the standard benchmark data set is now ILSVRC2012, a 1000-class version of the full ImageNet \cite{ILSVRC15}. ILSVRC2012 consists of a wide variety of images, and it has become quite standard for researchers who design and train new image classifiers to publish classifiers trained on ILSVRC2012. Such published artifacts represent thousands of hours of work by researchers who are well-versed in the ``black art'' of wringing every last percent of accuracy out of a deep CNN. Instead of developing new meta-learning methods, it may be more productive to simply fix $\mathcal{D}_\mathit{trn}$ = ILSVRC2012, and attempt to leverage all of the effort that has gone into learning deep CNNs over ILSVRC2012, by using those CNNs as the basis for the few-shot learner $f$. As other, even more wide-ranging and difficult benchmark data sets become prevalent (such as the full, 20,000+ class ImageNet), high-quality classifiers trained using that data set may be preferred. We first show that it is possible to use any of a number of published, high-quality, deep CNNs, learned over ILSVRC2012, as the basis for a few-shot learner that significantly outperforms state-of-the art methods. The way to do this is embarrassingly simple: remove the classifier from the top of the deep CNN, fix the weights of the remaining deep feature extractor, and replace the classifier with a simple MLP that is trained using $L_2$ regularization to prevent over-fitting. We call these ``library-based'' learners because they are based on standard, published feature extractors. Next, we ask: if a published deep CNN can be used to produce a state-of-the-art, few-shot learner, can we produce an even higher-quality few-shot learner by combining together \emph{many} high-quality, deep CNNs? We call such a learner a ``full library'' learner. Then, we note that other researchers have suggested the utility of re-using high-quality, pre-trained feature extractors for few-shot image classification. In particular, the authors of the ``Big Transfer'' paper \cite{kolesnikov2019big} argue that a very large network trained on a huge data set (the JFT-300M data set \cite{sun2017revisiting}, with 300 million images) can power an exceptionally accurate transfer-learning-based few-shot learning. Unfortunately, the authors have not made their largest JFT-300M-trained network public, and so we cannot experiment with it directly. However, they \emph{have} made public several versions of their ``Big Transfer'' network, trained on the full, 20,000+ class ImageNet benchmark public. Interestingly, we find that ``big'' may not be as important as ``diverse'': a single, few-shot classifier comprised of many different high-quality ILSVRC2012-trained deep CNNs seems to be a better option than a single few-shot classifier built on top of any of the Google-trained CNNs. Finally, we investigate why a full library learner works so well. We postulate two reasons for this. First, having a very large number of features ($>$ 10,000) does not seem to be a problem for few-shot learning. Second, there seems to be strength in diversity, in the sense that different CNNs appear useful for different tasks. \section{High Accuracy of Library-Based Learners} \subsection{Designing a Library-Based Learner} We begin by asking: what if we eschew advanced meta-learning methods, and instead simply use a very high-quality deep CNN pulled from a library, trained on the ILSVRC2012 data set, as the basis for a few-shot classifier? \input{tables/table_library} Specifically, we are given a high-quality, pre-trained deep CNN, from a library of pre-trained networks; we take the CNN as-is, but remove the topmost layers used for classification. This results in a function that takes an image, and returns an embedding. We then use that embedding to build a classifier in an elementary fashion: we feed the embedding into a multi-layer perceptron with a single hidden layer; a softmax is used to produce the final classification. Given a few-shot classification problem, two weight matrices $\textbf{W}_1$ and $\textbf{W}_2$ are learned; the first connecting the embedding to the hidden layer, the second connecting the hidden layer to the softmax. To prevent over-fitting during training, simple $L_2$ regularization is used on the weight matrices. \subsection{Evaluation} To evaluate this very simple few-shot learner, we first identify nine, high-quality deep CNNs with published models, trained on ILSVRC2012: ResNet18, ResNet34, ResNet50, ResNet101, ResNet152 (all of the ResNet implementations are the ones from the original ResNet designers \cite{he2016deep}), DenseNet121, DenseNet161, DenseNet169, and DenseNet201 (all of the DenseNet implementations are also from the original designers \cite{huang2017densely}). Our goal is to produce an ``out-of-the-box'' few-shot learner that can be used on any (very small) training set $\mathcal{D}_\mathit{few}$ without additional data or knowledge of the underlying distribution. We are very careful not to allow validation or parameter tuning on testing data domains, so all parameters and settings need to be chosen apriori. If it is possible to build such a few-shot learner, it would be the most widely applicable: simply produce a few training images for each class, apply the learner. Thus, we perform an extensive hyper-parameter search, solely using the Caltech-UCSD Birds 200 set \cite{WelinderEtal2010} as a validation data set, and then use the best hyperparameters from that data set in all of our experiments. Hyperparameters considered were learning rate, number of training epochs, regularization penalty weight, the number of neurons in the MLP hidden layer, and whether to drop the hidden layer altogether. A separate hyper-parameter search was used for 5-way, 20-way, and 40-way classification. We then test the resulting few-shot learner---one learner per deep CNN---on eight different data sets, FGVC-Aircraft \cite{maji13fine-grained}, FC100 \cite{oreshkin2018tadam}, Omniglot \cite{lake2015human}, Traffic Sign \cite{houben2013detection}, FGCVx Fungi \cite{schroeder2018fgvcx}, Quick Draw \cite{jongejan2016quick}, and VGG Flower \cite{nilsback2008automated}. To evaluate a few-shot learner on a data set, for an ``$m$-way $n$-shot'' classification problem, we randomly select $m$ different classes, and then randomly select $n$ images from each class for training; the remainder are used for testing. As this is ``out-of-the-box'' learning, no validation is allowed. We performed this evaluation for $m$ in $\{5, 20, 40\}$ and $n$ in $\{1, 5\}$. Due to space constraints, the full results are presented as supplementary material, and we give only a synopsis here (Table \ref{tab:comparison-5-5} and Table \ref{tab:comparison-20-5}). In Table \ref{tab:library}, we show the best and worst accuracy achieved across the 9 learners, for each of the 8 data sets, for $m$ in $\{5, 20, 40\}$ and $n = 1$. \input{tables/table_comparison_5_5} To give the reader an idea of how this accuracy compares to the state-of-the-art, we compare these results with a number of few-shot learners from the literature. We compare against Baseline and Baseline++ \cite{chen2019closer}, MAML \cite{finn2017model}, MatchingNet \cite{vinyals2016matching}, ProtoNet \cite{snell2017prototypical}, RelationNet \cite{sung2018learning}, Meta-transfer \cite{sun2019meta}, FEAT \cite{ye2020few}, and SUR \cite{2020arXiv200309338D}. When a deep CNN classifier must be chosen for any of these methods, we use a ResNet18. For methods that require a pre-trained CNN (FEAT, Meta-transfer, and SUR), we use the ResNet18 trained by the ResNet designers \cite{he2016deep}. Lest the reader be concerned that we chose the worst option (ResNet18), we point out that of the library-based few-shot learners, on the 5-way, 5-shot problem ResNet18 gave the best accuracy out of all of the ResNet-based learners for two of the data sets (see Table \ref{tab:complete-5-5}). Further, these competitive methods tend to be quite expensive to train---MAML, for example, requires running gradient descent over a gradient descent---and for such a method, the shallower ResNet18 is a much more reasonable choice than the deeper models (even using a ResNet18, we could not successfully train first-order MAML for 5-shot, 40-way classification, due to memory constraints). For the competitive methods (other than SUR) we follow the same procedure as was used for the library-based few-shot classifiers: any training that is necessary is performed on the ILSVRC2012 data set, and hyperparameter validation is performed using the Caltech-UCSD Birds 200 data set. Each method is then used without further tuning on the remaining eight data sets. To evaluate SUR on data set $X$, we use feature extractors trained on the data sets in \{Omniglot, Aircraft, Birds, Texture, Quickdraw, Flowers, Fungi,and ILSVRC\} $-$ $X$. Traffic Sign and FC100 datasets are reserved for testing only. \input{tables/table_comparison_20_5} A comparison of each of these competitive methods with the the best and worst-performing library-based learners on the 5-way, 5-shot learning problem is shown in Table \ref{tab:comparison-5-5}; a comparison on 20-way, 5-shot learning in Table \ref{tab:comparison-20-5}. A more complete set of results is in the supplementary material. \subsection{Discussion} There are a few key takeaways from these results. The best library-based learner \emph{always} beat every one of the other methods tested, with the only exception of SUR when testing on Omniglot data set. For the other data sets, the gap only grows as the number of ways increases. In fact, for the 20-way problem, the \emph{worst} library-based learner always beat all of the other methods tested (except SUR on Omniglot). The gap can be quite dramatic, especially on the 20-way problem. The best non-transfer based few-shot learner (MAML, Proto Nets, Relation Nets, and Matching Nets fall in this category) was far worse than even the worst library-based learner: 39\% accuracy for Proto Nets vs. 59\% accuracy for a classifier based on RestNet18 on Texture, 48\% accuracy for Relation Nets vs. 57\% accuracy for classifier based on ResNet101 on Quick Draw. There have been a large number of non-transfer-based methods proposed in the literature (with a lot of focus on improving MAML in particular \cite{finn2017model, finn2018probabilistic, kim2018bayesian, nichol2018reptile, lee2018gradient}) but the gap between MAML and the library-based classifiers is very large. We also note that of the rest non-library methods, Meta-transfer, Baseline, and FEAT were generally the best. We note that Meta-transfer, Baseline, and FEAT use the pre-trained ResNet18 without modification. This tends to support the hypothesis at the heart of this paper: starting with a state-of-the-art feature extractor, trained by experts, may be the most important decision in few-shot learning. \section{Related Work} While most research on few-shot learning \cite{wang2018low, oreshkin2018tadam, rusu2018meta} has focused on developing new and sophisticated methods for learning a few-shot learner, there have recently been a few papers that, like this work, have suggested that transfer-based methods may be the most accurate. \begin{figure}{} \centering \includegraphics[width=.99\linewidth]{jaccards/JaccardTop.pdf} \caption{Jaccard similarity of sets of most important features for the various (data set, data set) pairs.} \label{fig:top-features} \end{figure} \begin{figure}{} \centering \includegraphics[width=.99\linewidth]{jaccards/FeaturesSelected.pdf} \caption{Percent of each deep CNN's features that appear in the top 20\% of features, on each data set.} \label{fig:features-selected} \end{figure} In Section~\ref{sec:intro}, we mentioned Google's ``Big Transfer'' paper \cite{kolesnikov2019big}. There, the authors argued that the best approach to few-shot learning is to concentrate on using a high-quality feature extractor rather than a sophisticated meta-learning approach. We agree with this, but also give evidence that training a huge model and a massive data set may not be the only key to few-shot image classification. We found that a library with a wide diversity of high-quality deep CNNs can lead to substantially better accuracy than a single massive CNN, even when that deep CNN is trained on a much larger data set. Tian et al. \cite{tian2020rethinking} make a similar argument to the Big Transfer authors, observing that a simple transfer-based approach can outperform a sophisticated meta-learner. Chen et al. \cite{chen2019closer} were among the first researchers to point out that simple, transfer-based methods may outperform sophisticated few-shot learners. They proposed Baseline which uses a simple linear classifier on top of a pre-trained deep CNN, and Baseline++ which uses a distance-based classifier. Dhillon et al. \cite{dhillon2019baseline} also point out the utility of transfer-based methods, and propose a transductive fine-tuner; however, such a method relies on having an appropriately large number of relevant, unlabeled images to perform the transductive learning. Sun et al. \cite{sun2019meta} consider transfer learning, but where transfer is realized via shifting and scaling of the classification parameters. Dvornik et al. \cite{2020arXiv200309338D} propose SUR, and argue that diversity in features is best obtained through diversity in data sets. Their method trains many feature extractors, one per data set. We argue that instead, a single high-quality data set is all that is needed. Adding additional feature extractors trained on that data set is the best way to higher accuracy. This may be counter-intuitive, but there is an obvious argument for this: training on less diverse data sets such as Aircraft or VGG Flowers is apt to result in feature extractors that are highly specialized, do not generalize well, and are not particularly useful. The proposed library-based classifier generally outperformed SUR in our experiments. Dvornik et al. \cite{dvornik2019diversity} also consider the idea of ensembling for few-shot learning, although their idea is to simultaneously train a number of diverse deep CNNs as feature extractors during meta-learning; adding penalty terms that encourage both diversity and conformity during learning. We propose the simple idea of simply using a set of existing deep CNNs, trained by different groups of engineers. \section{Why Does This Work?} \subsection{Few-Shot Fine-Tuning Is Surprisingly Easy} We turn our attention to asking: why does using a full library of pre-trained feature extractors seem to work so well? One reason is that fine-tuning appears to be very easy with a library of pre-trained features. Consider the following simple experiment, designed to test whether the number of training points has much effect on the learned model. We choose a large number of 40-way, problems, over all eight of our benchmark data sets, and train two classifiers for each. Both classifiers use all of the 13,984 features provided by the nine library feature extractors. However, the first classifier is trained as a one-shot classifier, and the second classifier is trained using all of the available data in the data set. Our goal is to see whether the sets of learned weights have a strong correspondence across the two learners; if they do, it is evidence that the number of training points has a relatively small effect. Note that in a neural network with a hidden layer consisting of hundreds or thousands of neurons, there are likely to be a large number of learned weights that are of equal quality; in fact, simply permuting the neurons in the hidden layer results in a model that is functionally identical, but that has very different weight matrices. Thus, we do not use a hidden layer in either classifier, and instead use a softmax directly on top of an output layer that linearly combines the input features. Both the one-shot and full-data classifiers were learned without regularization. \input{tables/table_vs_bigt} Over each of the eight benchmark data sets, for each feature, we take the $L_1$ norm of all of the 40 weights associated with the feature; this serves as an indication of the importance of the feature. We compute the Pearson correlation coefficient for each of the 13,984 norms obtained using the models learned for the 1-shot and full data classifiers. These correlations are shown in Table \ref{tab:correlation}. What we see is a remarkably high correlation between the two sets of learned weights; above 80\% correlation in every case, except for the Traffic Sign data set. However, even in the case of the Traffic Sign data set, there was a weak correlation (the Traffic Sign data is a bit of an outlier in other ways as well, as we will see subsequently). This would seem to indicate that there is a strong signal with only one data point per class, as the learned weights do not differ much when they are learned using the whole data set. This may be one explanation for the surprising accuracy of the full library few-shot learner. Of course, the strong correlation may gloss over significant differences, and more data \emph{does} make a significant difference (consider the difference between the one-shot accuracies in Table 1 and the five-shot accuracies in Table 2.). But even one image per class seems to give a lot of information. \input{tables/table_correlation} \subsection{Different Problems Utilize Different Features} Another reason for the accuracy obtained by the full library method may be that different problem domains seem to utilize different sets of features, and different feature extractors. Having a large library ensures that \emph{some} features relevant to any task are always present. To investigate this, we construct a large number of 40-way training tasks over each of the various data sets, and for each, we learn a network without a hidden layer on top of all 13,984 features obtained using the library of deep CNNs. Again, we compute the $L_1$ norm of the set of weights associated with each of the features. This time, however, for each problem we then consider the features whose norms are in the top 20\%; these could be considered the features most important to solving the classification task. For each of the (data set, data set) pairs, we compute the average Jaccard similarity of these top-feature sets. Since each set consists of 20\% of the features, if each set of features chosen was completely random, for $n$ features in all, we would expect a Jaccard similarity of $\frac{0.04n}{.2n + .2n - 0.04n}$ $=$ $\frac{0.04}{.4 - 0.04}$ $=$ $0.111$. Anything greater indicates the sets of features selected are positively correlated; lower indicates a negative correlation. Results are in Figure \ref{fig:top-features}. For each of the nine CNNs, we also compute the fraction of each CNN's features that are in the top 20\% when a full library classifier is constructed. These percentages are in Figure \ref{fig:features-selected}. The data in these two plots, along with the previous results, tells a consistent story: there appears to be little correspondence between data sets in terms of the set of features that are chosen as important across data sets. The largest Jaccard value in Figure \ref{fig:top-features} is less than 0.5 (observed between FC100 and Texture). This shows, in our opinion, a relatively weak correspondence. The Traffic Sign data set, had an average Jaccard of $0.108$ across the other eight data sets, which is even lower than the $0.111$ that would be expected under a purely random feature selection regime. One might speculate that the lack of correspondence across data sets is evidence for the hypothesis that different tasks tend to use different features, which would explain why it is so effective to use an entire library of deep CNNs for few-shot learning. Also note that in Figure \ref{fig:features-selected}, we tend to see that different deep CNNs contribute ``important'' features at very different rates, depending on the particular few-shot classification task. This also seems to be evidence that diversity is important. In general, the DenseNets' features are preferred over the ResNets' features, but this is not universal, and there is a lot of variation. It may not be an accident that the three data sets where the selection of features from library CNNs shows the most diversity in Figure \ref{fig:features-selected} (Traffic Sign, Quick Draw, and Omniglot) are the three data sets where the classifier built on top of all nine library CNNs has the largest advantage compared to the few-shot classifiers built on top of the single, ``Big Transfer''-based deep CNN. \section{Description of Data} \input{data} \section{Hyper-parameters for Library-Based \\Learners} \input{hyper} \section{Competitive Methods} \input{competitive} \section{Complete Results} \input{results} \subsection{Datasets} \noindent\textbf{ILSVRC2012 \cite{ILSVRC15}} Figure \ref{fig:ilsvrc}. A dataset of natural images of 1000 diverse categories, the most commonly used Imagenet dataset, primarily released for `Large Scale Visual Recognition Challenge'. We use the ILSVRC-2012 version as the original dataset for the classification challenge has not been modified since. The dataset has a little more than 1.2 million (1,281,167 to be precise) images with each class consisting of images ranging from 732 to 1300. \\ \noindent\textbf{CUB-200-2011 Birds \cite{WelinderEtal2010}} Figure \ref{fig:cub}. A dataset for fine-grained classification of 200 different bird species, an extended version of the CUB-200 dataset. The total number of images in the dataset is 11,788 with mostly 60 images per class.\\ \noindent\textbf{FGVC-Aircraft \cite{maji13fine-grained}} Figure \ref{fig:aircraft}. A dataset of images of aircrafts spanning 102 model variants with 10,200 total images and 100 images per class. \\ \noindent\textbf{FC100 \cite{oreshkin2018tadam}} Figure \ref{fig:fc100}. A dataset curated for few-shot learning based on the popular CIFAR100 \cite{krizhevsky2009learning} includes 100 classes and 600 32 × 32 color images per class. It offers a more challenging scenario with lower image resolution. \\ \noindent \textbf{Omniglot \cite{lake2015human}} Figure \ref{fig:omniglot}. A dataset of images of 1623 handwritten characters from 50 different alphabets. We consider each character as a separate class. The total number of images is 32,460 with 20 examples per class. \\ \noindent\textbf{Texture \cite{cimpoi14describing}} Figure \ref{fig:texture}. A dataset consists of 5640 images, organized according to 47 categories inspired from human perception. There are 120 images for each category. Image sizes range between 300x300 and 640x640, and the images contain at least 90\% of the surface representing the category attribute.\\ \noindent \textbf{Traffic Sign \cite{houben2013detection}} Figure \ref{fig:traffic}. A dataset of German Traffic Sign Recognition benchmark consisting of more than 50,000 images across 43 classes. \\ \noindent \textbf{FGCVx Fungi \cite{schroeder2018fgvcx}} Figure \ref{fig:fungi}. A dataset of wild mushrooms species which have been spotted and photographed by the general public in Denmark, containing over 100,000 images across 1,394 classes. \\ \noindent\textbf{Quick Draw \cite{jongejan2016quick}} Figure \ref{fig:quick_draw}. A dataset of 50 million drawings across 345 categories. We take the simplified drawings, which are 28x28 gray-scale bitmaps and aligned to the center of the drawing's bounding box. Considering the size of the full dataset, we randomly sample 1,000 images from each category.\\ \noindent\textbf{VGG Flower \cite{nilsback2008automated}} Figure \ref{fig:vgg_flower}. A dataset consisting of 8189 images among 102 flower categories that commonly occuring in the United Kingdom. There are between 40 to 258 images in each category. \\ \subsection{Data Preparation} For all the datasets, we resize each image into 256 x 256 then crop 224 $\times$ 224 from the center (except quick draw which is already aligned to the center of the drawing's bounding box, so we directly resize quick draw images to 224 $\times$ 224). \subsection{Test Protocol} In this work, for all the methods the training process is performed solely on ILSVRC dataset. For our library based methods, this is followed by hyperparameter validation on the CUB birds dataset. After that, each method is tested on the remaining eight datasets without further tuning.\\ To be more specific, for the library based methods we only use the pre-trained (on ILSVRC dataset) models. While for the meta-learning based methods, we randomly split ILSVRC into a base (training) set of 900 classes for meta-training and a validation set of the remaining 100 classes.\\ In order to evaluate a few-shot learner on a data set, for an ``$n$-way $m$-shot'' classification problem, we randomly select $n$ different classes, and then randomly select $m$ images from each class for training (equivalent to `support' images in meta-learning literature). We then randomly select $k$ images for rest of the images from each class for testing (equivalent to `query' images in meta-learning literature). We perform this evaluation for $n$ in $\{5, 20, 40\}$ and $m$ in $\{1, 5\}$. \\ For the library based methods, the query size $k$ is set to 15 (except FGCVx Fungi dataset). For the meta-learning based methods, due to GPU memory constraints, for each class in a task we used 15 query images for 5-way, 10 query \input{data_images} \twocolumn \noindent images for 10-way, and 5 query images for 40-way problems, with only exception being the Fungi dataset. Fungi dataset has several classes with a very small number of images (6 being the minimum). Hence for Fungi dataset, we use 5 query images per class for 1-shot and 1 query image per class for 5-shot problems. Finally, for every problem, we report the mean of 600 randomly generated test tasks along with the 95\% confidence intervals. For the FC100 data set, there is a small portion overlaps with ILSVRC2012 data set but we still think that the FC100 as a testing set is interesting, as (1) all of the few-shot learners benefitted from the overlapping classes, and (2) this shows how the methods work in the case that the test classes are close to something that the few-shot learner has seen before. \section*{Appendix} \beginsupplement \input{appendix} \end{document}
{'timestamp': '2021-08-24T02:00:46', 'yymm': '2101', 'arxiv_id': '2101.00562', 'language': 'en', 'url': 'https://arxiv.org/abs/2101.00562'}
arxiv
\section{Introduction} Current achievements of deep neural networks (DNNs) heavily rely on large amounts of supervised data, which are expensive and difficult to acquire simultaneously. Therefore, the ability of continual learning (CL) on incremental training samples becomes extremely important. Numerous efforts have been devoted to CL, which aim to continually learn new training samples without \emph{catastrophic forgetting} of the learned data distribution \cite{parisi2019continual}. Existing CL methods mainly fall in two categories: weight regularization methods~\cite{parisi2019continual,kirkpatrick2017overcoming,aljundi2018memory} and replay-based methods~\cite{parisi2019continual,rebuffi2017icarl,shin2017continual}, and have achieved promising results in purely supervised settings. In many real-world applications, nevertheless, the incremental data are often partially labeled. For example, in face recognition~\cite{roli2006semi}, a device continually obtains user data for unlocking. These increasing data could be used to update the model for better user experience. However, true labels of the incoming data are usually unavailable unless the user provides the password for verification. Since frequently asking for labelling would affect user experience, most of the input data are unlabeled. Similar scenarios occur in fingerprint identification~\cite{yuan2020semi} and video recognition~\cite{luo2017adaptive}. Though such scenarios are common in our daily life, they are seldom studied in the CL literature. Therefore, in this paper, we focus on the challenging and realistic task that continually learns incremental partially labeled data. For simplicity, we refer to it as \emph{semi-supervised continual learning} (SSCL). Different from supervised CL, SSCL provides insufficient supervision and a large amount of unlabeled data. As is well known, unlabeled data are crucial in semi-supervised scenarios~\cite{zhu2009introduction} but are massive to exploit. In fact, we conduct preliminary experiments in SSCL and empirically verify that the representative CL methods including the weight regularization methods~\cite{parisi2019continual,kirkpatrick2017overcoming,aljundi2018memory} and the replay-based methods~\cite{parisi2019continual,rebuffi2017icarl,shin2017continual} may not effectively exploit the unlabeled data. Specifically, the joint training of a strong semi-supervised classifier significantly outperforms the best of existing CL strategies on the same classifier (see results in Fig.~\ref{svhn30b_MT} and Appendix A). We identify this as the \emph{catastrophic forgetting of unlabeled data} problem in SSCL. To this end, we present deep \emph{online replay with discriminator consistency (ORDisCo)}, a framework to continually learn a semi-supervised classifier and a conditional generative adversarial networks (GAN)~\cite{mirza2014conditional} together in SSCL. Specifically, ORDisCo is formulated as a minimax adversarial game~\cite{goodfellow2014generative}, where a generator tries to capture the underlying joint distribution of partially labeled data, and help the classifier make accurate predictions. At the same time, the classifier also predicts pseudo-labels for unlabeled data to improve the training of the conditional generator. In contrast to previous work~\cite{shin2017continual,wu2018memory,ostapenko2019learning}, ORDisCo replays data sampled from the conditional generator to the classifier in an \emph{online} manner, which is time- and storage-efficient to exploit the large amount of unlabeled data in SSCL. Further, to explicitly overcome the catastrophic forgetting of unlabeled data, we selectively stabilize parameters of the discriminator that are important for discriminating the pairs of old unlabeled data and their pseudo-labels predicted by the classifier. We follow the \textit{New Instance} and \textit{New Class} scenarios of CL \cite{parisi2019continual} to split commonly used SSL benchmark datasets \cite{chongxuan2017triple,oliver2018realistic}, including SVHN, CIFAR10 and Tiny-ImageNet, as the evaluation benchmarks for SSCL. To simulate the practical scenarios, all methods continually receive a batch of data with a few labels during training. Extensive evaluations on such benchmarks show that ORDisCo can significantly outperform strong baselines in SSCL. In summary, our contributions include: (i) We consider a realistic yet challenging task called semi-supervised continue learning (SSCL). We provide a systematical study of existing CL strategies and show that the catastrophic forgetting of unlabeled data is the key challenge in SSCL. (ii) We present ORDisCo to continually learn a classifier and a conditional GAN in SSCL. The generator replays data in an online manner with a consistency regularization on the discriminator to address the catastrophic forgetting of unlabeled data; (iii) We evaluate ORDisCO on various benchmarks and demonstrate that ORDisCO significantly improves both classification and conditional image generation over strong baselines in SSCL. \section{Related Work} \textbf{Continual learning (CL)} aims to address catastrophic forgetting in DNNs on a dynamic data distribution \cite{parisi2019continual}, which requires DNNs to learn from incoming tasks or training samples while retaining previously learned data distribution. Current efforts in CL mainly consider the setting where large amounts of annotated data are available for training. Regularization-based methods selectively penalize changes of the parameters to maintain the learned data distribution, e.g., EWC \cite{kirkpatrick2017overcoming}, SI \cite{zenke2017continual} and MAS \cite{aljundi2018memory}. While, replay-based methods store a small memory buffer to replay representative training samples \cite{rebuffi2017icarl, castro2018end}. To address the imbalance between the small memory buffer and large amounts of training samples, BiC \cite{wu2019large} splits an equal number of samples from both the memory buffer and new training data as a validation set to train an additional linear layer for bias correction, while the Unified Classifier \cite{hou2019learning} regularizes the cosine similarity of features in an unsupervised fashion to normalize the prediction. \cite{tao2020topology} maintains a topology of learned feature space, but it's difficult to learn such a CL-based topology from semi-supervised data. \cite{liu2020mnemonics} provides a more effective strategy to select the memory buffer from large amounts of labeled data, which is unavailable in SSCL. To better recover the learned data distribution, generative replay strategies continually learn a generative model to replay generated data \cite{shin2017continual, wu2018memory, ostapenko2019learning}. However, conditional generation for CL heavily relies on large amounts of labeled data to assign correct labels. Thus, the extension to large amounts of unlabeled data with only a few labels is highly nontrivial. Also, the generative models are often offline saved in CL, which results in additional time and storage cost. \textbf{CL of limited supervised data} Few-shot continual or incremental learning (FSIL) \cite{javed2019meta,tao2020few,ayub2020brain} incrementally learns new classes from a small amount of labeled data, which generally requires a pretraining step on large amounts of base tasks and training samples for few-shot generalization. Unsupervised continual learning (UCL) \cite{rao2019continual,smith2019unsupervised} continually learns new classes from large amounts of unlabeled data. However, FSIL and UCL only make use of a small amount of labeled data or large amounts of unlabeled data, both of which are easy to acquire in many real-world applications. Also, both FSIL and UCL mainly consider learning new classes from a fixed number of training samples, rather than continually learn new instances of the learned classes. By contrast, our setting of SSCL aims to continually learn new instances of the learned classes and new classes from partially labeled data, which is more realistic in real-world scenarios. \cite{li2019incremental} continually learns partially labeled new instances of fixed classes through stacking generators and discriminators that significantly expand the model. While, we focus on the setting that the model should maintain a relatively constant size, which is a common assumption for continual learning. \textbf{Semi-supervised learning (SSL)} provides a powerful framework to leverage unlabeled data from a small amount of labels. Pseudo-Labeling (PL) \cite{lee2013pseudo} is an early work to assign the prediction of an unlabeled data that is higher than a threshold as its pseudo-label to augment the labeled data. Many more recent works of SSL on discriminative model define a regularization term to learn the distribution of unlabeled data. Consistency regularization, e.g., PI-model \cite{laine2016temporal}, makes use of the stochastic predictions of a network and adds a loss term to regularize the consistency of predictions on different passes of the same data. Mean teacher (MT) \cite{tarvainen2017mean} enforces the predictions of the classifier closer to its exponential moving average on the same batch of unlabeled data. Virtual Adversarial Training (VAT) \cite{miyato2018virtual} adds adversarial perturbations to the unlabeled data and enforces the predictions to be the same as the original one. Graph Laplacian regularization \cite{gong2015deformed} penalizes the variation of labels on the graph of manifold structure. SSL on GAN is generally built on a two-network architecture, that the discriminator is responsible for both sample quality and label prediction, including CatGAN \cite{springenberg2015unsupervised}, Improved-GAN \cite{salimans2016improved}, CGAN \cite{mirza2014conditional} and its variants \cite{radford2015unsupervised,odena2017conditional}. Triple-GAN \cite{chongxuan2017triple} applies a triple-network architecture that includes a classifier taking the role of label prediction. ISL-GAN \cite{wei2020incremental} dynamically assigns more virtual labels to unlabeled data during joint training of all the partially labeled data together. However, existing efforts of SSL on both discriminative model and GAN only consider a static data distribution rather than a dynamic one. \section{Semi-supervised Continual Learning and Its Challenges} In this section, we first introduce the problem formulation of continual learning (CL) of incremental semi-supervised data, i.e. semi-supervised continual learning (SSCL). Then, we provide a systematic study of existing representative continual learning methods in SSCL. They suffer from catastrophic forgetting due to the poor usage of large amounts of unlabeled data. \subsection{Problem Formulation} Compared with supervised CL, SSCL only provides a small amount of labeled data and a large amount of unlabeled data, which is key to achieve good performance. Formally, when training on a task \(t\), SSCL is a special continual learning setting on a partially labeled dataset \(D^t = \bigcup_{b=0}^{[B]}D_{b}^t\) with \(B\) batches, where \(D_{b}^t = \{(x_{i}, y_{i})\}_{i \in b_{l}}\bigcup \{(x_{j})\}_{j \in b_{ul}} \) is a semi-supervised batch consisting of a labeled sub-batch \(b_{l}\) and an unlabeled sub-batch \(b_{ul}\). \(D_{b}^t\) is introduced when training on the current batch \(b\) and the performance on the task is evaluated after learning each batch. The above SSCL setting is similar to continual learning of \textit{New Instance} \cite{parisi2019continual}, while the dataset \(D^t\) for SSCL only consists of small amounts of labels rather than all the labels. We consider continual learning of \textit{New Class} \cite{parisi2019continual} with partially labeled data as a natural extension, where a collection of \(T\) semi-supervised datasets \(D = \bigcup_{t=0}^{[T]}D^t\) is sequentially learned. \(D^t\) is provided during training on the task \(t\), which includes several classes. After learning each task, all of the classes ever seen are evaluated without access to the task labels, i.e. the single-head evaluation \cite{chaudhry2018riemannian}. \subsection{A Systematic Study of Existing CL Methods} We adapt the representative continual learning strategies, including weight regularization methods~\cite{parisi2019continual} and memory replay ones~\cite{parisi2019continual}, to SSCL by considering \emph{unlabeled data} and provides a systematical analysis. In particular, we conduct extensive SSCL experiments on the SVHN dataset, where we equally split the training set into 30 batches with 3 labels per class in each batch. Notably, we learn various strong semi-supervised classifiers, including MT \cite{tarvainen2017mean}, VAT \cite{miyato2018virtual}, PL \cite{lee2013pseudo} and PI \cite{laine2016temporal} models in SSCL. We consider four learning strategies for all classifiers to verify the existence of catastrophic forgetting and analyze the underling reason, as follows: \begin{itemize} \item \textbf{Joint Training (JT):} The classifier is jointly trained on all the partially labeled data ever seen. \item \textbf{Sequential Training (ST):} The classifier is sequentially trained on the incremental partially labeled data. \item \textbf{Weight Regularization:} Representative approaches of weight regularization, including SI \cite{zenke2017continual}, MAS \cite{aljundi2018memory} and EWC \cite{kirkpatrick2017overcoming}, are implemented to the classifier to selectively stabilize parameters. \item \textbf{Memory Replay:} A memory buffer is implemented to replay old training data. Classical methods~\cite{rebuffi2017icarl,castro2018end} in CL use mean-of-feature to select samples, while in SSCL we do not have sufficient labels to perform selection. Therefore, we select data through uniform sampling, which is indeed competitive to existing selection methods as analyzed in~\cite{chaudhry2018riemannian} (See empirical results in Appendix A). \end{itemize} \begin{figure}[t] \centering \includegraphics[width=1\linewidth]{svhn30b_MT} \caption{Baselines that combine CL strategies to address SSCL. JT: Joint training of all the training samples ever seen. ST: Sequential training on the incremental data; SMB: ST with replaying the supervised data ever seen. SMB+UMB: SMB with an unsupervised memory buffer of 10000 images to replay unlabeled data. Weight regularization methods (EWC, MAS and SI) are implemented on only the supervised loss (-sl) and both the supervised loss and the unsupervised loss (-sl+ul). The gap between JT and SMB is around \(9.70\%\) in average, which is caused by the catastrophic forgetting of unlabeled data. } \label{svhn30b_MT} \vspace{-0.2cm} \end{figure} We extensively search the hyperparameters of all baselines and summarize the best results. For details like the search space, we refer the readers to Appendix B. We compare the performance of different learning strategies based on the MT classifier in Fig.~\ref{svhn30b_MT}. The results of other classifiers are similar and detailed in Appendix A. In Fig.~\ref{svhn30b_MT}, it can be seen that ST on the incremental partially labeled data significantly underperforms JT, suggesting the existence of catastrophic forgetting. Besides, simply adopting weight regularization methods~\cite{parisi2019continual,kirkpatrick2017overcoming,aljundi2018memory,zenke2017continual} on a semi-supervised classifier cannot address the issue in SSCL. We hypothesize that the regularization of parameter changes in such methods limits the learning of incremental data, see more experiments and detailed discussion in Appendix B. A potential future work can be designing proper regularization terms in SSCL. In comparison, using a supervised memory buffer (SMB), whose maximum size is of 900 images, to replay labeled data ~\cite{parisi2019continual,chaudhry2018riemannian} can effectively reduce the gap from JT but still has a large space to improve. Further, we evaluate a strategy with an additional unsupervised memory buffer (SMB+UMB), whose maximum size is of 10,000 images, to replay unlabeled data. Indeed, the extra buffer is about twice the size of a typical generator used in our method. Given an extra large memory buffer for unlabeled data, however, we observed that the performance of the memory replay approach cannot be further improved, implying that the unlabeled data are not fully exploited. In fact, we visualize the coverage of the UMB on the distribution of all the training data using t-SNE~\cite{maaten2008visualizing} embedding (see details in Appendix A). As shown in Fig.~\ref{coverage} (a), although the UMB has already stored around \(10 \%\) data of the entire dataset, it still cannot cover the distribution of training data very well. Therefore, a common issue of existing CL strategies in the semi-supervised scenarios is that they cannot effectively capture and exploit the distribution of unlabeled data. We identify this as the \emph{catastrophic forgetting of unlabeled data} problem, which is challenging because the incremental unlabeled data are massive and lack annotations. This motivates us to propose two new strategies to continually learn a generative model that can successfully capture the data distribution (see Fig.~\ref{coverage}, b) given partially labeled data. \begin{figure} \centering \subfigure[UMB]{ \includegraphics[width=1.5in]{Gen_Coverage_Ours-a}} \hspace{0.01in} \subfigure[ORDisCo]{ \includegraphics[width=1.5in]{Gen_Coverage_Ours-b}} \caption{Data coverage of an unsupervised memory buffer, i.e. UMB (a), and the samples generated from ORDisCo (b). ORDisCo has a less storage cost but achieves a better result.} \label{coverage} \vspace{-0.3cm} \end{figure} \section{Method} Based on the empirical analysis above, in this section, we first describe our framework that interdependently trains a classifier, a discriminator and a generator on the incremental semi-supervised data in Sec.4.1. Then, in Sec.4.2, we present two new strategies to mitigate catastrophic forgetting of the unlabeled data. \begin{figure}[t] \centering \includegraphics[width=0.90\linewidth]{DisCo} \caption{Deep online replay with discriminator consistency (ORDisCo). The partially labeled data are incrementally learned in the interplay of \(C\), \(G\), and \(D\). To mitigate catastrophic forgetting and better exploit the unlabeled data, we implement \ding{172} online semi-supervised generative replay in \(C\) and \ding{173} stabilization of discrimination consistency in \(D\). \(z\) and \(y'\) are the noise and the labels for conditional sampling, where the generated samples are applied as both labeled and unlabeled data for replay. Here, \(sl\) and \(ul\) stand for supervised and unsupervised losses, respectively. } \label{DisCo} \vspace{-0.3cm} \end{figure} \subsection{Conditional Generation on Incremental Semi-supervised Data} Different from existing generative replay methods~\cite{shin2017continual,wu2018memory,ostapenko2019learning}, we consider a SSCL setting where partially labeled data are given. Inspired by the state-of-the-art semi-supervised learning (SSL) GAN~\cite{chongxuan2017triple,li2019triple}, we build up a triple-network structure that continually learns a classifier together with a conditional generative adversarial network (GAN) to better exploit the unlabeled distribution from a few labeled data in SSCL. Both the classifier and the conditional generator produce ``fake'' data-label pairs and the discriminator focuses on discriminating if a data-label pair is real or fake. Compared to other SSL GANs~\cite{springenberg2015unsupervised,salimans2016improved,mirza2014conditional}, our framework is theoretically optimal under a nonparametric assumption and ensures that the GAN to capture the data distribution and the classifier to make predictions actually help each other~\cite{chongxuan2017triple,li2019triple}. Formally, the entire model includes a classifier \(C\), a generator \(G\) and a discriminator \(D\). Correspondingly, the optimization problem is to learn three groups of parameters as \(\{ \theta_C, \theta_G, \theta_D\}\). In such a triple-network architecture, \(C\) tries to improve its ability of classification and generate pseudo-labels for the conditional generation in \(D\) and \(G\). While, \(D\) and \(G\) continually learn and recover the data distributions seen in the incremental semi-supervised data. The general framework is shown in Fig.~\ref{DisCo} and we will describe the objective function for each component below. To learn a classifier \(C\) from partially labeled data, the loss functions can be generally defined as a supervised loss \(L_{sl} (\theta_{ C})\) and an unsupervised loss \(L_{ul} (\theta_{ C})\). Since our motivation is to continually capture and exploit the unlabeled data, we build up our method with a supervised memory buffer \(smb\) to replay a few labeled data. We define \(L_{sl} (\theta_{ C})\) and \(L_{ul} (\theta_{ C})\) as a cross entropy term and a consistency regularization term~\cite{tarvainen2017mean}: \begin{equation} {L}_{C,pl}(\theta_{ C}) = L_{sl} (\theta_{ C})+ L_{ul} (\theta_{ C}), \label{eq:pl loss} \end{equation} \begin{equation} L_{sl} (\theta_{ C}) = \mathbb{E}_{x,\, y\sim b_l \cup smb}\,[-y \, \log\,C(x)], \label{eq:sl loss} \end{equation} \begin{equation} L_{ul} (\theta_{ C}) = \mathbb{E}_{x\sim b_{ul}, \epsilon, \epsilon'}\,[\parallel C(x, \epsilon) - C'(x, \epsilon') \parallel^2], \label{eq:ul loss} \end{equation} where \(C'\) is the exponential moving average of \(C\) \cite{tarvainen2017mean}, \(\parallel \cdot \parallel^2\) is the square of the \(l_2\)-norm, and \(\epsilon\) and \(\epsilon'\) denote two different random noises, e.g. dropout masks. We mention that there are other options of unlabeled losses for SSL such as~\cite{miyato2018virtual,laine2016temporal,sohn2020fixmatch}. We leave a systematical study of this for future work. Next, we design a semi-supervised discriminator, which aims to distinguish if a data-label pair is from the labeled dataset or is a fake one: \begin{equation} \begin{split} {L}_{D,pl}(\theta_{ D}) = & \,\, \mathbb{E}_{x, \, y\sim b_l \cup smb}\,[\log ( D(x, y) )] \\ & + \alpha \, \mathbb{E}_{y'\sim p_{y'}, z \sim p_{z}}\,[\log( 1- D(G(z, y'), y') )] \\ & + (1-\alpha) \, \mathbb{E}_{x\sim bu}\,[\log(1 - D(x, C(x)) )], \end{split} \label{eq:netD loss} \end{equation} where the sampling distribution of label \(y'\) is uniform \({p}_{y'} = \textit{U}\{ 1,2, ..., k\}\) among all the \(k\) classes ever seen and the noise \(z\) is Gaussian \(p_{z} = N(0, 1)\). The first two terms are the regular loss functions for conditional GAN, computed on the labeled training data and the generated data, respectively. While the third term is computed on the unlabeled sub-batch \(b_{ul}\) with the pseudo-labels predicted by \(C\). We assign \(\alpha\) and \(1-\alpha\) as the coefficients of the last two terms to keep balance with the first term. Finally, the generator applies a regular loss function for conditional generation as follows: \begin{equation} {L}_{G}(\theta_{G}) = \mathbb{E}_{y'\sim p_{y'}, z \sim p_{z}}\,[-\log(1 - D(G(z, y'), y'))]. \\ \label{eq:netG loss} \end{equation} \subsection{Improving Continual Learning of Unlabeled Data} \begin{figure}[t] \centering \includegraphics[width=1\linewidth]{SVHN_T+G_data} \caption{Conditional samples in SSCL on SVHN (after learning 5 batches of partially labeled data). (a) Training data in SVHN. (b) Conditional samples from a conditional GAN baseline with replay of supervised data (SMB). (c) Conditional samples from ORDisCo with the same SMB. Each row has a fixed label. Our method outperforms the baseline in terms of label consistency because of the two strategies proposed.} \label{T+G_data} \vspace{-0.2cm} \end{figure} In such a framework, after training on a semi-supervised batch \(b_i\), \(C\) learns the distribution of \(b_{i,ul}\) from \(b_{i,l}\) for classification while \(G\) and \(D\) learns that for conditional generation. When accommodating for the next batch \(b_{i+1} \), all of the three networks adjust the learned parameters of the previous batch and suffer from \emph{catastrophic forgetting}, especially on unlabeled data. Because unlabeled data are key to solve semi-supervised tasks, without effective strategies to continually learn the unlabeled data from limited labels, the generative model would fail to assign correct labels to the conditional samples during the incremental learning (see Fig.~\ref{T+G_data} for empirical evidence). To this end, we propose two strategies: online semi-supervised generative replay and stabilization of discrimination consistency. \begin{table}[t] \centering \caption{Time and storage complexity of different generative replay strategies. \(B\) is the total number of batches to learn. }\smallskip \resizebox{1\columnwidth}{!}{ \begin{tabular}{cccc} \specialrule{0.01em}{1.2pt}{1.5pt} &Strategy (1) \cite{ostapenko2019learning} &Strategy (2) \cite{shin2017continual,wu2018memory} &ORDisCo \\ \specialrule{0.01em}{1.2pt}{1.5pt} Algorithm & offline & offline & online\\ Time &O(\(B\)) &O(\(B^2\)) &O(\(B\)) \\ Storage &O(\(B\)) &O(\(1\)) & O(\(1\)) \\ \specialrule{0.01em}{1.5pt}{1.5pt} \end{tabular} } \label{complexity} \vspace{-.4cm} \end{table} First, we propose a time- and storage-efficient strategy of online semi-supervised generative replay to improve CL of unlabeled data in \(C\). Existing generative replay methods \cite{shin2017continual,wu2018memory,ostapenko2019learning,xiang2019incremental,liu2020generative} often offline sample generated data or embedding, or save the old generators, which results in additional time and storage cost. Let's consider two main strategies for offline generative replay: (1) All old generators learned on each task or batch are saved, and replay conditional samples to a classifier \cite{ostapenko2019learning}; and (2) After learning each task or batch, the generator is saved. In the next task or batch, the generator replays conditional samples with the new training samples to update the generator and the classifier \cite{shin2017continual,wu2018memory, xiang2019incremental,liu2020generative}. In contrast, we online generate conditional samples from \(G\) and replay them to \(C\) rather than offline save a model for replay. As shown in Table \ref{complexity}, our online strategy is more time- and storage-efficient to exploit the large amounts of unlabeled data in SSCL (See detailed calculation in Appendix E). The conditional samples are used as both labeled data and unlabeled data to fully exploit the learned data distribution: \begin{equation} {L}_{C}(\theta_{C}) = {L}_{C,pl}(\theta_{ C}) + L_{G\rightarrow C} (\theta_{C}), \label{eq:netC loss} \end{equation} where the first term is defined in Eqn.~\ref{eq:pl loss} and the second term exploits the data sampled from the generator in an online manner, as follows: \begin{equation} \begin{split} & L_{G\rightarrow C} (\theta_{C}) = \mathbb{E}_{y'\sim p_{y'}, z \sim p_{z}}\,[-y' \, \log\,C(G(z, y'))] \\ & + \mathbb{E}_{y'\sim p_{y'}, z \sim p_{z}, \epsilon, \epsilon'}\,[\parallel C(G(z, y'), \epsilon) - C'(G(z, y'), \epsilon') \parallel^2], \end{split} \label{eq:replay loss} \end{equation} which is in analogy to the losses of labeled and unlabeled training data in Eqn.~\ref{eq:sl loss}, \ref{eq:ul loss}. Further, to explicitly mitigate catastrophic forgetting of unlabeled data in \(D\), we add a regularization term to selectively penalize changes of the parameters \(\theta_D\) from the old parameters \(\theta_D^*\) learned from the previous batches \(1:b\), depending on their contributions to the consistency of discriminating data-label pairs: \begin{equation} {L}_{D}(\theta_{ D}) = {L}_{D,pl}(\theta_{ D}) + \lambda \sum_{i} {\xi}_{1:b, i}( \theta_{D,i } - \theta_{D, i}^{*})^{2}, \label{eq:netD+reg loss} \end{equation} where the first term is defined in Eqn.~\ref{eq:netD loss} and \({\xi}_{1:b, i}\) is the strength of penalty on the changes of parameter \(i\). It is computed as \begin{equation} {\xi}_{1:b, i} = ((b-1) \times {\xi}_{1:b-1, i} + {\xi}_{b, i}) / b, \end{equation} where \begin{equation} {\xi}_{b, i} = \mathbb{E}_{x\sim bu} \, \left[ \parallel \frac{\partial \parallel (D(x, C(x))\parallel^2}{\partial \theta_{D,i}} \parallel \right]. \end{equation} After training on each batch \(b\), we measure \({\xi}_{b, i}\) through the expected norm of gradients on each parameters to the squared \(l_2\)-norm of discriminating the pairs of unlabeled data and their pseudo-labels predicted by \(C\). Then we update \({\xi}_{1:b, i}\) by its average. Therefore, the changes of parameters will be penalized if they change the predictions of data-label pairs on the old unlabeled batches and the learned pseudo-labels. Note that, since the regularization is in a re-weighted weight decay form, which is non-negative and is zero in expectation given an optimal discriminator, the regularization won't hurt the consistency and convergence given different initialization and data sequences. \section{Experiment} In this section, we first introduce the benchmark dataset and experiment settings of SSCL. Then we show the results of our method and the baselines on SSCL. \subsection{Experiment Setup} \textbf{Dataset:} SVHN \cite{netzer2011reading} is a dataset of colored digits, including 73,257 training samples and 26,032 testing samples of size 32 $ \times $ 32. CIFAR10 \cite{krizhevsky2009learning} is a dataset of 10-class colored images with 50,000 training samples and 10,000 testing samples of size 32 $ \times $ 32. Tiny-ImageNet is a dataset of 200-class natural images with 500, 50, 50 samples per class for training, validating and testing, respectively. We randomly choose 10 or 20 classes of images from Tiny-ImageNet, resized to 32 $ \times $ 32 or 64 $ \times $ 64. For the experiment of \textit{New Instance}, we randomly split the training images of SVHN, CIFAR10 and Tiny-ImageNet into 30, 30 and 10 batches. Then we allocate a small amount of labels to each batch as the benchmark of SSCL. To simplify the notation, the benchmarks are denoted as ``dataset-(number of labels / class / batch)'', including SVHN-1, SVHN-3, CIFAR10-5, CIFAR10-13 and Tiny-ImageNet-5. A model incrementally learns the semi-supervised batch and is evaluated on the test set after training on each batch. For the experiment of \textit{New Class}, we use the same semi-supervised splits as \textit{New Instance}, but construct the sequence as 5 binary classification tasks, where the partially labeled data of two new classes are provided in each task. We follow the single-head evaluation \cite{chaudhry2018riemannian} that all of the classes ever seen are evaluated without access to the task labels. \textbf{Architecture:} In our preliminary experiments (Fig. \ref{svhn30b_MT}, Appendix A), the classifiers use a Wide ResNet architecture (WRN-28-2), which is widely applied in SSL \cite{oliver2018realistic}. To accelerate training, ORDisCo applies a much simplified classifier similar to \cite{li2019triple}, including 9 convolution layers without residual connections. The simplified classifier achieves a comparable performance on the incremental semi-supervised data as WRN-28-2 (Fig. \ref{svhn30b_MT}, Appendix A). Our generator and discriminator use a similar architecture as \cite{li2019triple}, with spectral norm to stabilize training. We keep ORDisCo and all the baselines that directly compare with ORDisCo using the same architecture for fair comparison. Please see Appendix G for hyperparameters of ORDisCo. \textbf{Baselines:} All the SSL methods in our preliminary experiment (Fig. \ref{svhn30b_MT}, Appendix A) follow the same implementation as \cite{oliver2018realistic}, validated in Appendix B. Because mean teacher (MT) \cite{tarvainen2017mean} can be easily extended to many recent works \cite{iscen2019label,athiwaratkun2018there,luo2018smooth}, we choose it as the base model of SSL classifier in ORDisCo. We compare ORDisCo with the strongest baseline in the preliminary experiment, that the classifier is accessible to the labeled data ever seen through a supervised memory buffer (SMB). Since our motivation is to effectively capture and exploit the unlabeled data, we consider two extensions of SMB: (1) We combine SMB with an unsupervised memory buffer (UMB) of a similar size as our generator; and (2) We implement the \textit{Unified Classifier} \cite{hou2019learning}, the state-of-the-art method of incremental learning with memory replay, to better exploit the unsupervised memory buffer (UMB+UC). The Unified Classifier aims to address the imbalance between the small memory buffer and large amounts of training samples through regularizing the cosine distance of feature extractors in an unsupervised fashion to unify the prediction. \newcommand{\tabincell}[2]{\begin{tabular}{@{}#1@{}}#2\end{tabular}} \begin{table}[t] \centering \caption{Averaged accuracy (\%) of SSCL on Tiny-ImageNet. We randomly split training images of Tiny-ImageNet into 10 batches with equal number of labels (5 labels / class) in each batch. Here we show the results on the earlier 5 batches.}\smallskip \resizebox{1.00\columnwidth}{!}{ \begin{tabular}{clccccc} \specialrule{0.01em}{1.2pt}{1.5pt} \multicolumn{1}{c}{} & \multicolumn{1}{c}{Method} & \multicolumn{1}{c}{Batch 1} & \multicolumn{1}{c}{Batch 2} & \multicolumn{1}{c}{Batch 3} & \multicolumn{1}{c}{Batch 4} & \multicolumn{1}{c}{Batch 5} \\ \specialrule{0.01em}{1.5pt}{1.5pt} \multirow{3}*{\tabincell{c}{10-class \\ \(32 \times 32\)}} &SMB&43.00 &46.60 &55.40 &63.00 &59.80 \\ &SMB+UMB&43.80 &47.60 &55.20 &62.20 &63.40 \\ &ORDisCo&\textbf{45.20} &\textbf{54.40} &\textbf{59.60} &\textbf{65.40} &\textbf{69.20} \\ \specialrule{0.01em}{1.5pt}{1.5pt} \multirow{3}*{\tabincell{c}{20-class \\ \(32 \times 32\)}} &SMB&24.90 &32.50 &32.80 &38.70 &42.30 \\ &SMB+UMB&\textbf{25.20} &33.10 &33.60 &37.70 &42.60 \\ &ORDisCo&\textbf{25.20} &\textbf{33.30} &\textbf{36.50} &\textbf{42.00} &\textbf{45.10} \\ \specialrule{0.01em}{1.5pt}{1.5pt} \multirow{3}*{\tabincell{c}{10-class\\\(64 \times 64\)}} &SMB& \textbf{52.00} &53.00 &58.60 &66.00 &68.40 \\ &SMB+UMB&51.60 &57.00 &62.80 &68.40 &68.80 \\ &ORDisCo&51.20 &\textbf{60.20} &\textbf{65.20} &\textbf{70.40} &\textbf{72.80}\\ \specialrule{0.01em}{1.5pt}{1.5pt} \end{tabular} } \label{tiny} \vspace{-.2cm} \end{table} \subsection{SSCL of New Instance} We report the performance of ORDisCo and other baselines during SSCL of 30 incremental batches in Fig. \ref{SSCL_limit_label} (SVHN-1 and CIFAR10-5) and Appendix C (SVHN-3 and CIFAR10-13). ORDisCo significantly outperforms other baselines, particularly when the numbers of labels are smaller, i.e. SVHN-1 and CIFAR10-5. Compared with SMB, an additional unsupervised buffer (UMB) slightly improves the performance of SSCL on SVHN-3 and CIFAR10-13, but results in overfitting on SVHN-1 and CIFAR10-5 where the labeled data are extremely limited (See empirical results and analysis of the overfitting in Appendix A). The Unified Classifier better exploits the UMB through balancing the predictions on UMB and large amounts of unlabeled data, and thus slightly improves its performance. Also, the performance is only slightly increased by using a much larger UMB (See details in Appendix C). By contrast, ORDisCo can much better exploit the unlabeled data and substantially improve SSCL. We then evaluate ORDisCo on Tiny-ImageNet-5 with larger number of classes and larger-scale images in Table \ref{tiny}. Compared with SMB and SMB+UMB, ORDisCo achieves a much better performance on 10-class and 20-class of size \(32 \times 32 \) and 10-class of size \(64 \times 64\), through effective usage of the incremental unlabeled data to improve classification. Note that the reported performance is the result after training on each semi-supervised batch till convergence. Therefore, the outstanding performance of ORDisCo on limited partially labeled data, i.e. smaller numbers of labels and semi-supervised batches, indicates that ORDisCo can \emph{quickly learn a usable model} rather than waiting for more data to be collected. \begin{figure}[t] \centering \includegraphics[width=0.80\linewidth]{SSCL_SVHN_CIFAR10_limit_label} \caption{Averaged accuracy (\(\%\)) of SSCL on SVHN-1 and CIFAR10-5. ORDisCo (Ours) improves SMB by \(12.20\%\) and \(5.95\%\) at the final batch on SVHN-1 and CIFAR10-5, respectively. UMB: An unsupervised memory buffer of a similar size as our generator; UC: Using the unified classifier to exploit UMB.} \label{SSCL_limit_label} \vspace{-0.3cm} \end{figure} \begin{table}[t] \centering \caption{Ablation study on SVHN-1 and CIFAR10-5. Both online semi-supervised generative replay (Replay) and regularization of discrimination consistency (Reg) substantially improve SSCL.}\smallskip \resizebox{1\columnwidth}{!}{ \begin{tabular}{ccccc} \specialrule{0.01em}{1.2pt}{1.5pt} \multicolumn{1}{c}{} & \multicolumn{2}{c}{SVHN-1} & \multicolumn{2}{c}{CIFAR10-5} \\ Method & 15 Batch & 30 Batch & 15 Batch & 30 Batch \\ \specialrule{0.01em}{1.5pt}{1.5pt} SMB &38.08 &73.32 &59.61 & 67.18 \\ ORDisCo (+Replay, -Reg) &31.14 &84.66 &64.38 &71.69 \\ ORDisCo (+Replay, +Reg) &\textbf{55.07} &\textbf{85.52} &\textbf{66.58} &\textbf{73.13} \\ \specialrule{0.01em}{1.5pt}{1.5pt} \end{tabular} } \label{ablation} \vspace{-.2cm} \end{table} \subsection{Ablation Study and Analysis} Next, we analyze why ORDisCo improves continual learning of unlabeled data. ORDisCo enables a generative model to continually learn conditional generation from incremental semi-supervised data. Thus, the conditional generator of ORDisCo can much better cover the training data distribution than an unsupervised memory buffer of a similar size (Fig.~\ref{coverage}). We make the ablation study (SVHN-1 and CIFAR10-5 in Table \ref{ablation}, SVHN-3 and CIFAR10-13 in Appendix C) to validate the effects of the proposed strategies in ORDisCo, that both the online semi-supervised generative replay (refer to as Replay) and the regularizer to stabilize discrimination consistency (refer to as Reg) can significantly improve SSCL. The ablation study shows that the effects of the regularization on discrimination consistency are much more significant when the data sources are \emph{limited}, i.e. fewer labels and semi-supervised batches. \begin{table}[t] \centering \caption{Averaged accuracy (\(\%\)) of a jointly trained classifier to predict conditional samples learned from earlier batches on SVHN-1 and CIFAR10-5, where regularization of discrimination consistency (Reg) significantly improves generative replay. }\smallskip \resizebox{1\columnwidth}{!}{ \begin{tabular}{ccccc} \specialrule{0.01em}{1.2pt}{1.5pt} \multicolumn{1}{c}{} & \multicolumn{2}{c}{SVHN-1} & \multicolumn{2}{c}{CIFAR10-5} \\ Method & 5 Batch & 15 Batch & 5 Batch & 15 Batch \\ \specialrule{0.01em}{1.5pt}{1.5pt} SMB &\textbf{27.37} &51.45 &43.37 &70.64 \\ ORDisCo (+Replay, -Reg)&16.95 &37.89 &49.98 &68.67 \\ ORDisCo (+Replay, +Reg)&25.46 &\textbf{64.93} &\textbf{64.15} &\textbf{81.13} \\ \specialrule{0.01em}{1.5pt}{1.5pt} \end{tabular} } \label{generated data accuracy} \vspace{-.2cm} \end{table} To verify how the discrimination consistency improves SSCL, we use a jointly trained classifier on the semi-supervised dataset, which achieves considerable performance of classification (\(94.38\%\) for SVHN, \(87.37\%\) for CIFAR10), to evaluate conditional samples. We present the accuracy of the classifier to predict conditional samples on the earlier 5 and 15 batches of SVHN-1 and CIFAR10-5, which include only a few labels per batch. As shown in Table. \ref{generated data accuracy}, the predictions on the conditional samples of ORDisCo are significantly better than the one of a sequentially trained conditional GAN with SMB. Because the quality of conditional samples is generally poor when the partially labeled data are limited, replay of such conditional samples to the classifier in ORDisCo will decrease its performance to predict pseudo-labels of unlabeled data, and further interfere with conditional generation. While, the regularizer on discrimination consistency largely alleviates this issue through stabilizing the learned distribution of unlabeled data in the discriminator, which is critical to SSCL. \subsection{SSCL of New Class} ORDisCo can be naturally extended to incremental learning of New Class in semi-supervised scenarios. We consider an incremental dataset consisting of 5 binary classification tasks, where the partially labeled data of two new classes are introduced in each task. We keep the total number of labels the same as the one used in New Instance. As shown in Table \ref{New Class}, ORDisCo significantly outperforms SMB, SMB+UMB and SMB+UMB+UC through more effective usage of the unlabeled data. \begin{table}[t] \centering \caption{Averaged accuracy (\%) of SSCL of New Class. We follow the same semi-supervised splits as New Instance on SVHN-1, CIFAR10-5, or 10-class Tiny-ImageNet-5 of the size \(32 \times 32\), but construct a sequence of 5 binary classification tasks.} \smallskip \resizebox{1.00\columnwidth}{!}{ \begin{tabular}{clccccc} \specialrule{0.01em}{1.2pt}{1.5pt} \multicolumn{1}{c}{Split} & \multicolumn{1}{c}{Method} & \multicolumn{1}{c}{Task 1} & \multicolumn{1}{c}{Task 2} & \multicolumn{1}{c}{Task 3} & \multicolumn{1}{c}{Task 4} & \multicolumn{1}{c}{Task 5} \\ \specialrule{0.01em}{1.5pt}{1.5pt} \multirow{4}*{\tabincell{c}{SVHN-1}} &SMB&81.80 &50.73 &39.77 &40.41 &35.46 \\ &SMB+UMB&\textbf{83.30} &50.53 &35.92 &33.00 &37.35 \\ &SMB+UMB+UC&83.04 &53.10 &36.18 &36.83 &38.33 \\ &ORDisCo&82.72 &\textbf{54.69} &\textbf{60.68} &\textbf{56.18} &\textbf{53.79} \\ \specialrule{0.01em}{1.5pt}{1.5pt} \multirow{4}*{\tabincell{c}{CIFAR10-5}} &SMB&\textbf{95.78} &74.54 &61.63 &56.85 &55.12 \\ &SMB+UMB&95.50 &76.68 &63.22 &62.34 &60.52 \\ &SMB+UMB+UC&95.67 &\textbf{77.94} &65.95 &63.33 &62.43 \\ &ORDisCo&95.60 &77.23 &\textbf{68.62} &\textbf{66.49} &\textbf{65.91} \\ \specialrule{0.01em}{1.5pt}{1.5pt} \multirow{4}*{\tabincell{c}{TinyImageNet-5}} &SMB&88.50 &75.17 &67.17 &67.58 &65.47 \\ &SMB+UMB &87.83 &80.17 &68.33 &71.33 &67.13 \\ &SMB+UMB+UC&\textbf{88.67} &79.08 &69.94 &71.13 &69.87 \\ &ORDisCo&88.50 &\textbf{83.17} &\textbf{70.56} &\textbf{73.92} &\textbf{71.07 } \\ \specialrule{0.01em}{1.5pt}{1.5pt} \end{tabular} } \label{New Class} \vspace{-.4cm} \end{table} \subsection{Conditional Generation in SSCL} We present the conditional samples from ORDisCo and a sequentially trained conditional GAN with SMB during SSCL in Fig. \ref{conditional generation in SSCL} (See complete conditional samples of ORDisCo in Appendix D), where conditional generation is improved from incremental learning of partially labeled data. Due to more effective usage of unlabeled data, ORDisCo can generate high-quality conditional samples in SSCL, significantly better than the SMB baseline. \begin{figure}[t] \centering \subfigure[SVHN-3]{\includegraphics[height = 1.9cm]{conditional_samples_svhn-3}} \\ \vspace{-.1cm} \subfigure[CIFAR10-13]{\includegraphics[height = 1.9cm]{conditional_samples_cifar10-13}} \caption{Conditional generation in SSCL. We show the conditional samples of `0' in SVHN-3 and `horse' in CIFAR10-13. The column denotes the number of incremental batches learned by the conditional generator to generate images in each row. Starting from the sixth batch (the red box), ORDisCo can generate high-quality conditional samples, significantly better than the SMB baseline.} \label{conditional generation in SSCL} \vspace{-.4cm} \end{figure} \section{Conclusion} In this work, we provide a systematic analysis of semi-supervised continual learning, which is a realistic yet challenging setting without extensive study. Then we propose a novel method to continually learn a conditional GAN with a classifier from partially labeled data. Extensive evaluations on various benchmarks show that our method can effectively capture and exploit the unlabeled data in both classification tasks and conditional generation. Since our method can be a plug-and-play approach for semi-supervised continual learning, a wide range of semi-supervised learning approaches for classification and conditional generation can be flexibly implemented into the framework, which is our further direction. Another further work is to use ORDisCo on Mindspore\footnote{https://www.mindspore.cn}, a new deep learning computing framework. \section*{Acknowledgement} This work was supported by the National Key Research and Development Program of China (Nos. 2017YFA0700904, 2020AAA0104304), NSFC Projects (Nos. 61620106010, 62076145), Beijing NSF Project (No. L172037), Tsinghua-Huawei Joint Research Program. C. Li was supported by the fellowship of China postdoctoral Science Foundation (2020M680572), and the fellowship of China national postdoctoral program for innovative talents (BX20190172) and Shuimu Tsinghua Scholar. \iffalse {\small \bibliographystyle{ieee_fullname}
{'timestamp': '2021-04-12T02:06:42', 'yymm': '2101', 'arxiv_id': '2101.00407', 'language': 'en', 'url': 'https://arxiv.org/abs/2101.00407'}
arxiv
\section{Introduction} Semantic role labeling (SRL), as one of the core tasks to identify the semantic predicates in text as well as their semantic roles, has sparked much interest in natural language processing (NLP) community \cite{pradhan-etal-2005-semantic,lei-etal-2015-high,XiaL0ZFWS19}. SRL is a shallow semantic parsing, aiming to uncover the predicate-argument structures, such as `\emph{who did what to whom, when and where}', The task can be beneficial for a range number of downstream tasks, such as information extraction \cite{ChristensenMSE11,bastianelli-etal-2013-textual}, question answering \cite{shen-lapata-2007-using,berant-etal-2013-semantic} and machine translation \cite{xiong-etal-2012-modeling,shi-etal-2016-knowledge}. Traditionally, SRL is accomplished via two pipeline steps: predicate identification \cite{SCHEIBLE10} and argument role labeling \cite{pradhan-etal-2005-semantic}. More recently, there is growing interest in end-to-end SRL, which aims to achieve both two subtasks by a single model \cite{he-etal-2018-jointly}. Given a sentence, the goal is to recognize all possible predicates together with their arguments jointly. Figure \ref{intro} shows an example of end-to-end SRL. The end-to-end joint architecture can greatly alleviate the error propagation problem, and meanwhile simplify the overall decoding process, thus receives increasing attention. Graph-based models have been the mainstream methods to end-to-end SRL, which are achieved by enumerating all the possible predicates and their arguments exhaustively \cite{he-etal-2018-jointly,cai-etal-2018-full,LiHZZZZZ19}. Their results show that end-to-end modeling can obtain better SRL performance. \begin{figure}[!t] \centering \includegraphics[width=0.92\columnwidth]{illus/intro3.pdf} \caption{ An example of end-to-end SRL, where two propositions are shown in one sentence. } \label{intro} \end{figure} Alternatively, the transition-based framework offers another solution for end-to-end modeling, which is totally orthogonal to the graph-based models. Transition-based models have been widely exploited for end-to-end sequence labeling \cite{zhang-clark-2010-fast,LyuZJ16,ZhangZF18}, structural parsing \cite{zhou-etal-2015-neural,dyer-etal-2015-transition,YuanJT19} and relation extraction \cite{wang-etal-2018-neural-transition,ZhangQZLJ19}, which are closely related to SRL. These models can also achieve very competitive performances for a range of tasks, and meanwhile maintain high efficiencies with linear-time decoding complexity. In this work, we present the first work of exploiting the neural transition-based architecture to end-to-end SRL. The model handles SRL incrementally by predicting a sequence of transition actions step by step, which are used to detect all predicates as well as their semantic roles in a given sentence. The two subtasks of end-to-end SRL, predicate identification and argument role labeling, are performed mutually in a single model to make full interactions of them. For argument role labeling, the recognition is conducted in a close-first way, where the near-predicate roles are processed first. The partial outputs of the incremental processing are denoted as transition states. In addition, we suggest explicit high-order compositions to enhance our transition-based model, leveraging the precedent partially-recognized argument-predicate structures for the current action classification. Our neural transition system is built upon standard embedding-based word representations, and then is improved with dependency-aware representations by using recursive TreeLSTM \cite{tai-etal-2015-improved}. Concretely, we embed the surface words, characters, POS tags and dependency structures as input representations. During decoding, we represent the transition states by using standard BiLSTM \cite{hochreiter1997long} and Stack-LSTM \cite{dyer-etal-2015-transition} to encode the elements in buffers and stacks, respectively. Finally, we predict transition actions incrementally based on the state representations. We conduct experiments on dependency-based SRL benchmarks, including CoNLL09 \cite{hajic-etal-2009-conll} for the English language, and Universal Proposition Bank \cite{akbik2015generating,akbik2016polyglot} for seven other languages. Our end-to-end neural transition model wins the best results against the baselines, giving the state-of-the-art performances on both the predicate identification and argument role labeling, meanwhile keeping efficient on decoding. We also show that with recent contextualized word representations, e.g., ELMo \cite{devlin-etal-2019-bert}, BERT \cite{PetersNIGCLZ18} or XLNet \cite{YangDYCSL19}, the overall SRL performances can be further improved. In-depth analysis is conducted to uncover the important components of our final model, which can help comprehensive understanding of our model. Following we summarize our contributions: $\bullet$ We fill the gap in the literature of employing neural transition-based model for end-to-end SRL. We also enhance the parsing procedure with a close-first scheme. $\bullet$ We compose the high-order features (i.e., with one more predicate-role attachments from multiple predicates) in our transition framework for end-to-end SRL to model long-term substructure information explicitly. $\bullet$ Our transition framework wins new state-of-the-art performances against all current graph-based methods on benchmark datasets, meanwhile being faster on decoding. \section{Related Work} \citeauthor{gildea-jurafsky-2000-automatic} (\citeyear{gildea-jurafsky-2000-automatic}) pioneer the task of semantic role labeling, as a shallow semantic parsing. Approaches for SRL can be largely divided into two folds. Earlier efforts are paid for designing hand-crafted discrete features with machine learning classifiers \cite{pradhan-etal-2005-semantic,PunyakanokRY08,zhao-etal-2009-multilingual-dependency}. Later, A great deal of work takes advantages of neural networks with automatic distributed features \cite{fitzgerald-etal-2015-semantic,roth-lapata-2016-neural,marcheggiani-titov-2017-encoding,strubell-etal-2018-linguistically,Fei06295}. Also it is worth noticing that many previous work shows that integrating syntactic tree structure can greatly facilitate the SRL \cite{marcheggiani-etal-2017-simple,zhang-etal-2019-syntax-enhanced,Crossfei9165903}. Prior works traditionally separate the SRL into two individual subtasks, i.e., predicate disambiguation and argument role labeling. They mainly conduct argument role labeling based on the pre-identified predicate oracle. More recently, several researches consider the end-to-end solution that handles both two subtasks by one single model. All of them employs graph-based neural model, exhaustively enumerating all the possible predicate and argument mentions, as well as their relations \cite{he-etal-2018-jointly,cai-etal-2018-full,LiHZZZZZ19,fei-etal-2020-high}. The distinctions among them are quite slight, mostly lying in the encoder, or relation scorer. For example, \citeauthor{he-etal-2018-jointly} (\citeyear{he-etal-2018-jointly}) use the BiLSTM \cite{hochreiter1997long} as base encoder, and use a feed-forward layer as predicate-argument relation scorer, while \citeauthor{cai-etal-2018-full} (\citeyear{cai-etal-2018-full}) employ a biaffine scorer, and \citeauthor{LiHZZZZZ19} (\citeyear{he-etal-2018-jointly}) enhance the BiLSTM with highway connections. Graph-based and transition-based models are always two mainstream approaches for structural learning. In this work, we employ a neural transition model, an algorithm that has been extensively exploited for a wide range of NLP parsing tasks, e.g., part-of-speech (POS) tagging \cite{zhang-clark-2010-fast,LyuZJ16}, word segmentation \cite{zhang-etal-2016-transition,ZhangZF18}, dependency parsing \cite{zhou-etal-2015-neural,dyer-etal-2015-transition,YuanJT19} and information extraction \cite{wang-etal-2018-neural-transition,ZhangQZLJ19}etc. Note that we have no bias on the graph-based and transition-based models, and both the two kinds of models have their own advantages and disadvantages. Compared with graph-based models, one big advantage of transition-based approaches is that high-order features (i.e., subtrees, partial parsed results) can be explicitly modeled conveniently by using transition states (i.e., state representation). Currently there is no work for transition-based neural SRL. Besides, transition-based model can achieve highly competitive task performances meanwhile with good efficiency, i.e., linear-time encoding complexity. It worth noticing that \citeauthor{choi-palmer-2011-transition} (\citeyear{choi-palmer-2011-transition}) employ a transition model for handling SRL. Unfortunately their work is based on discrete features, while ours is in the literature the first neural transition-based work. We also present two enhancements for the task, i.e., 1) close-first parsing scheme, and 2) high-order feature composition. Besides, our work focuses on end-to-end SRL, but \citeauthor{choi-palmer-2011-transition} (\citeyear{choi-palmer-2011-transition}) assume that predicates are already given. \begin{figure*}[!t] \centering \subfigure[The transition system.]{ \label{sequence-a} \includegraphics[width=1.22\columnwidth]{illus/framework-vx2-a.pdf}} \subfigure[Model architecture.]{ \label{sequence-b} \includegraphics[width=0.78\columnwidth]{illus/framework-vx1-b.pdf}} \caption{ Illustration of the transition framework, where the input sequence is the same as that in Figure \ref{intro}. For brevity, here we omit the role labeling operation, as it is performed with \emph{LEFT/RIGHT-ARC} actions synchronously. } \label{sequence} \end{figure*} \section{Method} Following prior end-to-end SRL work \cite{he-etal-2018-jointly,LiHZZZZZ19}, we treat the task as predicate-argument-role triplets prediction. Given an input sentence $S = \{w_1, \cdots, w_n\}$, the transition system is expected to output a set of triplets $Y \in P \times A \times R$, where $P = \{p_1, \cdots, p_k\}$ are all possible predicate tokens, $A = \{a_1, \cdots, a_l\}$ are all associated argument tokens, and $R$ are the corresponding role labels for each $a_i$. Technically, we model $Y$ as a graph structure, where the nodes are predicates or arguments, and the directed edges represent the roles from predicate to argument. For example the sentence in Figure \ref{intro}, the final outputs are four triplets: $<$\emph{stay}, \emph{silent}, \emph{A3}$>$, $<$\emph{stay}, \emph{victims}, \emph{A1}$>$, $<$\emph{changes}, \emph{stay}, \emph{A-TMP}$>$ and $<$\emph{changes}, \emph{nothing}, \emph{A1}$>$. In this section, we first elaborate the transition system including the states and actions. We then describe the vanilla neural transition model, upon which we further introduce the high order model. \subsection{Transition System} Our transition framework transforms the structural learning into a sequence of action predictions. The system consists of \emph{actions} and \emph{states}. The actions are used to control state transitions, while the states store partially parsed results. \paragraph{States.} We define the transition states as $s = (\sigma_l, \alpha_l, \lambda_p, \alpha_r, \sigma_r, \beta, Y)$. We denote that the $\sigma_l$ and $\sigma_r$ are stacks holding processed arguments in left-side ($l$) and right-side ($r$), respectively, $\alpha_l$ and $\alpha_r$ are the corresponding stacks temporarily storing the arguments popped out of $\sigma_*$ ($*$ $\in$ \{$l$,$r$\}) which will be pushed back later. $\lambda_p$ is a variable referring to a candidate predicate. $\beta$ is a buffer loading the unprocessed words in a sentence. $Y$ is a container storing the output triplets. \paragraph{Actions.} We design total six actions as follows. \begin{itemize} \setlength{\topsep}{0pt} \setlength{\itemsep}{0pt} \setlength{\parsep}{0pt} \setlength{\parskip}{0pt} \item NO-PRD, current candidate $w_i$ is not a predicate, so moves $w_i$ from $\beta$ to $\sigma_l$ while popping the top element out of $\sigma_r$. \item PRD-GEN, current candidate $w_i$ is a predicate (i.e., $p_j$), so generate representation for $p_j$ onto $\lambda_p$. \item LEFT-ARC, the top element in $\sigma_l$ is a argument (i.e, $a_t$), so assign an arc between $p_j$ and $a_t$, and pop the top element out of $\sigma_l$ into $\alpha_l$. \item RIGHT-ARC, the top element in $\sigma_r$ is a argument (i.e, $a_t$), so assign an arc between $p_j$ and $a_t$, and pop the top element out of $\sigma_r$ into $\alpha_r$. \item NO-ARC, no arc between $p_j$ and the top element in $\sigma_l$ or $\sigma_r$, so pop the top elements out of $\sigma_l$ or $\sigma_r$ into $\alpha_l$ or $\alpha_r$. \item SHIFT, end of the detection of arguments for $p_j$. Pop all the elements out of $\alpha_{*}$ into $\sigma_{*}$, clear $\lambda_p$, and moves $w_i$ from $\beta$ to $\sigma_l$ while popping the top element out of $\sigma_r$. \end{itemize} \vspace{-10pt} \paragraph{Parsing scheme.} The vanilla transition framework generally process the words in a sentence incrementally from left to right, while such reading scheme may be rigid for SRL parsing. Intuitively, it is always easier for humans to first grasp the core ideas then dig into more details. To this end, we consider a \emph{close-first} parsing procedure \cite{goldberg-elhadad-2010-efficient,cai-lam-2019-core,kurita-sogaard-2019-multi}. We first perform recognition for any possible predicate, e.g., $p_j$, and then the process of detecting the arguments of $p_j$ starts down the path from near-to-$p_j$ to far-to-$p_j$, until all the arguments are determined. Given a sentence, before conducting the transitions, the $\sigma_r$ will pre-load all the words from $\beta$ except the first word in reverse order. When a predicate is determined, the system starts searching for its arguments in leftward and rightward alternatively, from near to far. Once an arc is confirmed, a labeler assigns a role label for the argument. It is worth noticing that only a subset of actions are legal to a certain transition state. And invalid actions can lower encoding efficiency, and lead to bad directed graph structure. For example, a \emph{NO-PRD} action must be followed by either \emph{NO-PRD} or \emph{PRD-GEN} action, and \emph{*-ARC} must starts by a \emph{PRD-GEN} action. We thus also design some constraints for each action. Figure \ref{sequence-a} shows the transition process based on the example sentence in Figure \ref{intro}. \subsection{The Vanilla Neural Model}\label{vanilla model} \paragraph{Word representation.} We first use the word form representation under two types of settings: $\bm{v}^w_i,\tilde{\bm{v}}^w_i $, where $\bm{v}^w_i$ is the representation initialized with a pre-trained embedding vector for word $w_i$, which further can be trained, and $\tilde{\bm{v}}^w_i$ is the fixed version. We also use convolutional neural networks (CNNs) to encode characters inside a word $w_i$ into character-level representation $\bm{v}^{c}_i$. In addition, given the input sentence $S$, we exploit the POS tag of the tokens, and use the embedding $\bm{v}^{pos}_i$ via a lookup table. \paragraph{Dependency features enhancement.} Besides, we employ a TreeLSTM \cite{tai-etal-2015-improved,miwa-bansal-2016-end} to encode the dependency structural feature representation $\bm{v}^{syn}_i$ for each corresponding word $w_i$. We concatenate these representations into unified input representation: $\bm{x}_i = [\bm{v}^w_i ; \tilde{\bm{v}}^w_i;\bm{v}^{c}_i;\bm{v}^{pos}_i;\bm{v}^{syn}_i ]$ Then, a BiLSTM is used as encoder for learning the context representations. We then concatenate two hidden states at each time step $i$ as the sequence representation: $\bm{h}_{i}= \{\bm{h}_{1}, \bm{h}_{2}, \cdots , \bm{h}_{n} \}$, which will be used for state representation learning. \paragraph{State representation.} The actions are predicted based on the neural transition state representations, as depicted in Figure \ref{sequence-b}. We first use a BiLSTM to generate representations $\bm{r}^{\beta}$ for each word $w_i$ in $\beta$. Another BiLSTM is used for generating predicate representation $\bm{r}^{\lambda_p}$ at $\lambda$. Taking the $9$-th transition step as example, the current representations of predicate `stay' in $\lambda$ and the word `witnesses' in $\beta$ are from BiLSTMs, respectively. We use Stack-LSTM \cite{ZhangQZLJ19,YuanJT19} to encode the elements in stacks (e.g., $\sigma_{*}, \alpha_{*}$). For instance, the representations of the top elements in stacks (i.e., `When' in $\sigma_{l}$, `witnesses' in $\alpha_{l}$, `nothing' in $\sigma_{r}$, `,' in $\alpha_{r}$) is obtained from the Stack-LSTM, respectively. Besides of the regular states introduced in $s$, we also maintain the trace of action histories $\delta$ via a stack. We summarize all these state representations via concatenation as the initiation for the next action prediction: \begin{equation} \setlength\abovedisplayskip{2pt} \setlength\belowdisplayskip{2pt} \bm{g}_t = [\bm{r}^{\sigma_l}_t;\bm{r}^{\sigma_r}_t;\bm{r}^{\alpha_l}_t;\bm{r}^{\alpha_r}_t;\bm{r}^{\lambda_p}_t;\bm{r}^{\beta}_t;\bm{r}^{\delta}_t] \,. \end{equation} \paragraph{Action prediction.} Based on state $\bm{g}_t$, the model predicts the action probability, as in Figure \ref{sequence-b}: \begin{equation} \label{label_score} \setlength\abovedisplayskip{2pt} \setlength\belowdisplayskip{2pt} \bm{P}^{a} = \text{softmax}(\text{FFNs}(\bm{g}_t)) \,, \end{equation} where FFNs($\cdot$) is a feed-forword network. At the meantime, once an arc is determined, a labeler\footnote{ In traditional transition methods, the arcs are determined jointly with their role labels by joint actions, e.g., \emph{LEFT-ARC-A1}, whereas we find in our preliminary experiments that separating these two predictions can bring better performances. } will assign a role label for the argument: \begin{equation} \label{role_score} \setlength\abovedisplayskip{2pt} \setlength\belowdisplayskip{2pt} \bm{P}^{r} = \text{softmax}(\text{FFNs}(\bm{g}_t)) \,. \end{equation} \paragraph{Training.} During training, we set the goal to maximize the likelihood of actions from the current states under the gold-standard actions. We first convert gold output structures of training data into action sequences. We minimize the following loss: \begin{equation} \setlength\abovedisplayskip{2pt} \setlength\belowdisplayskip{2pt} \mathcal{L} = - \begin{matrix}\sum_{t} \end{matrix} \hat{\varphi}_t \text{log} p(\varphi_t | \Theta ) + \frac{\zeta}{2} ||\Theta||^{2} \,, \end{equation} where $\hat{\varphi}$ denotes gold-standard actions, $\Theta$ is the set of all model parameters, and $\zeta$ is a co-efficient. Instead of greedily choosing the output with maximum probability, we apply beam-search algorithm \cite{zhang-clark-2008-tale,LyuZJ16} for decoding, where top-B partial outputs are cached for each transition decision, avoiding achieving sub-optimal results. \begin{figure}[!t] \centering \includegraphics[width=0.93\columnwidth]{illus/new_representation2.pdf} \caption{ New state representations with high-order feature for argument recognition and role labeling. } \label{new-state} \end{figure} \begin{table*}[!t] \begin{center} \resizebox{1.8\columnwidth}{!}{ \begin{tabular}{lccccccccc} \toprule \multirow{3}{*}{ } & \multicolumn{4}{c}{ \texttt{Without dependency feature}}& \multicolumn{5}{c}{ \texttt{With dependency feature}}\\ \cmidrule(r){2-5}\cmidrule(r){6-10} & \multicolumn{3}{c}{ Arg.}& Prd. & \multicolumn{3}{c}{ Arg.}& Prd. & \multicolumn{1}{l}{\multirow{2}{*}{Decode}}\\ \cmidrule(r){2-4}\cmidrule(r){5-5} \cmidrule(r){6-8}\cmidrule(r){9-9} & P &R &F1 &F1 &P &R& F1& F1 &\\ \midrule \citeauthor{he-etal-2018-jointly} (\citeyear{he-etal-2018-jointly}) & 89.0 & 87.6 & 88.9 & 91.3 & 89.5 & 88.0 & 89.2 & 92.6 & 604 \\ \citeauthor{cai-etal-2018-full} (\citeyear{cai-etal-2018-full})& 89.5 & 88.4 & 89.2 & 94.6 & 89.7 & 89.0 & 89.5 & 94.9 & 450 \\ \citeauthor{LiHZZZZZ19} (\citeyear{LiHZZZZZ19}) & \bf 89.9 & 89.2 & 89.6 & 95.0 & 90.2 & 89.5 & 89.9 & 95.2 & 432 \\ \hdashline Ours (Vanilla model) & 88.0 & 88.9 & 88.4 & 92.3 & 88.5 & 89.6 & 88.9 & 94.3 & \bf 1,058 \\ Ours (High-Order model) & 89.4 & \bf 91.1 & \bf 89.8 & \bf 95.2 & \bf 90.4 & \bf 90.0 & \bf 90.2 & \bf 95.5 & 897 \\ \bottomrule \end{tabular} } \end{center} \caption{ Results on CoNLL09 English in-domain test set. Decode means decoding speed (token per second). } \label{English-in-domain} \end{table*} \subsection{The High-Order Model} In the vanilla transition model, the actions are incrementally predicted with the first-order local features, considering the dependencies to the predicates only. Here we present a high-order model further, leveraging the previously recognized argument-predicate information into the current decision. Figure \ref{new-state} shows the overall network structure of our high-order features. We exploit the argument-predicate scoring distributions as the major sources for high-order compositions, which is mostly motivated by \citeauthor{lyu-etal-2019-semantic} (\citeyear{lyu-etal-2019-semantic}). Two types of argument-predicate scoring distributions (i.e., $\bm{I}^a$ and $\bm{I}^r$) are exploited for action ($a$) and role ($r$) label predictions, respectively, and their network compositions are exactly the same. In the following, we describe the high-order networks in detail. Concretely, the high-order features are calculated as follows. First, we derive a sequence of distribution-based features (i.e., $\bm{M}^{\tau}=\{\bm{I}^{\tau}_1,\cdots,\bm{I}^{\tau}_{t-1},\bm{I}^{\tau}_{t}\}$ ) from the historical argument-predicates. For each $i \in [1, t]$, we have: \begin{equation} \setlength\abovedisplayskip{3pt} \setlength\belowdisplayskip{3pt} \bm{I}^{\tau}_t = \text{softmax}(\text{FFN}([ \bm{r}_a ; \bm{r}_p])) \,, \end{equation} where $\bm{r}_a, \bm{r}_p$ are the current argument and predicate representation from $\sigma_{*}$ and $\lambda_p$, respectively, ${\tau}\in\{a, r\}$ indicating that the goal of the feature is for either action predication or role labeling. Note that the output dimension is the same as their final classification goal for $\bm{P}^{\tau}$ (see Eq \ref{label_score} and \ref{role_score}). Second, we use an attention mechanism guided by the first-order representation $\bm{g}_{t+1}$ to obtain the high-order feature vector: \begin{equation} \setlength\abovedisplayskip{3pt} \setlength\belowdisplayskip{3pt} \begin{split} u^{\tau}_k &= \text{tanh}(\bm{W}^{\tau}_1 \bm{g}_{t+1} + \bm{W}^{\tau}_2 \bm{I}^{\tau}_{k} ) \\ \alpha^{\tau}_k &= \text{softmax}(u^{\tau}_k) \\ \bm{o}^{\tau}_{t+1} &= \begin{matrix} \sum_{k=1}^j \end{matrix} \alpha^{\tau}_k \bm{I}^{\tau}_{k} \,, \end{split} \end{equation} where $\bm{o}^{\tau}_{t+1}$ is the desired representation, and $\bm{W}^{\tau}_1$ and $\bm{W}^{\tau}_2$ are parameters. Finally, we concatenate the first-order and high-order feature representation together (i.e., $\hat{\bm{g}}_{t+1} = [\bm{g}_{t+1}; \bm{o}^{\tau}_{t+1}]$) for transition action and role label predictions. In the high-order model, the action prediction, decoding and learning processing are kept consistent with the vanilla neural model in $\S$~\ref{vanilla model}. But with the above high-order feature, the recognition for the following and farther arguments will be informed by the earlier decisions, avoiding the error accumulation in the vanilla transition system. It also worth noticing that with beam-search strategy, we are able to facilitate the use of high-order feature, making the information communication between arguments most efficient. \section{Experiments} \subsection{Settings} We employ two dependency-based SRL benchmarks: CoNLL09 English, and Universal Proposition Bank (UPB) for other total seven languages. We use the pre-trained fasttext\footnote{\url{https://fasttext.cc/}} word embeddings for each language as default word representation. The hidden sizes in BiLSTM, TreeLSTM and Stack-LSTM are 200. We use the two layer version of BiLSTM, Stack-LSTM. The dimension of transition states is 150 universally. We adopt the Adam optimizer with initial learning rate of 1e-5. $\zeta$ is 0.2, and beam size \textbf{B} is 32, according to our developing experiments. We train the model by mini-batch size in [16,32] with early-stop strategy. We evaluate the contextualized word representations, i.e., ELMo\footnote{\url{https://allennlp.org/elmo}}, BERT (base-cased-version)\footnote{\url{https://github.com/google-research/bert}} and XLNet (base-version)\footnote{\url{https://github.com/zihangdai/xlnet}}. Each dataset comes with its own train, develop and test sets. We use the precision (P), recall (R) and F1 score as the metric. We conduct significance tests via Dan Bikel’s randomized evaluation comparator\footnote{\url{http://www.cis.upenn.edu/˜dbikel/software.html/comparator}}. Our codes can be found at \url{https://github.com/scofield7419/TransitionSRL}. \begin{table}[!t] \begin{center} \resizebox{0.75\columnwidth}{!}{ \begin{tabular}{lllll} \toprule & Arg. & Prd. \\ \hline\hline Ours (High-Order model) & \bf 91.0 & \bf 96.3 \\ \hline \multicolumn{5}{l}{$\bullet$ Input features}\\ \quad w/o Char & 90.7 & 96.0 \\ \quad w/o POS & 90.4 & 95.6 \\ \quad w/o Dep-tree & 89.8 & 95.1 \\ \hline \multicolumn{5}{l}{$\bullet$ Incremental high-order feature}\\ \quad w/o $\bm{o}^a$ & 89.4 & 95.4 \\ \quad w/o $\bm{o}^r$ & 88.8 & 95.7 \\ \quad Ours (Vanilla model) & 88.6 & 94.1 \\ \hline \multicolumn{5}{l}{$\bullet$ Transition parsing direction }\\ \quad left-to-right & 88.5 & 93.0 \\ \quad right -to-left & 88.0 & 92.8 \\ \bottomrule \end{tabular} } \end{center} \caption{ Ablation results (F1 score). } \label{Ablation} \end{table} \subsection{Ablation Study} We study the contributions from each part of our methods, in Table \ref{Ablation}. Based on CoNLL09 in-domain developing set, we evaluate the performances of the argument recognition and role labeling (Arg.), and the predicate detection (Prd.). \paragraph{Input features.} When removing the character encoder, POS tags and syntactic dependencies, respectively, the performances drop consistently. We notice that the dependency structural knowledge is of the greatest importance for both the argument and predicate recognition, among other features, which coincides with the prior findings of the structural syntax information \cite{marcheggiani-etal-2017-simple,zhang-etal-2019-syntax-enhanced,Crossfei9165903}. \paragraph{High-order feature.} We ablate the argument-predicate scoring distribution $\bm{o}^a$ and $\bm{o}^r$ to see the contribution of the proposed interaction mechanism. We can find that both these two distributions plays key role for arguments role labeling, especially the $\bm{o}^r$. When removing such incremental high-order feature away (i.e., vanilla model w/o $\bm{o}^a$\&$\bm{o}^r$), the results drop significantly. This verifies the usefulness of the proposed high-order feature. \paragraph{Transition parsing order.} Our model performs argument parsing around the predicate down the `from-near-to-far' direction. Compared with the traditional `left-to-right' reading order, or the reversed `right -to-left' order, we can find that the \emph{close-first} parsing scheme is much more effective. \begin{table*}[!t] \begin{center} \resizebox{1.48\columnwidth}{!}{ \begin{tabular}{lcccccccc} \cline{1-9}\cline{1-9} & DE & FR & IT & ES & PT & FI & ZH & \texttt{Avg.} \\ \hline \citeauthor{he-etal-2018-jointly} (\citeyear{he-etal-2018-jointly})& 68.5 & 84.3 & 67.6 & 73.0 & 79.2 & 70.4 & 64.9 & 72.6 \\ \citeauthor{cai-etal-2018-full} (\citeyear{cai-etal-2018-full})& 69.9 & 85.5 & 67.8 & \bf 74.5 & 78.9 & 71.0 & 65.8 & 73.3\\ \citeauthor{LiHZZZZZ19} (\citeyear{LiHZZZZZ19})& 69.7 & 85.0 & 69.0 & 73.8 & 79.6 & 70.5 & \bf 66.0 & 73.4 \\ \hdashline Ours (Vanilla model) & 68.9 & 86.2 & 68.6 & 73.0 & 80.1 & 69.9 & 63.6 & 72.9 \\ Ours (High-Order model) & \bf 70.5 & \bf 87.8 & \bf 69.2 & 73.6 & \bf 80.7 & \bf 71.6 & 65.6 & \bf 74.2 \\ \cline{1-9}\cline{1-9} \end{tabular} } \end{center} \caption{ End-to-end SRL on UPB data. Values are F1 scores for argument recognition and role labeling. } \label{UPB} \end{table*} \begin{table}[!t] \begin{center} \resizebox{0.94\columnwidth}{!}{ \begin{tabular}{lcccc} \toprule & \multicolumn{3}{c}{ Arg.}& Prd. \\ \cmidrule(r){2-4}\cmidrule(r){5-5} & P &R &F1 &F1 \\ \midrule \citeauthor{he-etal-2018-jointly} (\citeyear{he-etal-2018-jointly}) & 79.5 & 76.2 & 78.6 & 78.6 \\ \citeauthor{cai-etal-2018-full} (\citeyear{cai-etal-2018-full})& \bf 80.4 & 76.9 & 79.5 & 80.5 \\ \citeauthor{LiHZZZZZ19} (\citeyear{LiHZZZZZ19})& 79.9 & 78.5 & 79.2 & 82.0 \\ \hdashline Ours (High-Order model) & 80.2 & \bf 79.8 & \bf 80.0 & \bf 82.7 \\ \bottomrule \end{tabular} } \end{center} \caption{ Results on out-of-domain data of CoNLL09. } \label{English-out-of-domain} \end{table} \begin{table}[!t] \begin{center} \resizebox{0.94\columnwidth}{!}{ \begin{tabular}{lccc} \toprule & P &R &F1 \\ \midrule \citeauthor{zhao-etal-2009-multilingual-dependency} (\citeyear{zhao-etal-2009-multilingual-dependency})& - & - & 85.4 \\ \citeauthor{bjorkelund-etal-2010-high} (\citeyear{bjorkelund-etal-2010-high})& 87.1 & 84.5 & 85.8 \\ \citeauthor{fitzgerald-etal-2015-semantic} (\citeyear{fitzgerald-etal-2015-semantic})& -& - & 86.7 \\ \citeauthor{roth-lapata-2016-neural} (\citeyear{roth-lapata-2016-neural})& 88.1 & 85.3 & 86.7 \\ \citeauthor{marcheggiani-titov-2017-encoding} (\citeyear{marcheggiani-titov-2017-encoding})& 89.1 & 86.8 & 88.0 \\ \hdashline \citeauthor{he-etal-2018-jointly} (\citeyear{he-etal-2018-jointly})& 89.8 & 89.6 & 89.7 \\ \citeauthor{cai-etal-2018-full} (\citeyear{cai-etal-2018-full})& 89.9 & 90.2 & 90.0 \\ \citeauthor{LiHZZZZZ19} (\citeyear{LiHZZZZZ19})& \bf 90.9 & 90.2 & 90.5 \\ \hdashline Ours (High-Order model) & 90.3 & \bf 91.0 & \bf 90.7 \\ \bottomrule \end{tabular} } \end{center} \caption{ Pipeline argument role labeling on CoNLL09. } \label{argument role labeling} \end{table} \subsection{Main Results} \paragraph{CoNLL09 in-domain results.} We mainly make comparisons with the recent previous end-to-end SRL models. In Table \ref{English-in-domain}, first of all, we find that the syntactic dependency feature configurations universally contribute to both the argument recognition and predicate disambiguation, compared with the syntax-agnostic models. Most importantly, our high-order model outperforms these baselines on both two subtasks. The improvements are more significant on the setting with dependency features, i.e., 90.2\% (Arg.) and 95.5\% (Prd.). Also we notice that our model is especially better at predicate disambiguation. Besides, our transition systems beat competitors with higher decoding speed, nearly two times faster. \paragraph{Results for other languages.} Table \ref{UPB} shows the performances on UPB for other languages. The experiments are conducted with dependency features. Overall, our high-order model wins the best averaged F1 score (74.2\%). Also the high-order feature universally helps to improve the vanilla transition model with average 1.3\%(=74.2-72.9) F1 score. The improvements so far by our model demonstrate its effectiveness. \paragraph{CoNLL09 out-of-domain results.} Table \ref{English-out-of-domain} compares the performances on out-of-the-domain test set of CoNLL09 data with dependency features. Overall, the similar trends are kept as that on in-domain dataset. Our model still performs the best, yielding 80.0\% (Arg.) and 82.7\% (Prd.) F1 scores, verifying its generalization capability on capturing the semantic preferences of the task. \paragraph{Argument role labeling.} We next compare the results in Table \ref{argument role labeling} for standalone argument role labeling, where the models are given by the gold pre-identified predicates as input, and output the argument boundaries and roles. Compared with the baseline pipeline systems, the end-to-end systems can perform better, while our transition model gives a new state-of-the-art 90.7\% F1 score. \begin{figure}[!t] \centering \includegraphics[width=0.96\columnwidth]{illus/arg-prd-dis3.pdf} \caption{ Argument recognition under varying surface distance between predicates and arguments. } \label{distance} \end{figure} \begin{table}[!t] \begin{center} \resizebox{0.94\columnwidth}{!}{ \begin{tabular}{lccc} \toprule & ELMo & BERT & XLNet \\ \midrule \citeauthor{he-etal-2018-jointly} (\citeyear{he-etal-2018-jointly})& 89.7& 90.8& 90.3 \\ \citeauthor{cai-etal-2018-full} (\citeyear{cai-etal-2018-full})& 90.8 & 91.7& 91.4 \\ \citeauthor{LiHZZZZZ19} (\citeyear{LiHZZZZZ19})& \bf 91.5 & 92.0 & 91.8 \\ \hdashline Ours (High-Order model) & 91.3& \bf 92.2& \bf 92.0 \\ \bottomrule \end{tabular} } \end{center} \caption{ Results with contextualized word representation. } \label{LM} \end{table} \begin{figure}[!t] \centering \includegraphics[width=0.9\columnwidth]{illus/case-show.pdf} \caption{ Visualizations of the parses under varying transition iterations. The predicate is in the box. The arrows above the sentence are from the vanilla model, while the ones beneath are by our high-order system. Red and green arrows represent incorrect and correct argument or role, respectively. } \label{case} \end{figure} \paragraph{Contextualized word representation.} Finally, we take advances of the recent contextualized word representations, ELMo, BERT and XLNet. As shown in Table \ref{LM}, all the end-to-end SRL models can benefit a lot. With enhanced word representations, we see that the graph-based model by \citeauthor{LiHZZZZZ19} (\citeyear{LiHZZZZZ19}) can achieve better results (91.5\%) with ELMo. while our model can obtain the best performances by BERT (92.2\%), and XLNet (92.0\%). \subsection{Discussion} \paragraph{Necessity of back refining.} We introduce the \emph{incremental high order interaction} for improving the argument recognition, by informing the detection of following and farther arguments with previous recognition history information, that is, the later decisions are influenced by former decisions. Such uni-directional propagation naturally spurs a potential question: \emph{Is it necessary to use the later refined decisions to inform and refine back the former decisions?} Theorically speaking, the negative influences only exist at the initial transition decisions, because our proposed interaction mechanism combined with beam search strategy can largely refined the future decisions. One the other hand, the \emph{close-first} parsing scheme can ensure that the nearer-to-predicate arguments recognized earlier are more likely to be correct. In addition, in our experiment we proves the unnecessity of the back refining. Figure \ref{distance} shows the performance under varying surface distance from predicate to arguments. It is clear that within the distances of 3-4, the performances by our full model changes very little. Even when removing the interaction mechanism (into vanilla model), the decreases under short surface distances is not much significant. Lastly, our high-order model handles better the long-distance dependency issues, compared with baselines. \paragraph{High-order features.} We now look into the incremental high order interaction mechanism. We consider conducting empirical visualization of the transition parsing steps. We compare the transition results by high-order model, and the vanilla model without high-order feature, as illustrated in Figure \ref{case}. At the earlier steps with short distance between predicate and argument, e.g., second and fourth iteration steps, both two transition models can make correct prediction. At 7$^{\text{th}}$ step, the vanilla model wrongly assigns a \emph{A3} for argument `you', and further falsely determines the `sometime' as \emph{AM-TMP} argument at 8$^{\text{th}}$ step. On the contrary, our high-order model with such interaction can perform correct role labeling, and yield accurate argument detection even in remote distance. \paragraph{Role violation.} To further explore the strengths of our transition model, we study the argument role violation \cite{punyakanok-etal-2004-semantic,fitzgerald-etal-2015-semantic,he-etal-2018-jointly}. Consider categorizing the role labels into three types: (U) unique core roles (A0-A5, AA), (C) continuation roles and (R) reference roles. 1) If a core role appears more than once, U is violated. 2) If C-X role not precedes by the X role (for some X), C is violated; 3) R is violated if R-X role does not appear. Table \ref{Role Violation} shows the role violation results. First of all, our high-order model gives the most consistent results with gold ones, with minimum role violations. This partially indicates that the system can learn the latent constraints. But without the \emph{incremental high order interaction}, performances by vanilla model for continuation and reference roles get hurt. This is reasonable, since generally the non-core roles are more remote from their predicate. We also find that our transition model with \emph{close-first} parsing order performs better, especially for the unique core role, compared with the `left-to-right' parsing order. Finally, the graph-based baselines tend to predict more duplicate core arguments, and also recognize fewer reference argument roles. \begin{table}[!t] \begin{center} \resizebox{0.76\columnwidth}{!}{ \begin{tabular}{lccc} \toprule & U & C & R \\ \midrule Gold & 55 & 0 & 88 \\ \hdashline Ours (High-Order model) & 82 & 8 & 98 \\ Ours (Vanilla model) & 106 & 10 & 122 \\ left-to-right Trans. & 212 & 13 & 139 \\ \hdashline \citeauthor{he-etal-2018-jointly} (\citeyear{he-etal-2018-jointly})& 242 & 14 & 208\\ \citeauthor{cai-etal-2018-full} (\citeyear{cai-etal-2018-full})& 210 & 11 & 162 \\ \bottomrule \end{tabular} } \end{center} \caption{ Results for argument role violation. } \label{Role Violation} \end{table} \section{Conclusion} We investigated a neural transition model for end-to-end semantic role labeling. We designed the transition system where the predicates were first discovered one by one, and then the associated arguments were determined in a \emph{from-near-to-far} order. We proposed to use the incremental high-order feature, leveraging the previously recognized argument-predicate scoring distribution into the current decision. Experimental results on the dependency-based SRL benchmarks, including CoNLL09 and Universal Proposition Bank datasets, showed that the transition model brings state-of-the-art performances, meanwhile keeping higher decoding efficiency. Further analysis demonstrated the usefulness of the high-order feature and the close-first parsing order. \end{CJK} \newpage \section*{Acknowledgments} We thank the anonymous reviewers for providing constructive comments and suggestions. This work is supported by the National Natural Science Foundation of China (No. 61772378 and 61602160), the National Key Research and Development Program of China (No. 2017YFC1200500), the Research Foundation of Ministry of Education of China (No. 18JZD015).
{'timestamp': '2021-01-05T02:14:17', 'yymm': '2101', 'arxiv_id': '2101.00394', 'language': 'en', 'url': 'https://arxiv.org/abs/2101.00394'}
arxiv
\section{Introduction} Biometric data such as face, fingerprint or iris images reveal information about the identity of the individual as well as the identity of the device used to acquire the data~\cite{BiomSensor_1, BiomSensor_2}. In some applications such as smartphone banking, it is necessary to authenticate both the {\em user} as well as the {\em device} in order to enhance security~\cite{Galdi_PRL_15, Ross_ICB_18}. This can be done by invoking two separate modules: one for biometric recognition and the other for device or sensor recognition.\footnote{The terms ``device" and ``sensor" are interchangeably used in this paper. Thus, determining the identity of a smartphone camera (\textit{i.e.,} sensor) is akin to determining the identity of the smartphone (\textit{i.e.,} device) itself.} In such cases, the system has to store two distinct templates: a biometric template denoting the identity of the user and sensor template denoting the identity of the device. In this paper, we approach this problem by designing a {\em joint template} that can be used to authenticate both the user and the device simultaneously. Our objective is as follows: \textit{Given a biometric image we would like to simultaneously recognize the individual and the acquisition device}. In the process of accomplishing this objective, we address the following questions: \begin{figure}[t] \centering \subfloat[] { \includegraphics[scale=.37]{FIG1_NEW} }\\ \subfloat[] { \includegraphics[scale=.37]{FIG1_NEWB.png} } \caption{Difference between (a) methods that use separate modules for computing biometric and sensor representations, and (b) the proposed method that uses an embedding network to generate a joint biometric-sensor representation. } \label{Fig: Obj} \end{figure} \begin{enumerate} \item \textbf{Why do we need to combine biometric and device recognition?} \\ Smartphones are increasingly using biometrics for access control and monetary transactions. Examples include fingerprint and face recognition on iPhones and iris recognition on Samsung Galaxy S9. Device verification\footnote{Typically used in two factor authentication (2FA) protocol that combines any two of the three factors: `something you are' (biometrics), `something you have' (a code on the authorized device) and `something you know' (a password) for additional security.} can provide assurance that the biometric sample is being acquired by an authorized device. A combined biometric and device recognition system can therefore guarantee that the right person is accessing the remote service (\textit{e.g.}, banking) using an authorized device. \item \textbf{Can existing device verification techniques be used in the smartphone application scenario?} \\ Device identification can be performed using the MAC (media access control) address, a unique networking address assigned to each device. However, in case of smartphones that have multiple network interfaces, such as Wi-Fi, 4G, bluetooth, etc., there can be multiple MAC addresses which may be broadcasted, making them vulnerable. Alternatively, SRAM cells can be used to deduce physically unclonable cues for device identification~\cite{Ross_ICB_18}; this is a hardware-based solution and requires access to the physical device. In a mobile banking scenario, where the verification is conducted remotely, the customer provides a biometric sample in the form of an image, and some device information, but not necessarily the physical device itself. In this scenario, hardware-based solutions will be ineffective. \item \textbf{Why do we need a joint representation?} \\ Existing literature uses separate modules to tease out the biometric-specific and sensor-specific details from an image and perform feature-level or score-level fusion~\cite{Galdi_PRL_15, Ross_ICB_18}. However, they suffer from the following limitations: (i) the overall performance is limited by the weakest recognition module, and (ii) the process may not generalize well across different biometric modalities and multi-spectral sensors. Therefore, a \textit{joint} representation that combines both biometric and sensor-specific features present in a biometric image can offer the following advantages: (i) the joint representation is not constrained by the performance of the individual recognition module, and the same \textit{method} can be employed across different biometric modalities, and (ii) the joint representation integrates the biometric and sensor representations into a compact template, such that, the individual templates cannot be easily de-coupled; this implicitly imparts privacy to the biometric component. \end{enumerate} \section{Related Work} Biometric recognition systems comprise a \textit{feature extraction} module that elicits a salient feature representation from the acquired biometric data, and a \textit{comparator} module that compares two sets of feature representations to compute a match score~\cite{Jain_Intro}. On the other hand, sensor recognition systems extract sensor pattern noise~\cite{Lukas_TIFS_06} from a set of training images obtained from different sensors to generate \textit{sensor reference patterns}. To deduce the sensor identity of an unknown test image, first its sensor pattern noise is extracted, and then it is \textit{correlated} with the reference patterns. The test image is assigned to the device whose reference pattern yields the highest correlation value. In~\cite{Galdi_ICIAP}, the authors used partial face images acquired using smartphones and employed a weighted sum fusion rule at the score level to combine sensor and biometric recognition. Later, they extended their work to include feature level fusion in~\cite{Galdi_PRL_15} and concluded that score level fusion performed comparatively better. In~\cite{Galdi_Face}, the authors performed HOG-based face recognition and combined it with Photo Response Non-Uniformity-based sensor recognition at the score level. In~\cite{Ross_ICB_18}, the authors combined fingerprint recognition with device recognition by performing feature level fusion of minutiae-cylinder-codes with SRAM start-up values. Fusion at the score or feature level is often dependent on the specific biometric modality and the device sensor used. A specific fusion rule producing the best results on a particular biometric and sensor modality (\textit{e.g,} iris and near-infrared sensors) may not yield optimal results on a different modality (\textit{e.g,} face and RGB sensors), and therefore, needs to be tuned separately for each pair of biometric and sensor modalities. Furthermore, feature-level fusion retains the individual biometric and sensor-specific components that can be recovered from the fused representation using appropriate measures. Obtaining the biometric template may compromise the privacy aspect of biometrics. In contrast, the proposed joint representation non-trivially unifies the biometric and sensor-specific features. As a result, typical countermeasures will be ineffective in disentangling the biometric component from the joint representation. This will implicitly preserve the privacy of the biometric component. The remainder of the paper is organized as follows. Section~\ref{Sec:Prop} describes the proposed method. Section~\ref{Sec:DSandExp} describes the dataset and experimental protocols used in this work. Section~\ref{Sec:Res} reports the results. Section~\ref{Sec:Sum} summarizes the findings and concludes the paper. \section{Motivation and Proposed Method} \label{Sec:Prop} An image contains both low frequency and high frequency components. For example, in a face image, the low frequency components capture the illumination details while the high frequency components capture the structural details present in the face that are useful for biometric recognition. Recently, sensor recognition has been successully accomplished using Photo Response Non-Uniformity (PRNU)~\cite{Lukas_TIFS_06} for different types of sensors, such as DSLR sensors~\cite{Chen_TIFS_08}, smartphone sensors~\cite{BTAS_19}, and also near-infrared iris sensors~\cite{Uhl4_ICB_12}. PRNU is a form of sensor pattern noise in an image that manifests due to anomalies during the fabrication process and is, therefore, unique to each sensor. Typically, PRNU resides in the high frequencies that can be useful for sensor recognition~\cite{Lukas_TIFS_06}. Since the high frequencies dominate in both biometric and sensor representations, we hypothesize that there is a joint representation, that, if effectively extracted, can be utilized for both tasks of biometric and sensor recognition. Our objective is to \textit{learn} this joint representation that lies at the intersection of the sensor and biometric space. Mathematically, it can be represented as $\displaystyle J(\bm{X}) = B(\bm{X}) \cap S(\bm{X})$, where $\bm{X}$ is an input biometric image, $B(\cdot)$ is the biometric representation extracted from $\bm{X}$, $S(\cdot)$ is the sensor representation computed from the same input $\bm{X}$, and $J(\cdot)$ is the joint representation. Existing methods process $\bm{X}$ using two independent routines to extract the two representations, and can optionally perform fusion, either at feature level or at score level, to make a decision. However, we propose to leverage the two representations to derive a joint representation (see Figure~\ref{Fig: Obj}). The joint space can be best approximated using an embedding network that can convert images to compact representations~\cite{Emb1}. The embedding network $\mathcal{E}$, takes two inputs, $\bm{X}$ and the dimensionality ($k$) of the embedding to be generated, such that $\displaystyle J(\bm{X}) = \mathcal{E}(\bm{X},k) \approx B(\bm{X}) \cap S(\bm{X})$. The second argument $k$, allows us to regulate the dimensionality of the joint representation, which will be much lesser than the original dimensionality of the image, as well as the combined dimensionality of the two representations computed separately, \textit{i.e.}, if $\bm{X} \in \mathbb{R}^d$, $B(\bm{X}) \in \mathbb{R}^m$ and $S(\bm{X}) \in \mathbb{R}^n$, then the joint representation $J(\bm{X}) \in \mathbb{R}^k$, where, $k << d$ and $k < (m+n)$. \begin{figure*}[h] \centering \includegraphics[scale=.39]{Fig_outline_CR} \caption{Outline of the proposed method used for computing the joint biometric and sensor representation. \textbf{Input:} A single image, or a pair of images, or 3-tuple images to the embedding network. \textbf{Output:} Joint biometric-sensor representation. The embedding network is trained in three mutually exclusive modes, \textit{viz.,} classical mode (top row), siamese mode (middle row) and triplet mode (bottom row). The switching circuit selects only one training mode at a time.} \label{Fig: Prop} \end{figure*} In this work, we used a deep convolutional neural network that serves the role of the embedding network (see Figure~\ref{Fig: Prop}). The embedding network consists of two 2-D convolutional layers and three linear layers. We used max-pooling for down-sampling the feature map and a parametric-rectified linear activation unit (PReLU) as the activation function. The embedder accepts an image, resized to $48 \times 48$, as the input and produces a 8-dimensional output, which is the \textit{joint} representation. The choice of the dimensionality of the representation along with the experimental setup is described later (see Section~\ref{Sec: Expts}). The \textbf{main contributions} of this work are as follows: \begin{enumerate} \item We propose a method to learn a joint biometric and sensor representation using a one-shot approach that can be used in joint identification and joint verification scenarios. A correct joint identification/verification occurs \textit{only} if both subject identity and device identity yield correct matches. \item We employ an embedding network that can learn the joint representation irrespective of the biometric modality and the sensor used for acquisition. In this context, we evaluate the proposed method using three different biometric modalities (face, iris and periocular), and different types of sensors (iris sensors operating in the near-infrared spectrum and smartphone camera sensors operating in the visible spectrum). \item We perform extensive experiments using different training paradigms and loss functions, and compare the proposed method with existing state-of-the-art algorithms for biometric and sensor recognition. \end{enumerate} \section{Datasets and Experiments} \label{Sec:DSandExp} \subsection{Datasets} In this work, we focused on three different biometric modalities, \textit{viz}., iris, periocular and face. To this end, we used three different datasets - (i) CASIA-Iris Image Database Version 2~\cite{CasV2} which contains near-infrared iris images acquired using two sensors, (ii) Mobile Iris Challenge Evaluation (MICHE-I) dataset~\cite{MICHE} which contains partial face images acquired using two smartphones (front and rear sensors separately) and front camera of a tablet, and (iii) OULU-NPU dataset~\cite{OULU} which contains face images acquired using the front sensors of six smartphones. We used \textit{only} bonafide images from all three sessions in the OULU-NPU dataset. Table~\ref{Tab: Dataset} describes the datasets used in this work. Note that the smartphone datasets (MICHE-I and OULU-NPU) contain images acquired in the visible spectrum. \begin{table*}[] \caption{Dataset specifications used in this work. We used three datasets corresponding to 3 biometric modalities \textit{viz.,} iris, periocular and face. Here, we perform joint biometric and sensor recognition, so total $\# Classes$ is computed as the product of $\# Subjects$ and $\# Sensors$. ($^*$MICHE-I dataset has a total 75 subjects, out of which the first 48 subjects were imaged using iPhone 5S UNIT I and the remaining 27 subjects were imaged using iPhone 5S UNIT II, as observed in~\cite{Galdi_PRL_15}. Here, `UNIT' refers to two different units of the same brand and model iPhone 5S, and therefore, should be treated as two different smartphones. In this case, $\# Classes$ = 375 since only a subset of the total 75 subjects were imaged using either of the two units of iPhone 5S smartphone at a time. Therefore, $75 \times 3$ [Samsung] $+ 48 \times 2$ [UNIT I] $+ 27 \times 2$ [UNIT II] $= 375$.) } \label{Tab: Dataset} \begin{tabular}{|l|ll|l|l|l|} \hline \textbf{Modality} & \textbf{Dataset} & \textbf{\begin{tabular}[c]{@{}l@{}}Name of sensors\end{tabular}} & \textbf{\begin{tabular}[c]{@{}l@{}}(\# Subjects, \# Sensors, \\ \# Classes)\end{tabular}} & \textbf{Split} & \textbf{\# Images} \\ \hline \hline \multirow{2}{*}{Iris} & \multirow{2}{*}{CASIA-Iris V2} & \multirow{2}{*}{CASIA IrisCAM-V2, OKI IrisPass-h} & \multirow{2}{*}{(60, 2, 120)} & Train & 1,680 \\ & & & & Test & 720 \\ \hline \multirow{2}{*}{Periocular} & \multirow{2}{*}{MICHE-I} & \multirow{2}{*}{\begin{tabular}[c]{@{}l@{}}Apple iPhone 5S (Front and Rear) UNIT I and UNIT II, \\ Samsung Galaxy S4 (Front and Rear), Samsung Galxy Tab GT2 (Front)\end{tabular}} & \multirow{2}{*}{(75, 7, 375$^*$)} & Train & 2,278 \\ & & & & Test & 863 \\ \hline \multirow{2}{*}{Face} & \multirow{2}{*}{OULU-NPU} & \multirow{2}{*}{\begin{tabular}[c]{@{}l@{}}HTC Desire EYE, Sony XPERIA C5 Ultra Dual, MEIZU X5,\\ Oppo N3, Samsung Galaxy S6 Edge, ASUS Zenfne Selfie\end{tabular}} & \multirow{2}{*}{(55, 6, 330)} & Train & 5,940 \\ & & & & Test & 2,970 \\ \hline \hline \multicolumn{3}{|l|}{TOTAL} & (190, 15, 825) & & 14,451 \\ \hline \end{tabular} \end{table*} \subsection{Evaluation Protocol} \label{Sec: EvalProto} Before we describe the experiments, we present the protocol that is used to evaluate the proposed approach. We evaluate the method in two scenarios, \textit{viz.,} (i) joint identification and (ii) joint verification. The terms joint identification and joint verification are different from the terms used conventionally in the biometric literature. In the case of \textbf{joint identification}, a correct identification occurs \textit{only} when both sensor and subject labels of the test sample match with the ground truth labels. To perform evaluation in the joint identification scenario, we select one embedding from each class (combines both sensor and subject label) to form the gallery, and the remaining embeddings are used as probes. We use two metrics to compute the distance or similarity between the probe and gallery embeddings and select the top three matches: (i) standardized Euclidean distance (computes the pairwise euclidean distance divided by the standard deviation) and (ii) cosine similarity. We plot the cumulative match characteristics (CMC) curves corresponding to the top three ranks. In the case of \textbf{joint verification}, two joint representations will yield a match if both the embeddings belong to the same sensor and same subject, otherwise a mismatch occurs. Incorrect match can occur in three cases as follows: (i) if the two joint representations belong to the same subject, but different sensors, (ii) if the two joint representations belong to the same sensor, but different subjects, and (iii) if the two joint representations belong to different subjects and different sensors. To perform evaluation in the joint verification scenario, we compute the distance or similarity between all the test embeddings and present receiver operating characteristics (ROC) curves to indicate the joint verification performance. We also report the true match rate (TMR) values @1\% and 5\% false match rates (FMR). \subsection{Experimental Settings} \label{Sec: Expts} In this work, we designed the experimental settings using three different modes of training. See Figure~\ref{Fig: Prop}. Say, $\bm{O}$ denotes the output of an embedding network for input $\bm{X}$, \textit{i.e.}, $\bm{O} = \mathcal{E}(\bm{X},k)$. In the first mode, referred to as the \textit{classical} mode, the embedding $\bm{O}$ is fed to a classification network which minimizes the cross-entropy loss computed between the ground truth label and the predicted label. The classification network in our case is a shallow network which applies PReLU activation on the embedding, followed by a fully-connected layer and then applies softmax to compute a probability value. We assigned the ground truth label for the $i^{th}$ image, such that $l_i \in Sub_i \otimes\ Sen_i$, where $Sub_i$ denotes the subject identifier of image $i$, $Sen_i$ denotes the sensor identifier for the same image and $\otimes$ denotes the tensor product. The cardinality of the set of labels $|L| = |Sub \times Sen|$. In the second mode, referred to as the \textit{siamese} mode, a siamese network~\cite{siamese} is used which feeds a pair of images to the embedding network. The embedding network then computes a pair of embeddings ($\bm{O}_i, \bm{O}_j$) and the siamese network is trained by minimizing the contrastive loss~\cite{contrastive} computed between the pair of embeddings. We used single margin (SMCL) and double margin (DMCL) contrastive losses. Finally, in the third mode, referred to as the \textit{triplet} mode, a triplet network~\cite{tripletnetwork} is trained using embeddings generated from an anchor ($\bm{O}_a$), a positive ($\bm{O}_p$) and a negative ($\bm{O}_n$) sample by minimizing the triplet loss~\cite{tripletloss}. We performed offline triplet mining as well as online triplet mining~\cite{TLmining} with different triplet selection strategies (random negative triplet selection, semi hard negative triplet selection and hardest negative triplet selection). The triplet loss considers only one negative example at a time. Alternatively, multi-class N-pair loss function~\cite{npair} considers multiple negative instances from several classes. In this work, we consider a positive example as one which belongs to the same class as the anchor (same subject and same sensor), whereas there can be three types of negative examples, \textit{viz}., same subject but different sensor, same sensor but different subject and different sensor with different subject. Therefore, the number of negative classes in this work is significantly high, so we used multi-class N-pair loss using two mining techniques: (i) all positive pairs and (ii) hard negative pairs. Table~\ref{Tab: Loss} summarizes the different loss functions used in the three training modes in this work. Note that each input to the embedding network as shown in Figure~\ref{Fig: Prop} is \textbf{mutually exclusive}, \textit{i.e.}, the embedding network can operate independently in any of the three training modes. We modified the design of an existing embedding network for implementing the different training paradigms~\cite{imp}. We used learning rate = $1\times \exp{(-4)}$, batch size = 4, Adam optimizer, and a step decay to reduce the learning rate by a factor $\gamma = 0.1$ every 8 epochs. The proposed network is shallow so we trained only for 50 epochs. The margin values in single margin contrastive loss and triplet losses are set to 1, while in double margin contrastive loss, both margins are set to 0.5. \begin{table}[] \centering \caption{Description of the training modes and the loss functions used in this work.} \label{Tab: Loss} \scalebox{1.1}{ \begin{tabular}{|l|l|l|} \hline \multicolumn{1}{|c|}{\textbf{Training mode}} & \multicolumn{2}{c|}{\textbf{Loss function}} \\ \hline \hline Classical & \multicolumn{2}{c|}{Cross entropy} \\ \hline \multirow{2}{*}{Siamese} & \multicolumn{2}{c|}{Single margin contrastive loss (SMCL)} \\ & \multicolumn{2}{c|}{Double margin contrastive loss (DMCL)} \\ \hline \multirow{6}{*}{Triplet} & \multicolumn{2}{c|}{Offline triplet mining} \\ \cline{2-3} & \multirow{3}{*}{Online triplet mining} & Random negative \\ & & Semi-hard negative \\ & & Hardest negative \\ \cline{2-3} & \multirow{2}{*}{Multi-class N-pair} & All positive pair \\ & & Hard negative pair \\ \hline \end{tabular}} \end{table} For each dataset, we used a training set and a test set (see Table~\ref{Tab: Dataset}). The number of classes is computed as the product of the number of sensors and number of subjects in that dataset. For example, CASIA-Iris V2 dataset has 60 subjects and 2 sensors, so total number of classes is $60 \times 2=120$. Each class has 20 images, therefore, the total number of images (samples) is 2,400 ($20 \times 120$). The training and test partitions follows a 70:30 split. So, for a single class, out of 20 samples, 14 samples are randomly selected as the training set and the remaining 6 samples form the test set. Similar protocol is followed for the remaining datasets. \begin{figure}[h] \centering \includegraphics[scale=.27]{dim_fig.eps} \caption{Variation in the joint verification performance as a function of the dimensionality of the joint representation. Experiment is conducted on the validation set using 50 images from the MICHE-I dataset and four dimensionality values \textit{viz.,} $\{4,8,16,32\}$. 8-dimensional embedding resulted in the highest joint verification accuracy, and is therefore selected in this work.} \label{Fig: Dim} \end{figure} Next, in the training phase, the embedding network accepts an image (resized to $48 \times 48$) as input. Different image resolutions were used $\{28 \times 28, 48 \times 48, 96 \times 96 \}$, but $48 \times 48$ provided optimal trade-off between accuracy and training time. The embeddings are trained in (i) classical, (ii) siamese and (iii) triplet modes. Then, in the testing phase, we computed the embeddings from the test set. We evaluate the test embeddings in joint identification and joint verification scenarios. Although deep learning-based sensor identification methods exist in the literature~\cite{CR_Ref1, CR_Ref2, CR_Ref3}, we used Enhanced PRNU~\cite{Li_TIFS_10} (with enhancement Model III) as the sensor identification baseline for all three modalities due to its low computational burden and effectiveness against multi-spectral images~\cite{Ross_18}. Enhanced PRNU requires creation of sensor reference patterns, that serve as gallery and test (probe) noise residuals, that are correlated with the reference patterns. We used training images to compute the sensor reference patterns and test images for correlation. A test image is assigned to the sensor class resulting in the highest correlation value. See~\cite{BTAS_19} for more details. Test noise residuals computed from JPEG images can be matched successfully against sensor reference patterns computed from RAW images~\cite{PRNU_JPEG}, thereby, justifying the use of PRNU as a state-of-the-art sensor identification baseline. We used COTS matcher as the biometric recognition baseline for iris and face modalities. For the periocular modality, we used a pretrained ResNet-101 architecture~\cite{ResNet} and used the features from layer 170 as the biometric representation for the test samples. This particular architecture is used because it has demonstrated good performance in biometric verification on the MICHE-I dataset~\cite{BTAS_19}. The gallery comprises the training images and the probes are the test images. Since, PRNU can only be used for the task of sensor identification, we selected to implement both the baselines only in identification scenario. We further conducted an experiment using a validation set comprising 50 images from the MICHE-I dataset (excluded from the test set) to analyze the effect of the dimensionality of the embedding on the verification performance. To this end, we used four values of $k = \{4,8,16,32\}$, and then selected that value which results in the highest performance for the remaining experiments. \begin{figure}[] \centering \includegraphics[scale=.27]{sensortsne} \caption{2-D projection of the embeddings using t-SNE used for sensor identification in the OULU-NPU dataset. Each sensor class is sufficiently discriminated from the rest of the sensors.} \label{Fig: tsne} \end{figure} \section{Results and Analysis} \label{Sec:Res} \subsection{Selection of the metric and dimensionality of embedding} In terms of the choice of the distance/similarity \textbf{metric}, we observed that standardized euclidean distance metric resulted in better performance compared to the cosine similarity metric. This can be attributed to the standardization process which takes into account the intra-class and inter-class variations in the embeddings. In terms of the choice of the \textbf{dimensionality} of the embedding, we observed that 8 was the optimal value, since, it resulted in the best performance (64\% on the MICHE-I validation set) as indicated in Figure~\ref{Fig: Dim}. Therefore, we used 8-dimensional embedding and standardized Euclidean distance metric for all the experiments. Furthermore, we presented the t-SNE~\cite{TSNE} visualization of the performance of the embedding network in terms of sensor identification for the OULU-NPU dataset in Figure~\ref{Fig: tsne}. The well-separable clusters corresponding to the six sensors demonstrate the capability of the embedding network used in this work. \subsection{Performance of each of the three training modes} In terms of \textbf{training algorithms}, the overall results in both joint identification and joint verification scenarios indicate that the embedding network trained in \textit{siamese} mode outperformed the remaining training paradigms (see Figures~\ref{Fig: CMC} and~\ref{Fig: ROC}). The reason for the superior performance of siamese network can be attributed to the use of contrastive loss. Out of the two contrastive losses, single margin contrastive loss outperformed double margin contrastive loss. The contrastive loss considers a pair of embeddings at a time, and tries to either minimize the distance between them if they belong to the same class, or increases the distance between them by some margin if they belong to different classes. On the other hand, triplet loss tries to \textit{simultaneously} minimize the distance between the anchor and positive sample, whereas, maximize the distance between the anchor and negative samples. In this work, the number of negative classes is very high (in a 330 class dataset, 1 class is positive and the remaining 329 classes are negative). This makes the task of triplet loss much more complex as compared to contrastive loss. Given the huge variation in the possible combination of negative triplets (see Figure~\ref{Fig: Prop}), we suspect that the triplet loss struggled to determine the accurate decision boundary between the positive and negative classes, resulting in an overall reduction in performance. We investigated different types of triplet mining strategies, and observed that online triplet mining outperformed offline triplet mining and multi-class N-pair in a majority of the cases. \begin{table}[] \centering \caption{Results in the joint identification scenario. Results are reported in terms of Rank 1 identification accuracies (\%). A correct joint identification implies that \textit{both} sensor and subject resulted in a match. Mismatch of either subject or sensor or both will result in an incorrect joint identification.} \label{Tab: Ident} \scalebox{0.8}{ \begin{tabular}{|l|l|l|l|l|l|} \hline \multirow{2}{*}{Dataset} & \multirow{2}{*}{\begin{tabular}[c]{@{}l@{}}Method for \\ baseline\end{tabular}} & \multicolumn{3}{c|}{Baseline performance} & \multirow{2}{*}{\begin{tabular}[c]{@{}l@{}}Proposed \\ method \\ (\%)\end{tabular}} \\ \cline{3-5} & & \begin{tabular}[c]{@{}l@{}}Sensor\\ identification \\ (\%) \end{tabular} & \begin{tabular}[c]{@{}l@{}}Biometric\\ identification \\ (\%)\end{tabular} & \begin{tabular}[c]{@{}l@{}}Joint\\ identification \\ (\%)\end{tabular} & \\ \hline \hline \begin{tabular}[c]{@{}l@{}}CASIA- \\Iris V2 \end{tabular} & \begin{tabular}[c]{@{}l@{}}PRNU \\COTS \end{tabular} & 100.00 & 56.52 & 56.52 & \textbf{89.67 } \\ \hline MICHE-I & \begin{tabular}[c]{@{}l@{}}PRNU \\ResNet-101 \end{tabular} & 99.86 & 18.05 & 18.05 & \textbf{47.53 } \\ \hline OULU-NPU & \begin{tabular}[c]{@{}l@{}}PRNU \\COTS \end{tabular} & 98.48 & 84.24 & 83.13 & \textbf{99.81 } \\ \hline \end{tabular}} \end{table} \subsection{Results of the joint identification experiment} In terms of the performance in \textbf{joint identification scenario}, Table~\ref{Tab: Ident} compares the results with the baseline performance for all the datasets. We reported the baselines for sensor identification (PRNU), biometric identification (COTS or ResNet), followed by joint identification, separately. We reiterate that joint identification involves a correct match only if both sensor and subject labels are correct to allow fair comparison with the proposed method. Results indicate that the proposed method outperformed the baseline (joint identification) by 26.41\% averaged across all three datasets computed at Rank 1. The poor performance for the MICHE-I dataset can be attributed to two factors - firstly, the large number of classes (= 375) compared to rest of the datasets (see Table~\ref{Tab: Dataset}), and secondly, the diverse acquisition settings (indoor vs. outdoor) resulting in degraded biometric recognition, and subsequently leading to overall poor performance. Surprisingly, the proposed method can still outperform the baseline by $\sim$30\%. We have further analyzed this performance in Section~\ref{MICHE_Analysis}. CMC curves indicate the superior performance of the siamese network in contrast to classical and triplet networks. \begin{figure*}[h] \centering \subfloat[] { \includegraphics[scale=.3]{CMC_SEUC_CASIA_CR} } \hspace{-0.75cm} \subfloat[] { \includegraphics[scale=.3]{CMC_MICHELEFTANDRIGHT_SEUC_CR} } \hspace{-0.75cm} \subfloat[] { \includegraphics[scale=.3]{CMC_SEUC_OULU_CR} } \caption{Cumulative Matching Characteristics (CMC) curves for the proposed method in the \textbf{joint identification scenario} for the following datasets: (a) CASIA-Iris V2 (b) MICHE-I and (c) OULU-NPU. Refer to Table~\ref{Tab: Loss} for the different training networks and loss functions indicated in the legend in an identical order.} \label{Fig: CMC} \end{figure*} \begin{figure*}[h] \centering \subfloat[] { \includegraphics[scale=.315]{ROC_SEUC_CASIA_CR} } \hspace{-0.75cm} \subfloat[] { \includegraphics[scale=.315]{ROC_MICHELEFTANDRIGHT_SEUC_CR} }\hspace{-0.75cm} \subfloat[] { \includegraphics[scale=.315]{ROC_SEUC_OULU_CR} } \caption{Receiver Operating Characteristics (ROC) curves for the proposed method in the \textbf{joint verification scenario} for the following datasets: (a) CASIA-Iris V2 (b) MICHE-I and (c) OULU-NPU. Refer to Table~\ref{Tab: Loss} for the different training networks and loss functions indicated in the legend in an identical order. } \label{Fig: ROC} \end{figure*} \begin{table}[] \centering \caption{Results in the joint verification scenario. Results are reported in terms of true match rate (TMR) at false match rates (FMRs) of 1\% and 5\%.} \label{Tab: Veri} \scalebox{1.2}{ \begin{tabular}{|l|l|l|} \hline Dataset & TMR@FMR=1\% & TMR@FMR=5\% \\ \hline \hline CASIA-Iris V2 & 90.00 & 98.00 \\ \hline MICHE-I & 62.00 & 90.00 \\ \hline OULU-NPU & 100.00 & 100.00 \\ \hline \end{tabular}} \end{table} \subsection{Results of the joint verification experiment} In terms of the performance in \textbf{joint verification scenario}, Table~\ref{Tab: Veri} reports the results. Results indicate that the proposed method achieved an average joint TMR of 84\% @1\% FMR, and an average TMR of 96\% @5\% FMR, indicating the strong representative capability of the joint representation. ROC curves in Figure~\ref{Fig: ROC} indicate that the joint representation learnt using siamese network trained with single margin contrastive loss (see the curve marked Siamese-SMCL-Emb[Joint]) outperformed the remaining joint representations. We would like to point out that in~\cite{Galdi_PRL_15}, the authors achieved 23\% (by using feature level fusion) and 86\% (by using score level fusion) at 5\% FMR on the MICHE-I dataset (the authors excluded the Samsung Galaxy Tab 2 subset of the MICHE-I dataset, which we included in our evaluations). Although their objectives were different compared to the proposed work (they adopted a fusion rule for integrating their proposed biometric and sensor recognition performances), we would like to indicate that the task of joint recognition is difficult. In spite of that, the proposed method performed reasonably well. \subsection{Analysis of the performance of the proposed method on MICHE-I dataset} \label{MICHE_Analysis} In both cases of joint identification and joint verification experiments, we observed that the performance of the proposed method evaluated on the MICHE-I dataset was relatively worse compared to the remaining two datasets. We hypothesize that the poor performance can be attributed to two reasons: (i) the image characteristics, and (ii) the variation in the performance across different lateralities, \textit{i.e.,} left vs. right periocular images. MICHE-I dataset was assembled as a part of an iris challenge evaluation and contains images acquired in unconstrained settings (indoor and outdoor settings) having occlusions (specular reflection and downward gaze). See some challenging images from the MICHE-I dataset images in Figure~\ref{Fig: MICHE}. In contrast, CASIA and OULU datasets contain images acquired in controlled settings. \begin{figure}[h] \centering \subfloat[] { \includegraphics[scale=.07]{OCCL_1} }\hspace{0.3cm} \subfloat[] { \includegraphics[scale=.03]{SPEC1} }\hspace{0.3cm} \subfloat[] { \includegraphics[scale=.03]{BACK} }\hspace{0.3cm} \subfloat[] { \includegraphics[scale=.07]{RIGHTEYE} } \caption{Example images from the challenging MICHE-I dataset. (a) Occlusion, (b) Downward gaze and specular reflection, (c) Prominent background in the outdoor setting and (d) A single image containing both eyes but labeled as right eye image (061\textunderscore GT2\textunderscore OU\textunderscore F\textunderscore RI\textunderscore 01\textunderscore 3 where, RI indicates right eye).} \label{Fig: MICHE} \end{figure} We presented the CMC curves corresponding to joint identification results for two lateralities separately in Figure~\ref{Fig: CMCMICHE}. Results indicate that the proposed method performed better on left periocular images compared to right periocular images. This variation in the performance across the two lateralities resulted in the overall poor performance on the entire MICHE-I dataset. MICHE-I dataset has an imbalanced distribution of lateralities. Only 30\% of the total number of images are of left periocular images. We hypothesize that the imbalanced distribution coupled with some mislabeled test case (see Figure~\ref{Fig: MICHE}(d)) may have further compounded the challenges, resulting in overall poor performance. \begin{figure}[h] \centering \subfloat[] { \includegraphics[scale=.3]{CMC_MICHE_LEFTONLY_CR} } \hspace{-0.75cm} \subfloat[] { \includegraphics[scale=.3]{CMC_MICHE_RIGHTONLY_CR} } \caption{Cumulative Matching Characteristics (CMC) curves for the proposed method in the joint identification scenario for the MICHE-I dataset evaluated separately on the two lateralities. (a) Left periocular images and (b) Right periocular images. Results indicate that the proposed method performs better on left periocular images compared to right periocular images.} \label{Fig: CMCMICHE} \end{figure} The \textbf{main findings} from the experiments are as follows: \begin{enumerate} \item The joint biometric and sensor representation performed well in both joint identification scenario, with an average identification accuracy of $\sim80\%$ computed at Rank 1, and an average joint verification accuracy of $96\%$ at a false match rate of 5\%, averaged across the three biometric modalities. \item The representation is \textit{robust} across three modalities (iris, face and periocular), and different sensors (near-infrared iris sensors and visible smartphone sensors). \item The joint embedding outperformed baselines that used state-of-the-art commercial biometric matchers and sensor identification schemes across three datasets corresponding to three biometric modalities and multi-spectral sensors. \end{enumerate} \section{Summary and Future Work} \label{Sec:Sum} In this paper, we proposed a one-shot method to simultaneously authenticate the user and the device from a single image, say a face or an iris image. To accomplish this task, we developed a method to learn a joint representation that can be used for combined biometric and sensor (device) recognition. The joint representation will be useful in remote application scenarios that employ multiple factor authentication. Examples include mobile banking on smartphones and accessing secure services. Additionally, the joint representation will be implicitly privacy-preserving as the biometric and sensor representations cannot be trivially separated. We used an embedding network to generate the joint representation. We evaluated the proposed approach by (i) exploring different training schemes, and (ii) testing the method on multiple datasets belonging to three different biometric modalities (iris, face and periocular) in both the identification and verification scenarios. We observed best performing results of identification accuracy of 99.81\% at Rank1 and a verification accuracy of TMR=100\% at 1\% FMR using the proposed method. Future work will involve improving the current framework by incorporating domain knowledge (sensor characteristics) to further increase the recognition performances. We will also evaluate the proposed method on datasets with larger number of subjects and sensors. \balance \bibliographystyle{ieeetran}
{'timestamp': '2021-01-05T02:20:20', 'yymm': '2101', 'arxiv_id': '2101.00524', 'language': 'en', 'url': 'https://arxiv.org/abs/2101.00524'}
arxiv
\section*{Acknowledgments} We appreciate all anonymous reviewers and the meta-reviewer, for their insightful comments. Tao Ge is the corresponding author. \section{Introduction} Text infilling (e.g., masked language modeling) has become a prevalent learning objective for pre-trained language models (PTLMs)~\citep{peters2018deep,radford2018improving,devlin2018bert,yang2019xlnet,liu2019roberta,lan2019albert,lewis2019bart,raffel2019exploring}. It provides self-supervision by masking out tokens or spans in text, and trains a model to infill the masked content based on the contexts, accordingly guiding the model for representation learning, as Figure \ref{fig:mainexample}(a) shows. \begin{figure*}[t] \centering \includegraphics[width=16cm]{sections/ssr_example_canwen.pdf} \caption{The comparison of \textbf{(a)} Text Infilling and \textbf{(b)} Sequence Span Rewriting. Instead of learning to directly fill the blanks, Sequence Span Rewriting first exploits an imperfect span generator to generate imperfect spans within the text and then feeds the filled text to the model to learn how to rewrite it into the ground truth.} \label{fig:mainexample} \end{figure*} In this paper, we propose to extend the conventional text infilling to a novel sequence-to-sequence (Seq2Seq) pre-training objective, namely \textbf{S}equence \textbf{S}pan \textbf{R}ewriting (SSR). We train a model to rewrite machine-generated imperfect text spans into the ground truth text, as illustrated in Figure \ref{fig:mainexample}(b). SSR has two advantages over text infilling: \textbf{(1) SSR provides better supervision signals,} as SSR trains the model with diverse and fine-grained rewriting patterns beyond filling the blanks; \textbf{(2) SSR bridges the gap between pre-training and fine-tuning,} because many downstream Seq2Seq tasks like summarization and paraphrase generation are naturally sequence span rewriting tasks where a source sentence is mapped to the target sentence following specific rewriting patterns The key element in implementing SSR is how to generate imperfect text spans that are both diverse and informative. Inspired by ELECTRA~\cite{clark2020electra}, we use a powerful pre-trained text infilling model -- T5-large~\cite{raffel2019exploring} -- as the imperfect span generator. Compared with random or rule-based noising approaches, the T5-based imperfect span generator can derive various informative text spans that benefit the model to learn meaningful and diverse rewriting patterns including paraphrasing and enhancing the fluency and contextual consistency through correcting grammatical, commonsense and factual errors, to improve a text sequence. These rewriting patterns resemble the goal of various NLG tasks and thus strengthen the ability of pre-trained model for downstream applications. In our experiments, we apply SSR to the typical Seq2Seq pre-trained model -- T5~\cite{raffel2019exploring} in a continual learning fashion. We show SSR outperforms both the original pre-trained T5 models and their continual training counterparts with the conventional text infilling objective on various Seq2Seq tasks, including text summarization, question generation, and grammatical error correction, with a small number of optimization steps with moderate amount of machine-generated data, which confirms the potential of SSR to serve as a plug-and-play method to improve various existing pre-trained Seq2Seq models. Notably, we find SSR especially useful for pre-training smaller Seq2Seq models, with the help of a powerful imperfect span generator. This observation sheds light on a new approach for knowledge transfer from large models to smaller ones. \section{Related Work} \paragraph{Pre-training in NLP} BERT~\citep{devlin2018bert} introduced the masked language modeling objective by masking out certain tokens in a text and predicting them based on their left and right side contexts. Recent work has shown that BERT's performance can be further improved by training for longer~\citep{liu2019roberta}, by tying parameters across layers~\citep{lan2019albert}, and by replacing a consecutive span of tokens with the mask token for MLM training~\citep{DBLP:journals/tacl/JoshiCLWZL20}. Our approach is also related to ELECTRA~\cite{clark2020electra}, which uses a pre-trained masked language model to generate fake tokens and train a discriminator to detect them. The key difference is that our approach focuses on span-level texts and trains the model to correct the mistakes instead of simply detecting them, which includes more diverse and informative signals and enables the model to perform text generation tasks in a Seq2Seq fashion. To enable mask language models for natural language generation tasks,~\citet{song2019mass} used a decoder to generate the masked tokens autoregressively. UniLM~\citep{dong2019unified} multitasks MLM and language modeling objectives. More recently, BART~\citep{lewis2019bart} and T5~\citep{raffel2019exploring} pre-train Seq2Seq models with the text span infilling objective, which removes text spans in the input texts and train the models to recover the original texts in an auto-regressive fashion. More recently, CALM~\citep{DBLP:conf/iclr/ZhouLSL021} introduces concept-to-sentence generation and concept order recovery as two self-supervised objectives that encourage Seq2Seq PTLMs to acquire generative commonsense reasoning ability. MARGE~\citep{lewis2020pre} pre-trains a Seq2Seq model with an unsupervised multi-lingual cross-document paraphrasing objective. Their approach is related to our text rewriting objective. However, MARGE requires multi-lingual paraphrase documents and needs to train a separate retrieval model while our method can simply used an off-the-shelf model pre-trained with text infilling to generate training data. Also, MARGE is pre-trained to generate a paraphrase-like document in another language, thus mainly helpful for translation tasks and multi-lingual tasks. In contrast, SSR focus on monolingual text rewriting and improve general text generation tasks. SSR departs significantly from the aforementioned methods for Seq2Seq pre-training as it employ machine-generated noises instead of rule-based ones, thus introducing more diverse training signals. Also, SSR receives complete inputs without artificial masks during pre-training relying solely on monolingual corpus. \paragraph{Model Acceleration for PTLMs} Recently, many attempts have been made to speed up a large pre-trained language model (PTLM). To name a few, \citet{shen2020q} quantized BERT to 2-bit using Hessian information; \citet{michel2019sixteen} pruned unnecessary attention heads in the transformer layers to reduce the parameters of a BERT model. DistilBERT~\citep{sanh2019distilbert} and uses knowledge distillation~\cite{hinton2015distilling,romero2014fitnets} to compress BERT. More recently,~\citep{DBLP:journals/corr/abs-2106-04570} proposed Meta Distillation to improve the performance of knowledge distillation for compression BERT. In addition,~\citet{xu2020bert} introduced progressive module replacing to train more compact BERT models by encouraging the student model to behave similarly with the teacher model. In addition,~\citet{zhou2020bert,schwartz2020right} proposed to accelerate the inference stage of pre-trained models via input-adaptive inference. However, to the best of our knowledge, few studies have been done for accelerating large sequence-to-sequence PTLMs. Our approach can also be used for model compression by using a large pre-trained model as the imperfect span generator. In this way, SSR also exploits the knowledge of a larger model to improve the training of a compact model. \section{Methodology} The key idea of SSR is to train a Seq2Seq model to rewrite machine-generated text spans that may contain a variety of noise such as paraphrase, grammatical and factual errors, into ground truth that are correct and appropriate in the context. As illustrated by Figure \ref{fig:mainexample}(b), SSR involves three steps: (1) masking out parts of the text; (2) generating imperfect text to fill in the masked spans; (3) training the Seq2Seq model to rewrite the imperfect spans to the ground truth. We will introduce the technical details of SSR in Section \ref{subsec:ssr} and an advanced training strategy for SSR in Section \ref{subsec:curriculum} \subsection{Sequence Span Rewriting} \label{subsec:ssr} \paragraph{Text Span Masking} To generate training data of sequence span rewriting in a self-supervised fashion, we first randomly sample a number of text spans and mask them. Specifically, the spans are masked with special mask tokens by order (e.g., \texttt{<s$_1$>}, \texttt{<s$_2$>} and \texttt{<s$_3$>}) in Figure \ref{fig:mainexample}(b) as in T5, with span lengths drawn from a Poisson distribution ($\lambda$ = 3). The number of spans is controlled so that approximately 30\% of all tokens are masked. Specially, 0-length spans correspond to an insertion of a mask token For example, as shown in Figure \ref{fig:mainexample}, given a sentence ``In 2002, Elon Musk founded SpaceX, an aerospace manufacturer company.'', we randomly sample three text spans (two of them are of length 1). The masked sentence becomes ``In \texttt{<s$_1$>}, Elon Musk \texttt{<s$_2$>} SpaceX, \texttt{<s$_3$>} company.'' \paragraph{Imperfect Span Generation} With masked spans, we can generate imperfect text to fill in the spans. Specifically, we feed the masked input into the imperfect span generator to generate predictions in an auto-regressive fashion. To improve the diversity of generation, we use nucleus sampling~\citep{Holtzman2020The} that truncates the unreliable tail of the probability distribution and samples from the dynamic nucleus of tokens containing the vast majority of the probability mass. For instance, given the previous masked input sentence, a T5-large model generates ``2001'', ``joined'', and ``a manufacturer'' as imperfect spans. \paragraph{Span Rewriting} After we obtain imperfect spans within the text, we pre-train the Seq2Seq model to rewrite imperfect text spans into the ground truth. Specifically, we use special tokens \texttt{<s$_i$>} and \texttt{</s$_i$>} to denote the starting and ending of $i$-th text span to be rewritten in the source sequence, which gives ``In \texttt{<s$_1$>} 2001 \texttt{</s$_1$>}, Elon Musk \texttt{<s$_2$>} joined \texttt{</s$_2$>} SpaceX, \texttt{<s$_3$>} a manufacturer \texttt{</s$_3$>} company.'' as the input for SSR pre-training. Similarly, we use \texttt{<s$_i$>} to separate different text spans in the target sequence, which gives ``\texttt{<s$_1$>} 2002 \texttt{<s$_2$>} founded \texttt{<s$_3$>} an aerospace manufacturer'' as the target sequence. We train the model to generate target text spans from left to right auto-regressively by maximum likelihood estimation. We can see that the SSR objective involves using a pre-trained model to generate imperfect spans, which will lead to increased computational cost. In practice, we suggest starting SSR pre-training based on checkpoints of existing Seq2Seq pre-trained models. In this way, we only need to generate a few amount of imperfect spans and continually pre-train the models for a few steps. In this perspective, SSR can be viewed as a general approach that be used to improve various Seq2Seq pre-trained models before fine-tuning them on downstream text generation tasks. For fine-tuning SSR, we simply denote the entire input sequence with the same span identifier (e.g., \texttt{<s$_1$>}) used during SSR pre-training. Therefore, the model would learn to rewrite the entire input sequence, alleviating the gap caused by the \texttt{<mask>} token during text infilling pre-training. For example, for grammatical error correction, the input is formatted as ``\texttt{<s$_1$>} I go to school yesterday. \texttt{</s$_1$>}'' and the output is ``\texttt{<s$_1$>} I went to school yesterday.'', which exactly corresponds to the pre-training format of SSR. In addition, for some constrained text generation tasks~\citep{DBLP:conf/emnlp/LinZSZBCR20} and controlled text generation~\citep{DBLP:conf/icml/HuYLSX17} tasks, we can specify which part of input text to be rewritten with span identifiers. This enables more flexible text generation with Seq2Seq pre-trained models. Taking text attribute transfer as an example, an input example would looks like ``Great food \texttt{<s$_1$>} but very rude \texttt{</s$_1$>} waiters.'' and the corresponding target sequence is ``\texttt{<s$_1$>} and very friendly''. The inductive bias of span rewriting learned by SSR pre-training naturally benefit these kind of NLG applications. \subsection{Curriculum SSR} \label{subsec:curriculum} As mentioned above, we apply SSR as a continual training objective for pre-trained Seq2Seq models that were originally trained with the text infilling objective. However, continually training a pre-trained Seq2Seq model with a different objective may result in drastic adaption of its parameters. To make this transition smoother and reduce the difficulty of optimization, we propose to schedule the SSR training examples with curriculum learning~\citep{bengio2009curriculum} according to their difficulties. Specifically, we measure the difficulty of rewriting a certain imperfect text span with both the length of the imperfect span and the uncertainty (i.e., perplexity) of the imperfect span generator when generating this span. Intuitively, a short imperfect span generally includes some simple word substitution (e.g., big $\rightarrow$ large) or grammatical error (e.g., is $\rightarrow$ was) while a longer imperfect span may require more complicated paraphrasing (e.g., what is happening $\rightarrow$ what's up). Also, an imperfect span with larger perplexity suggests the span may be of lower quality or more uncommon, thus more difficult to be rewritten into ground truth. Therefore, we consider longer imperfect spans and spans with a higher perplexity under the imperfect span generator to be more difficult. We split the SSR training examples into $k$ ($k=5$ in our experiments) groups according to the sum of per-token loss of the imperfect span generator when it generates an SSR training example. We then start pre-training the model with the easiest group of SSR training examples and then gradually switch to more difficult groups during pre-training. Intuitively, this will make the transition from the original text infilling objective to the sequence span rewriting objective more smooth. \section{Experiments} \subsection{Experimental Settings} SSR\xspace is implemented as a text-to-text transformer model with a bidirectional encoder and a left-to-right auto-regressive decoder. For pre-training, we minimize the negative log-likelihood of the original ground truth text spans. We describe details of the architecture, pre-training, and fine-tuning of SSR\xspace in this section. \paragraph{Architecture} We use the same architecture as T5~\citep{raffel2019exploring} which is roughly equivalent to the original Transformer proposed by~\citet{vaswani2017attention}, with the exception of removing the Layer Norm bias, placing the layer normalization outside the residual path, and using a different relative position embedding scheme Following the design choice of T5~\citep{raffel2019exploring}, we train three sizes of SSR\xspace: \begin{itemize} \item SSR\xspace-small: 60M parameters, 6 Transformer layers, 8 attention heads, 512 hidden size \item SSR\xspace-base: 220M parameters, 12 Transformer layers, 12 attention heads, 768 hidden size \item SSR\xspace-large: 770M parameters, 24 Transformer layers, 16 attention heads, 1024 hidden size \end{itemize} \paragraph{Pre-training Details} As we propose SSR to serve as a general plug-and-play approach to improve existing Seq2Seq pre-trained models without intensive computation like pre-training from scratch, we initialize each size of SSR\xspace model with the corresponding pre-trained T5 model of the same size, and continually pre-train the models with the SSR objective. \begin{table*}[!tbp] \centering \begin{minipage}{\textwidth} \centering \resizebox{\textwidth}{!}{ \begin{tabular}{lclllllll} \toprule \multirow{2}{*}{\textbf{Model}} & \multirow{2}{*}{\textbf{Architecture}} & \multicolumn{3}{c}{\textbf{CNN/DM}} &\multicolumn{3}{c}{\textbf{XSum}}\\ \cmidrule(lr){3-5} \cmidrule(lr){6-8} & & RG-1 & RG-2 & RG-L & RG-1 & RG-2 & RG-L \\ \midrule \multicolumn{8}{c}{\textit{Performance of models without pre-training}} \\ \midrule Lead-3 & - & 40.42 & 17.62 & 36.67 & 16.30 & 1.60 & 11.95 \\ PTGEN~\citep{see2017get} & - & 36.44 & 15.66 & 33.42 & 29.70 & 9.21 & 23.24 \\ \midrule \multicolumn{8}{c}{\textit{Performance of state-of-the-art models based on pre-trained models of comparable size}} \\ \midrule MASS~\citep{song2019mass} & L=6, H=1024 & 42.12 & 19.50 & 39.01 & 39.75 & 17.24 & 31.95 \\ BERTSumAbs~\citep{liu2019text} & L=12, H=768 & 41.72 & 19.39 & 38.76 & 38.76 & 16.33 & 31.15 \\ UniLMv2~\citep{bao2020unilmv2} & L=12, H=768 & 43.16 & 20.42 & 40.14 & 44.00 & 21.11 & \bf 36.08 \\ \midrule \multicolumn{8}{c}{\textit{Performance of comparable models based on T5-base}} \\ \midrule T5-base~\citep{raffel2019exploring} & L=12, H=768 & 42.25 & 20.22 & 39.45 & 43.12 & 20.84 & 34.98 \\ T5-base-cont & L=12, H=768 & 42.49 & 20.33 & 39.65 & 43.32 & 20.94 & 35.21 \\ DistilT5-base & L=12, H=768 & 42.37 & 20.25 & 39.53 & 43.25 & 20.89 & 35.14 \\ DenoiseT5-base & L=12, H=768 & 42.22 & 20.18 & 39.41 & 43.14 & 20.82 & 35.03 \\ SSR\xspace-base & L=12, H=768 & \bf 43.53$^{*}$ & \bf 20.79$^{*}$ & \bf 40.44$^{*}$ & \bf 44.05 & \bf 21.19 & 35.88 \\ \bottomrule \end{tabular} } \caption{Abstractive summarization results. We also present the transformer architecture for the methods using pre-trained models. For example, L=12, H=768 means both the encoder and decoder are built with 12 transformer layers with a hidden size of 768. $^{*}$The asterisk denotes statistically significant improvement with p-value < 0.05 upon all compared models.} \label{tab:result1} \end{minipage} \end{table*} For imperfect span generation, we use the off-the-shelf T5-large model with nucleus sampling ($p=0.9$) to sample generated text spans. For SSR learning, we sample 4GB of text from Wikipedia corpus, BookCorpus~\citep{zhu2015aligning}, and RealNews~\citep{zellers2019defending}, which are commonly used for pre-training language models. Our implementation is based on Hugging Face Transformers~\cite{wolf2020transformers}. We use text sequences with a maximum length of 256 tokens to sample masked text spans and generate imperfect text spans. We then continually pre-train different variants of SSR\xspace for 100k updates\footnote{We empirically find 100k updates to be enough since the models' performance on downstream tasks begin to saturate.}, with a maximum sequence length of 256, a batch size of 512, and a learning rate of 5e-5 with a linear warm-up for the first 8,000 updates. It is noteworthy that although SSR requires using a pre-trained Seq2Seq model for imperfect span generation, the computation cost of using SSR to improve a Seq2Seq pre-trained model is still considerably smaller than the pre-training cost. This is because SSR requires much smaller training corpus and optimization steps when employed in a continual pre-training setting. This also reduces recent concerns~\citep{strubell2019energy,parrot} about the carbon footprint and energy consumption in LM pre-training. \subsection{Tasks and Datasets} \paratitle{Abstractive Summarization} aims to rewrite a long document into a short summary. To provide a comparison with the recent work in pre-trained models for this task, we present results on two widely used summarization datasets: CNN/DailyMail~\citep{hermann2015teaching} and XSum~\citep{narayan2018don}, and report evaluation results in terms of ROUGE-1, ROUGE-2 and ROUGE-L~\citep{lin-2004-rouge}. \paratitle{Question Generation} is to generate valid and fluent questions according to a given passage and target answers. It can be considered as rewriting a target answer and its surrounding context into a question form. Following previous work~\citep{dong2019unified}, we concatenate the passage and an answer as the input of the model to learn to generate the corresponding question in the fine-tuning stage. We use SQUAD~\citep{rajpurkar2016squad} dataset to train and test question generation following the data split in~\citep{du-cardie-2018-harvesting}. We report evaluation results in terms of BLEU~\citep{papineni-etal-2002-bleu}, METEOR~\citep{banerjee-lavie-2005-meteor}, and CIDEr~\citep{vedantam2015cider}. \paratitle{Grammatical Error Correction} is a task that rewrites a potentially erroneous input sentence into a fluent sentence that is grammatical error free without changing the original meaning of the input sentence. Following the recent work~\cite{grundkiewicz2019neural,kiyono2019empirical,zhou2019improving} in GEC, we use the public Lang-8~\cite{mizumoto2011mining}, NUCLE~\cite{dahlmeier2013building}, FCE~\cite{yannakoudakis2011new} and W\&I+LOCNESS datasets~\cite{bryant2019bea,granger1998computer} for fine-tuning without using any synthetic GEC data, and then evaluate Max-Match (M$^2$) precision, recall, and F$_{0.5}$ score on the CoNLL-2014~\citep{ng2014conll} test set. \begin{table*}[!tbp] \centering \begin{minipage}{\textwidth} \centering \resizebox{\textwidth}{!}{ \begin{tabular}{lclllllll} \toprule \multirow{2}{*}{\textbf{Model}} & \multirow{2}{*}{\textbf{Architecture}} & \multicolumn{3}{c}{\textbf{Question Generation}} &\multicolumn{3}{c}{\textbf{GEC}}\\ \cmidrule(lr){3-5} \cmidrule(lr){6-8} & & BLEU-4 & METEOR & CIDEr & P & R & F$_{0.5}$ \\ \midrule \multicolumn{8}{c}{\textit{Performance of baseline models without pre-training}} \\ \midrule \citet{zhang2019addressing} & - & 18.37 & 22.65 & 46.68 & - & - & - \\ Xfmr-big~\citep{chen2020improving} & L=12, H=1024 & - & - & - & 64.9 & 26.6 & 50.4 \\ Xfmr-big + Synthetic Data~\citep{zhou-etal-2020-pseudo} & L=12, H=1024 & - & - & - & 69.1 & 33.7 & 57.1 \\ \midrule \multicolumn{8}{c}{\textit{Performance of state-of-the-art models based on pre-trained models of comparable size}} \\ \midrule UniLMv2~\citep{bao2020unilmv2} & L=12, H=768 & \bf 24.43 & 26.34 & 51.97 & - & - & - \\ \midrule \multicolumn{8}{c}{\textit{Performance of comparable models based on T5-base}} \\ \midrule T5-base~\citep{raffel2019exploring} & L=12, H=768 & 23.74 & 25.95 & 51.61 & 68.6 & 33.5 & 56.7 \\ T5-base-cont & L=12, H=768 & 23.93 & 26.11 & 51.78 & 69.6 & 33.6 & 57.3 \\ DistilT5-base & L=12, H=768 & 23.86 & 25.93 & 51.64 & 69.3 & 33.1 & 56.9 \\ DenoiseT5-base & L=12, H=768 & 23.70 & 25.91 & 51.58 & 69.5 & 33.4 & 57.1 \\ SSR\xspace-base & L=12, H=768 & 24.35 & \bf 26.51$^{*}$ & \bf 52.11$^{*}$ & \bf 70.5$^{*}$ & \bf 34.9$^{*}$ & \bf 58.7$^{*}$ \\ \bottomrule \end{tabular} } \caption{Question generation and GEC results. We also present the transformer architecture for the methods using transformer models. For example, L=12, H=768 means both the encoder and decoder are built with 12 transformer layers with a hidden size of 768. $^{*}$The asterisk denotes statistically significant improvement with p-value < 0.05 upon all compared models.} \label{tab:result2} \end{minipage} \end{table*} \subsection{Compared Models} We compare SSR\xspace with the following models: \begin{itemize} \item \textbf{T5}: the original pre-trained text-to-text transformer based on the text infilling objective. \item \textbf{T5-cont}: text-to-text transformer initialized by T5 and continually pre-trained with the original text infilling objective with additional training steps. The total number of additional training steps is equal to that of SSR\xspace. \item \textbf{DistilT5}: the variant that continually pre-trains T5 by text infilling with sequence-level knowledge distillation~\citep{kim2016sequence}. This is implemented by using the imperfect text spans generated by T5-large as target outputs for text infilling. DistilT5-small and DistilT5-base are similar to conventional sequence-level knowledge distillation while DistilT5-large can be viewed as continually pre-trained with self-distillation. \item \textbf{DenoiseT5}: the variant that injects rule-based noises into plain text and continually pre-train a T5 model to output the original text. The rule-based noises include token shuffling, deletion, and replacement. We adopt the same noise strategy as described in~\citet{wang-etal-2019-denoising}. \end{itemize} For reference, we also compare against two state-of-the-art base-sized pre-trained models for NLG including MASS~\citep{song2019mass} and UniLMv2~\citep{bao2020unilmv2}. \subsection{Experimental Results} We first present experimental results of SSR\xspace-base and comparable baselines on different datasets. Then we show additional results of SSR\xspace-small and SSR\xspace-large for further analysis. \paragraph{Summarization Results} According to Table \ref{tab:result1}, it is observed that SSR\xspace-base substantially improves the original T5-base model and its continual training variants on both CNN/DM and XSum datasets, and achieves state-of-the-art results for the models of the same size in the abstractive summarization benchmarks. It is notable that our models are only continually pre-trained on a relatively small dataset for only a few number of updates. This confirms the potential of our approach as a general ``plug-and-play'' approach for improving various kinds of sequence-to-sequence pre-trained models. In contrast, using T5-large as a teacher model fails to improve the training of a T5-base student with sequence-level knowledge distillation. This shows SSR can better exploit the capability of a large Seq2Seq pre-trained model to improve a smaller one, indicating its potential to serve as a model compression technique for Seq2Seq pre-trained models. \begin{table}[!tbp] \centering \begin{minipage}{\linewidth} \centering \resizebox{0.95\linewidth}{!}{ \begin{tabular}{llll} \toprule \multirow{2}{*}{\textbf{Model}} & \multicolumn{3}{c}{\textbf{CNN/DM}} \\ & RG-1 & RG-2 & RG-L \\ \midrule T5-large & 43.09 & 20.68 & 40.15 \\ T5-large-cont & 43.14 & 20.71 & 40.21 \\ DistilT5-large & 43.05 & 20.63 & 40.07 \\ SSR\xspace-large & \bf 43.65$^{*}$ & \bf 20.98$^{*}$ & \bf 40.69$^{*}$ \\ \bottomrule \end{tabular} } \caption{Abstractive summarization results on CNN/DailyMail for SSR-large and corresponding T5 models of the same size. $^{*}$The asterisk denotes statistically significant improvement with p-value < 0.05 upon all compared models. } \label{tab:result3} \end{minipage} \end{table} \paragraph{Question Generation and GEC Results} Similar results are observed for question generation and GEC tasks, as shown in Table \ref{tab:result2}: SSR\xspace-base substantially outperforms all the other T5 variants and achieves comparable or even better results than the other base-size pre-trained models. Surprisingly, continually pre-training T5-base with SSR can achieve significant improvement over a transformer-big model pre-trained on rule-based synthetic data. We attribute this to the closer relationship between the task of GEC and our proposed SSR objective and more diverse grammatical errors introduced by the machine-generated spans. Interestingly, we observe the improvement of SSR\xspace on the GEC task is even more significant than that on question generation and summarization datasets, because SSR is intuitively more similar to the challenge of GEC which can be well addressed by span correction \cite{chen2020improving}. \subsection{Analysis} \paragraph{Impact of Model Size} To analyze the effectiveness of the proposed SSR objective for Seq2Seq pre-trained models with different sizes, we report the performance comparison of small-size and large-size SSR\xspace and different T5-based baselines. Note that we focus on analysis of SSR on the same T5 backbone model and do not compare against other large-sized Seq2Seq PTLMs because they are pre-trained with different data and number of stpes, thus are not comparable with our models. We present the results of large-size models and small-size models in Table \ref{tab:result3} and Table \ref{tab:result4}, respectively.\footnote{We do not compare against the variant with the denoising-based objective since its performance is consistently lower than the baseline in the previous experiments.} We find that the sequence span rewriting objective improves both large-size and small-size models. However, the improvement upon small-size models is significantly larger than that upon large-size models. This suggests that our method is more effective when the infilling model is significantly larger than the rewriting model. The performance of SSR\xspace-small is also significantly better than DistilT5-small sequence-level knowledge distillation. That indicates SSR's potential on exploiting the knowledge from large pre-trained Seq2Seq transformers to improve the training of smaller models in a task-agnostic fashion. \begin{table}[!tbp] \centering \begin{minipage}{\linewidth} \centering \resizebox{0.95\linewidth}{!}{ \begin{tabular}{llll} \toprule \multirow{2}{*}{\textbf{Model}} & \multicolumn{3}{c}{\textbf{CNN/DM}} \\ & RG-1 & RG-2 & RG-L \\ \midrule T5-small & 40.22 & 19.36 & 37.85 \\ T5-small-cont & 40.43 & 19.55 & 38.08 \\ DistilT5-small & 40.38 & 19.49 & 38.01 \\ SSR\xspace-small & \bf 41.95$^{*}$ & \bf 20.06$^{*}$ & \bf 39.01$^{*}$ \\ \bottomrule \end{tabular} } \caption{Abstractive summarization results on CNN/DailyMail for SSR-small and corresponding T5 models of the same size. $^{*}$The asterisk denotes statistically significant improvement with p-value < 0.05 upon all compared models.} \label{tab:result4} \end{minipage} \end{table} \begin{table}[!tbp] \centering \begin{minipage}{\linewidth} \centering \resizebox{\linewidth}{!}{ \begin{tabular}{llccc} \toprule \multirow{2}{*}{\textbf{Model}} & \textbf{Imperfect} & \multicolumn{3}{c}{\textbf{CNN/DM}} \\ & \textbf{Span Generator} & RG-1 & RG-2 & RG-L \\ \midrule T5-base & - & 42.25 & 20.22 & 39.45 \\ SSR-base & T5-base & 42.78 & 20.51 & 39.97 \\ SSR-base & T5-large & \bf 43.47 & \bf 20.74 & \bf 40.37 \\ \midrule T5-small & - & 40.22 & 19.36 & 37.85 \\ SSR-small & T5-base & 41.03 & 19.74 & 38.68 \\ SSR-small & T5-large & \bf 41.95 & \bf 20.06 & \bf 39.01 \\ \bottomrule \end{tabular} } \caption{Abstractive summarization results on CNN/DailyMail for SSR with imperfect span generator of different sizes.} \vspace{-3mm} \label{tab:result-gensize} \end{minipage} \end{table} \paragraph{Impact of Imperfect Span Generator} We also investigate the impact of the size of the imperfect span generator. This time, we generate imperfect text spans for pre-training using T5-base model and continually pre-train SSR-base and SSR-small. The results are shown in Table \ref{tab:result-gensize}. We find that our approach performs better with a larger imperfect span generator, which seems in contradiction to the findings in the replaced token detection objective introduced in ELECTRA~\cite{clark2020electra}. We suspect the reason is that the task of span-level infilling is more challenging than its token-level counterpart. Therefore, a small imperfect span generator may not be powerful enough to generate imperfect text spans that are meaningful and of relatively high quality. Consequently, the rewriting model may simply learn to ignore the imperfect spans and the SSR objective will degrade into text infilling. Moreover, we can see that the improvement yielded by the SSR objective is more significant when the size of the imperfect span generator is larger than the rewriting model that we aim to train. This confirms that SSR can effectively exploit the knowledge of a large model to better train a smaller one. Interestingly, we find that using imperfect spans generated by T5-base to continually pre-train T5-base can still improve the performance, which is similar to the case of self-distillation~\citep{furlanello2018born}. \begin{table}[!tbp] \centering \begin{minipage}{\linewidth} \centering \resizebox{\linewidth}{!}{ \begin{tabular}{llll} \toprule \multirow{2}{*}{\textbf{Model}} & \multicolumn{3}{c}{\textbf{CNN/DM}} \\ & RG-1 & RG-2 & RG-L \\ \midrule SSR-base & \bf 43.53$^{*}$ & \bf 20.79$^{*}$ & \bf 40.47$^{*}$ \\ \quad No curriculum & 43.26 & 20.53 & 40.14 \\ \quad Anti-curriculum & 43.09 & 20.48 & 40.01 \\ \quad Loss-only curriculum & 43.40 & 20.67 & 40.25 \\ \quad Length-only curriculum & 43.43 & 20.71 & 40.35 \\ \bottomrule \end{tabular} } \caption{Ablation study results on CNN/DailyMail for SSR-base with different curriculum learning strategies. $^{*}$The asterisk denotes statistically significant improvement with p-value < 0.05 upon all compared ablation.} \label{tab:result-curr} \end{minipage} \end{table} \paragraph{Impact of Curriculum Pre-training} We then analyze the effectiveness of the proposed curriculum pre-training technique. We continually pre-train SSR-base with three variants of the proposed curriculum pre-training method: \textit{No curriculum} denotes the variant without curriculum pre-training; \textit{Anti-curriculum} denotes the variant where pre-training starts with difficult examples; \textit{Loss-only} and \textit{Length-only curriculum} denote a curriculum based solely on per-token loss and the length of imperfect span, respectively. The results are shown in Table \ref{tab:result-curr}. We find that pre-training SSR from relatively easy examples to hard examples statistical significantly improve its performance on downstream tasks. More specifically, we find that scheduling the training examples by their length is slightly more effective than by per-token loss, while the combination of them can yield further improvements. \section{Discussion} \paragraph{Pre-training via Rewriting} We discuss several key advantages of SSR over the conventional text infilling objectives here. \textbf{(1) SSR is closer to the downstream sequence transduction tasks.} This is because the model's prediction is not only based on its bidirectional context but also conditioned on the imperfect spans. In this way, the gap between pre-training and fine-tuning stages, which is introduced by the masked tokens or spans in conventional pre-training objectives, is alleviated. Indeed, many NLG tasks can be viewed as sequence span rewriting problems that rewrite the input text into another language, more compact format, grammatically correct sentences, or another style. \textbf{(2) SSR introduces more diverse noise patterns.} These patterns include paraphrasing and simplification of the text span, missing or redundant information, grammatical errors, and errors in terms of world knowledge or commonsense knowledge. In fact, many of the rewriting patterns introduced by SSR resemble training examples in the downstream tasks. In contrast, conventional self-supervised Seq2Seq pre-training techniques rely on rule-based noise functions like text span masking, token masking, token deletion, token rotation, sentence shuffling, etc. \textbf{(3) SSR enables the model to learn from informative examples.} SSR enables the model to learn from informative examples, where the span generator makes an error. This provides more meaningful supervision and is also similar to the idea of active learning~\cite{settles2009active}. \paragraph{Distillation via Rewriting} SSR sheds light on a new perspective of exploiting the knowledge of a large pre-trained model to improve smaller models. Similar to knowledge distillation (KD), this can be achieved by using a large-size teacher model pre-trained with the text infilling objective as the imperfect span generator, and pre-train or refine a small-size student model with the generated data using SSR. Different from conventional KD~\citep{hinton2015distilling} or sequence-level KD~\citep{kim2016sequence}, SSR enables the student model to exploit both teacher outputs and the ground truth at the same time. It is also related to boost learning~\citep{schapire2003boosting} and residual learning~\citep{he2016deep} in a sense that the model only needs to learn the prediction error of the teacher model, instead of the original task, text infilling, which may be too difficult for smaller-size models. \section{Conclusion} We present sequence span rewriting (SSR\xspace), a novel self-supervised objective for improving sequence-to-sequence transformers pre-trained with conventional text infilling objectives. SSR introduces more diverse and fine-grained learning signals and also bridges the gap between self-supervised pre-training and task-specific fine-tuning on common NLG datasets. Our experiments on continual T5 pre-training confirm the effectiveness of SSR\xspace on improving pre-trained T5 models of different sizes across different tasks and datasets. Also, the large improvements achieved on small models with a larger imperfect span generator indicates a new perspective of exploiting the knowledge of a large pre-trained model to help train smaller ones. \section*{Ethical Considerations} Our approach is proposed to improve existing sequence-to-sequence pre-training techniques. It does not involve the collection and release of data except that generated by a pre-trained model, nor inference of information or judgments about individuals. That being said, since an improved sequence-to-sequence pre-trained model may be used in various downstream applications, it is still an important future direction to investigate the bias, fairness, and privacy issue in various kinds of pre-trained models.
{'timestamp': '2021-09-27T02:12:55', 'yymm': '2101', 'arxiv_id': '2101.00416', 'language': 'en', 'url': 'https://arxiv.org/abs/2101.00416'}
arxiv
\section{Introduction} A massive number of Internet-of-Things (IoT) devices will emerge in the market to enable advanced IoT based applications such as environmental monitoring, smart homes, smart transportation networks, and smart cities, to name a few. According to Cisco's most recent internet report \cite{Cisco}, IoT connections will reach $14.7$ billion by $2023$ which accounts for half of the global connected devices. Centralized and scheduling-based multiple access techniques cannot fully support such unprecedented growth in the number of IoT devices because scheduling the transmissions of a massive number of IoT devices would introduce significant computational and communication overheads. Due to their scalability and ease of implementation, distributed random-access-based wireless technologies such as Wi-Fi, Zigbee, and Aloha-based LoRaWAN, will have a major role in provisioning massive IoT access in beyond 5G systems \cite{khairy2018renewal,khairy2019sustainable,el2018lora}. It is well recognized that Non Orthogonal Multiple Access (NOMA) can improve the channel access efficiency in 5G cellular networks by exploiting Successive Interference Cancellation (SIC) to decode non-orthogonal data transmissions \cite{ding2017application,ding2017survey,maraqa2019survey,ni2019analysis}. In slotted-Aloha systems, applying NOMA can significantly improve the channel access efficiency as users are randomly paired when they access the channel \cite{choi2017noma,choi2018game,choi2018multichannel,ziru}. Integrating NOMA with slotted-Aloha systems is therefore a promising solution to support massive machine type communications (mMTC) of IoT devices in beyond 5G networks \cite{khairy2020constrained}. Analyzing the performance of multi-cell slotted-Aloha systems with NOMA however, is very challenging due to the combinatorial space of possible transmissions and interference events that affect data decoding at the base stations. To circumvent this complexity, existing works mainly focused on a single-cell random access network where users can meet one of pre-specified target received power levels at the base stations to simplify the analysis \cite{choi2017noma,choi2018game, choi2018multichannel,ziru}. In a realistic large scale wireless IoT network, wireless users are spatially distributed in multiple cells with inter-cell interference, and perfect power control to meet the target received power levels at the base stations may not be available. Machine learning enables a data-driven approach for holistic system design, control, and optimization, which can be leveraged to study challenging multi-cell wireless IoT systems in 5G and beyond. In this work, we consider a high-density spatially-distributed multi-cell wireless IoT network with a massive number of IoT devices. IoT devices send uplink sensor data to the base stations (BSs) using an adaptive $p$-persistent slotted Aloha protocol. BSs, on the other hand, exploit power-domain SIC to decode concurrent transmissions of multiple users when possible, thus improving the random access efficiency. To attain a capacity-optimal massive IoT network, we study wireless channel access management of each individual IoT device to leverage the heterogeneity of users' channels. To the best of our knowledge, our work is the first work to study network performance of a high-density spatially-distributed multi-cell wireless IoT network with NOMA, and is the first to conceive a provably-optimal data-driven framework for managing the random access probabilities of individual IoT devices in a multi-cell network environment. The main contributions of our work can be summarized as follows. First, we propose a novel formulation to manage channel access of individual IoT devices in a multi-cell wireless IoT network with NOMA. Specifically, we formulate the problem of channel access of IoT devices as a single stage optimization problem, where the objective is to maximize the geometric mean of users' expected capacity. Second, we show that this optimization objective, albeit being mathematically intractable and high dimensional, admits favourable mathematical properties which enable the design of efficient data-driven algorithmic solutions that avoid channel access starvation of users in multi-cell networks. Third, two learning based algorithms are proposed to optimally tune the transmission probabilities of IoT devices. The first algorithm is a centralized model-based algorithm in which a central controller learns an Input-Concave Neural Network (ICNN) to predict the system's performance. An upper confidence bound type approach is devised to strike a balance between model exploration and model exploitation; and the optimal transmission probabilities can be found by gradient ascent-based optimization on the learned model. The second algorithm is a scalable, distributed, model-free algorithm, in which each individual IoT device adapts its transmission probability locally based on an observable aggregate quantity that is a function of other users' transmission probabilities. Because the proposed algorithms are data-driven and enable continual learning in the sense that network capacity is improved as more algorithm iterations are executed, knowledge of the channel model or the network topology is not required. The convergence of the proposed algorithms to the optimal solution is further established based on convex optimization and game-theoretic analysis. Last but not least, we conduct extensive simulations to demonstrate the merits of the novel formulation and the efficacy of the proposed algorithms. It is shown that optimizing the geometric mean of users' expected capacity can greatly improve the throughput fairness among devices. The remainder of this paper is organized as follows. Related research works are given in Sec. II, followed by the system model and the problem formulation in Secs. III and IV, respectively. The proposed centralized and distributed learning based algorithms are presented in Secs. V and VI. The performance evaluation results are provided in Sec. VII, followed by concluding remarks and future work in Sec. VIII. \section{Related Works} The application of NOMA in $5$G networks have been extensively studied in the literature. In \cite{ding2015impact,al2017optimum}, a centralized scheduling-based network is considered, where the central controller schedules the transmissions of pairs of users, and decides their transmission powers according to their channel conditions, in order to maximize the sum-rate performance of NOMA users. Centralized scheduling, however, is not considered as a scalable solution for the unprecedented growth in the number of IoT devices. For instance, in mMTC $5$G based networks, scheduling transmissions of a massive number of IoT devices would incur significant overheads. In addition, it may be too expensive for low power IoT devices to estimate their channel conditions and provide the scheduler with channel state information in a timely manner. Recent works have proposed to apply NOMA in a slotted Aloha system such that users are randomly paired when they distributively access the channel to support mMTC in $5$G and beyond. Simulation results in \cite{elkourdi2018enabling} show that the throughput performance of slotted Aloha with NOMA significantly outperforms that of conventional slotted Aloha. A game-theoretic formulation to determine the transmission probability in a single-cell NOMA-based Aloha system is introduced in \cite{choi2018game,choi2018multichannel}. The proposed solution considers a payoff function based on an energy-efficiency metric, which ensures Nash equilibrium but not maximum throughput. In \cite{seo2018nonorthogonal,seo2018performance,seo2018two,seo2019uplink}, a slotted Aloha system with NOMA and random channel fading is investigated. In this single-cell system, users choose one of pre-specified target received power levels at the BS based on either their channel gain or the geographical region corresponding to the BS. The system is analyzed in terms of access delay, throughput, and energy efficiency, and it is was shown that the achievable maximum throughput significantly outperforms that of conventional slotted Aloha without NOMA, which is consistent with the findings of \cite{elkourdi2018enabling}. Single-cell multi-channel Aloha with NOMA is studied in \cite{choi2017noma} where different users with multiple transmission power levels are distributed in different channels. A closed-form expression for a lower-bound on the throughput was derived, and it was shown that applying NOMA can provide a higher throughput than multi-channel Aloha by exploiting power difference \cite{choi2017noma}. While increasing the number of power levels in multi-channel slotted Aloha with NOMA leads to further gains in the maximum achievable throughput, the gains are slower than linear \cite{yu2020throughput}. Some works have also studied algorithm design in single-cell slotted Aloha systems with NOMA and two target received power levels in order to optimize network throughput in \cite{qu2019distributed,ziru}. In all these aforementioned works, single-cell slotted Aloha wireless networks with NOMA are studied. Furthermore, efficient power control techniques are assumed such that users can meet the target received power levels at the BS. In practical networks, wireless IoT devices are likely distributed in a large scale multi-cell network with inter-cell interference and experience heterogeneous wireless fading channels, which make optimal power control very challenging if not impossible. To the best of our knowledge, our work is the first to propose a provably-optimal data-driven framework to optimize individual random channel access probabilities of IoT devices in a multi-cell network environment with NOMA. \section{System Model} \label{sec:sysmod} We consider a multi-cell IoT network consisting of $M$ Base Stations (BSs) and $N$ IoT devices in which IoT devices transmit uplink sensor data to the BSs using an adaptive $p$-persistent slotted Aloha protocol. Let $\mathcal{M}=\{1,\cdots, M\}$ be the set of BSs, and $\mathcal{N}=\{1,\cdots, N\}$ be the set of IoT devices. Time is slotted into fixed-length communication slots indexed by $n$, that is, the $n$-th communication slot is $[t_n, t_{n+1})$, where $t_{n+1} - t_n = \Delta t,~\forall n$. In the beginning of a slot $n$, an IoT device, e.g., device $i \in \mathcal{N}$, attempts to access the channel with probability $p_i$ in order to transmit its most recent sensor data to the BS, which in turn relays the data to remote network servers. Channel access probability of individual devices, $p_i, \forall i \in \mathcal{N}$, is locally adapted in order to leverage the heterogeneity of users' channels and attain the maximum network capacity. Each IoT device is served by the nearest BS. Let $\mathcal{N}_m \subseteq \mathcal{\mathcal{N}}$ denote the subset of IoT devices which are associated with BS $m$, such that $|\mathcal{N}_m|\leq N$, $\bigcup_{m=1}^M \mathcal{N}_m = \mathcal{N}$, $\mathcal{N}_i \cap \mathcal{N}_j= \phi, \forall i\neq j \in \mathcal{M}$. Let $u^{i,m}=\{0,1\}$ indicate whether IoT device $i$ associates with BS $m$. If BS $m$ is the closest to IoT device $i$, $u^{i,m}=1$, and $u^{i,l}=0, \forall l \neq m$. IoT devices transmit with a fixed transmission power of $P_{TX}$ watts. The power of the signal transmitted by an IoT device $i$ to BS $m$ in any given communication slot is typically subject to a random channel model which accounts for small-scale and large-scale fading. In this work, we study the design of a data-driven network optimization framework which only depends on observing an aggregate quantity of users' throughputs as a feedback mechanism, and hence knowledge of the channel model or network topology are not required. Let $P^{i,m}_{RX}$ denote the received power at BS $m$ from IoT device $i$ in a communication slot $t_n$ given that user $i$ transmits. BS $m$ first attempts to decode the signal with the highest signal power under the interference from all other IoT devices involved in the NOMA transmissions. Without loss of generality, IoT devices which transmit in slot $n$ are sorted in the descending order of the received signal strength at BS $m$, such that $i=1$ is the IoT device with the highest received signal to interference plus noise (SNIR) at BS $m$, and $i=2$ is the IoT device with the second highest received SNIR at BS $m$ \footnote{Due to the decoding complexity of SIC, we consider that the two highest received signals of NOMA transmissions are possibly decodable, yet our proposed framework is readily extensible for more than 2 NOMA transmissions.}. Because of the distributed random channel access protocol, users $i\in\{1,2\}$ are randomly paired when they distributively access the channel. Let $\mathcal{I}_m$ be the random set of transmitters in slot $t_n$. The highest received SNIR at BS $m$ in slot $t_{n}$ is therefore, \begin{equation} \text{SNIR}_{1,m} = \frac{P^{1,m}_{RX}}{n_0 + \sum_{k \in \mathcal{I}_m \setminus \{1\}} P^{k,m}_{RX}}, \end{equation} where $n_0$ is the noise floor power. Similarly, the second highest received SNIR at BS $m$ in slot $t_{n}$ is, \begin{equation} \text{SNIR}_{2,m} = \frac{P^{2,m}_{RX}}{n_0 + \sum_{k \in \mathcal{I}_m\setminus \{1,2\} } P^{k,m}_{RX}}, \end{equation} BS $m$ can decode the signal with $\text{SNIR}_{1,m}$ if \begin{enumerate} \item user 1 is associated with BS $m$, $u_n^{1,m}=1$, and, \item $\text{SNIR}_{1,m}$ is larger than or equal to the SNIR threshold $\text{SNIR}_\text{Th}$, i.e., $\Phi(\text{SNIR}_{1,m})=\text{SNIR}_{1,m}$, \end{enumerate} where $\Phi(.)$ is a threshold function to maintain a minimum target SNIR and quality of service, that is, $\Phi(\text{SNIR}_{i,m})=\text{SNIR}_{i,m}$ if $\text{SNIR}_{i,m} \geq \text{SNIR}_\text{Th}$, and $\Phi(\text{SNIR}_{i,m})=0$ otherwise. \begin{comment} \begin{equation} \label{snrthres} \begin{gathered} \begin{aligned} \Phi(\text{SNIR}_{i,m})= \begin{cases} 0,~~~~~~~~~\text{SNIR}_{i,m} < \text{SNIR}_\text{Th}, \\ \text{SNIR}_{i,m}, \text{SNIR}_{i,m} \geq \text{SNIR}_\text{Th}. \end{cases} \end{aligned} \end{gathered} \end{equation} \end{comment} In addition, BS $m$ can decode the signal with $\text{SNIR}_{2,m}$ if \begin{enumerate} \item The signal with $\text{SNIR}_{1,m}$ is successfully decoded, \item user 2 is associated with BS $m$, $u_n^{2,m}=1$, and, \item $\text{SNIR}_{2,m}$ is larger than or equal to the SNIR threshold, i.e., $\Phi(\text{SNIR}_{2,m})=\text{SNIR}_{2,m}$ \end{enumerate} The upper bound on the rate achieved by the $i$-th user in slot $t_n$ given that user $i$ transmits is, \begin{equation} \begin{aligned} R_{i,\text{TX}} = &\mathcal{W}\text{log}_2\Big(1+\Phi(\text{SNIR}_{1,m})u_n^{1,m}\Big)\mathbb{I}_{1,i} +\\ &\mathcal{W}\text{log}_2\Big(1+\Phi(\text{SNIR}_{2,m})u_n^{1,m}u_n^{2,m}e_n^{1,m}\Big)\mathbb{I}_{2,i} \end{aligned} \end{equation} where $\mathcal{W}$ is the transmission bandwidth, $e_n^{1,m} = 1$ if $\Phi(\text{SNIR}_{1,m})=\text{SNIR}_{1,m}$ and $0$ otherwise, $\mathbb{I}_{1,i}=1$ if user $i$ is the IoT device with the highest received SNIR at BS $m$ and $0$ otherwise, and $\mathbb{I}_{2,i}=1$ if user $i$ is the IoT device with the second highest received SNIR at BS $m$ and $0$ otherwise. Notice that either $\mathbb{I}_{1,i}$ or $\mathbb{I}_{2,i}$ can be $1$ in slot $t_n$. It is worth mentioning that the maximum achievable rate by the $i$-th user in slot $t_n$ depends on the transmission probability vector of all IoT devices, $\vect{p} = (p_1, \cdots, p_N)$, and has the general form, \begin{equation} \begin{aligned} \label{form} R_i(\vect{p}) = &A_i \Big( p_i\prod_{j\neq i}(1-p_j) \Big) + \sum_{j\neq i} B^j_i \Big( p_i p_j\prod_{k\neq j,i}(1-p_k) \Big) + \\ &\sum_{j \neq i} \sum_{k \neq i,j} C^{j,k}_i \Big( p_i p_j p_k \prod_{l\neq j,i,k}(1-p_l) \Big) + \cdots \end{aligned} \end{equation} where $A_i$ is a non-negative random variable (R.V.) which represents user $i$'s maximum theoretical rate given that user $i$ is the only user that transmits in slot $t_n$, $B^j_i$ is a non-negative R.V. which represents user $i$'s maximum theoretical rate given that user $i$ and another user $j$ transmit concurrently in $t_n$, and $C^{j,k}_i$ is a non-negative R.V. which represents user $i$'s {maximum theoretical} rate given that user $i$ and two other users, $j,k$, transmit concurrently in $t_n$, and so on and so forth. Notice that $R_i(\vect{p})$ is a weighted sum of $\sum_{k=0}^{N-1} \binom{N-1}{k}= 2^{N-1}$ random variables. In theory, the distributions of $A_i,B^j_i,C^{j,k}_i,\cdots$ or their expectations can be derived by considering NOMA decoding events at the BSs, which {require knowledge} of the network topology and the random channel model. However, this is a very challenging task {in practice because of the massive number of IoT devices and the combinatorial number of possible transmission events}. In this paper, we propose a novel {data-driven formulation that enables the design of efficient algorithms to tune $\vect{p}$ so that the capacity of the network is optimized, without assuming knowledge of the network topology or the channel model.} \section{Problem Formulation} To {maximize NOMA's gain by leveraging the heterogeneity of users' channels, and} enable a capacity-optimal network, we propose a novel formulation to manage random channel access of {individual} IoT devices in a high-density spatially-distributed multi-cell wireless IoT network. Specifically, we formulate the decision problem of tuning $p_i \in (0,1], \forall i \in \mathcal{N}$, as a single stage optimization problem, where the optimization objective, $\mathcal{O}(\vect{p})$, is the log of the geometric mean of users’ expected rates, \begin{equation}\label{eq:system} \begin{aligned} \mathcal{O}(\vect{p}) &= \text{log} \Bigg[ \Big(\prod_{i=1}^N \Bar{R_i}(\vect{p}) \Big)^{1/N} \Bigg]\\ &= \frac{1}{N} \sum_{i=1}^N \text{log}\big(\Bar{R_i}(\vect{p}) \big) \end{aligned} \end{equation} where $\Bar{R_i}(\vect{p}) = \mathbb{E}[R_i(\vect{p})] \in \mathbb{R}_+, \forall i \in \mathcal{N}$. This formulation is motivated by the following merits of the geometric mean, \begin{enumerate} \item By maximizing the log of the geometric mean of users' expected rates, the geometric mean of users' expected rates is maximized as the log function is a monotonic transformation that preserves the locations of maxima. Based on the arithmetic mean (AM) and geometric mean (GM) inequality, the geometric mean of user's expected rates is upper bounded by the arithmetic mean, $$\Big(\prod_{i=1}^N \Bar{R_i}(\vect{p}) \Big)^{1/N} \leq \frac{1}{N} \sum_{i=1}^N \Bar{R_i}(\vect{p}),$$ and the equality holds when all users have the same expected rate, i.e., $\Bar{R_i}(\vect{p})=\Bar{R}(\vect{p}), ~\forall i$. Hence, by maximizing the geometric mean of users' expected rates, a lower bound on the average of users' expected rates is maximized. \item The geometric mean is a non-decreasing monotone function of users' expected rates: by increasing the expected rate of any user, the geometric mean increases. \item The geometric mean is not as sensitive to outliers or extreme values as the arithmetic mean, and it is $0$ if any user has a zero expected rate. Therefore, by maximizing the geometric mean {as a function of the high-dimensional transmission probability vector $\vect{p} \in (0,1]^N$}, we ensure that no user is starved under the optimal transmission probability vector $\vect{p}^*$, i.e., $\Bar{R_i}(\vect{p^*}) > 0, \forall i \in \mathcal{N}$. This is not achieved when the arithmetic mean is optimized {as a function of $\vect{p}$} \footnote{Notice that the AM of expected user rates is a convex combination of the achievable conditional expected rates by $2^N-1$ different transmissions events, and hence the maximum is attained at one of the extreme points.}, because the optimal transmission probability vector $\vect{p}^{AM}$ which maximizes the arithmetic mean grants the channel to users $\mathcal{N}^{AM}$ whose transmissions maximize the NOMA sum-rate performance, i.e., $p_i^{AM}=1, i\in \mathcal{N}^{AM}$, while other users $j \not \in \mathcal{N}^{AM}$ are starved $p_j^{AM}=0$, leading to very poor rate fairness. Our proposed geometric-mean-based formulation on the other hand, natively ensures good rate fairness without imposing explicit fairness constraints, as will be shown in our extensive numerical experiments. \end{enumerate} In addition, the optimization objective in \eqref{eq:system} admits attractive mathematical properties which facilitate the design of efficient centralized and provably convergent distributed optimization algorithms. Given some topology dependent conditions, we prove that $\mathcal{O}(\vect{p})$ is a strictly concave function on a convex set $S^{N}$ for $N\in \{2,3\}$. The proof of a general case of $N > 3$ is mathematically intractable, yet we conjecture that this property holds based on our extensive numerical experiments. In the following section, we show how this property can be used to design an efficient centralized learning-based algorithm to maximize \eqref{eq:system}. In Sec. VI, we propose a distributed learning-based algorithm to maximize \eqref{eq:system} and prove its convergence to a pure Nash equilibrium for the general case of $N$ users. To prove that $\mathcal{O}(\vect{p})$ is a strictly concave function on $S^{N}$ for the case of $N \in \{2,3\}$ users, we first prove that $\bar{R}_i(\vect{p})$ is a strictly log-concave function on a convex set $S^{N}_i$. \begin{definition} A non-negative function $f: \mathbb{R}^n \rightarrow \mathbb{R}_+$ is a strictly logarithmically concave (log-concave) if its domain (dom) is a convex set, and if it satisfies the inequality $$ f(\beta \vect{x}+(1-\beta)\vect{y}) > f(\vect{x})^\beta f(\vect{y})^{1-\beta}$$ $\forall \vect{x},\vect{y} \in$ dom $f$ and $0 < \beta < 1$. If $f$ is a strictly positive function, $f(\vect{x})>0, \forall \vect{x} \in$ dom $f$, then $f$ is a strictly log-concave function if, $$ \text{log}(f(\beta\vect{x}+(1-\beta)\vect{y})) > \beta \text{log}(f(\vect{x})) + (1-\beta)\text{log}(f(\vect{y}))$$ in other words, $\text{log}(f)$ is a strictly concave function. \end{definition} Furthermore, let $\mathbb{H}$ denote the hessian operator, \begin{equation} \mathbb{H}[f(\vect{p})] = \begin{bmatrix} \frac{\partial f }{\partial p_1 \partial p_1} & \cdots & \frac{\partial f}{\partial p_1 \partial p_N}\\ \vdots & \ddots & \vdots \\ \frac{\partial f}{\partial p_N\partial p_1}& \cdots & \frac{\partial f}{\partial p_N \partial p_N} \end{bmatrix}. \end{equation} \begin{theorem} In a multi-cell $p$-persistent slotted Aloha system of $N=2$ users and $M\in \{1,2\}$ BSs with NOMA, where users attempt to transmit to the closest BS with probability $p_i, \forall i \in \{1,2\}$ in each slot, the expected rate of a user $i$, $\bar{R}_i(p_1,p_2), \forall i \in \{1,2\}$, is a strictly log-concave function of $(p_1,p_2)$ on the convex set $S^2_i =\{(p_1,p_2) |~p_1,p_2 \in (0,1]\}, \forall i \in \{1,2\}$. \end{theorem} \begin{proof*} A sufficient condition for $\text{log}\big(\bar{R}_i({\vect{p}})\big), \forall i \in \{1,2\}$, to be strictly concave is that $\mathbb{H}\Big[\text{log}\big(\bar{R}_i(\vect{p})\big)\Big] \prec 0$, i.e., the hessian matrix is negative definite $\forall \vect{p} \in S^N_i$. A necessary and sufficient condition for negative definiteness of the hessian matrix $\forall \vect{p} \in S^N_i$ is $(-1)^k D_k > 0$ for $k = 1, ..., N$ and $\forall \vect{p} \in S^N_i$, where $D_k$ is the determinant of the $k$-th leading principal sub-matrix of the hessian. Without loss of generality (W.L.O.G.), set $i=1$. The log of the expected rate of user $1$ is, \begin{equation} \text{log}\Big(\bar{R}_1(p_1,p_2)\Big) = \text{log}\Big(\mathbb{E}[A_1] p_1(1-p_2) + \mathbb{E}[B^2_1] p_1 p_2\Big), \end{equation} with a hessian matrix, \begin{equation} \mathbb{H}\Big[\text{log}\Big(\bar{R}_1(p_1,p_2)\Big)\Big] = \begin{bmatrix} \frac{-1}{p_1^2} & 0\\ 0 & \frac{-(\mathbb{E}[A_1]-\mathbb{E}[B^2_1])^2}{((1-p_2)\mathbb{E}[A_1]+\mathbb{E}[B^2_1])p_2)^2}. \end{bmatrix} \end{equation} As $(-1)^1D_1 = \frac{1}{p_1^2} > 0$ and $(-1)^2D_2 = \frac{(\mathbb{E}[A_1]-\mathbb{E}[B^2_1])^2}{p_1^2((1-p_2)\mathbb{E}[A_1]+\mathbb{E}[B^2_1])p_2)^2} > 0 $, $\text{log}\Big(\bar{R}_1(p_1,p_2)\Big)$ is strictly concave on $S^2_1$. Similarity, $\text{log}\Big(\bar{R}_2(p_1,p_2)\Big)$ is strictly concave on $S_2^2$. $\blacksquare$ \end{proof*} For $N=2$ case, $\text{log}\Big(\bar{R}_i(p_1,p_2)\Big)$ is strictly log-concave on $S_i^2$, and independent of $\mathbb{E}[A_i], \mathbb{E}[B_i^j]$, i.e., the property is independent of the topology and the achievable expected user rate with and without interference from the other user. For $N=3$ case, $\text{log}\Big(\bar{R}_i(p_1,p_2,p_3)\Big)$ is strictly log-concave over a convex set $S^3_i, \forall i \in \{1,2,3\}$, if $\mathcal{C}_i= \bar{A}_i - \bar{B}_i^j - \bar{B}_i^k + \bar{C}_i^{j,k} > 0, \forall i,j,k \in \{1,2,3\}$ and $i\neq j \neq k$, where $\bar{A}_i=\mathbb{E}[{A}_i], \bar{B}_i^j=\mathbb{E}[{B}_i^j]$, and $\bar{C}_i^{j,k}= \mathbb{E}[{C}_i^{j,k}]$, as formalized below. \begin{theorem} In a multi-cell $p$-persistent slotted Aloha system of $N=3$ users and $M\in\{1,2,3\}$ BSs with NOMA, where users attempt to transmit to the closest BS with probability $p_i, \forall i \in \{1,2,3\}$ in each slot, the expected rate of a user $i$, $\bar{R}_i(p_1,p_2,p_3), \forall i \in \{1,2,3\}$, is a strictly log-concave function of $(p_i,p_j,p_k)$ on the convex set $S_i^3 = \{(p_i,p_j,p_k)|~p_i \in (0,1],~p_j \in (0, \Tilde{p}_j),~p_k \in (0, \Tilde{p}_k)\}$, $\forall i,j,k\in\{1,2,3\}$ and $i \neq j \neq k$, where $\Tilde{p}_j = \frac{\bar{A}_i - \bar{B}_i^k - \sqrt{ \left\lvert \bar{A}_i\bar{C}_i^{j,k} - \bar{B}_i^j\bar{B}_i^k \right\rvert }}{\mathcal{C}_i}$, and $\Tilde{p}_k = \frac{\bar{A}_i - \bar{B}_i^j - \sqrt{\left\lvert\bar{A}_i\bar{C}_i^{j,k} - \bar{B}_i^j\bar{B}_i^k \right\rvert}}{\mathcal{C}_i}$. \end{theorem} \begin{proof*} W.L.O.G., let $i=1,j=2,$ and $k=3$. The log of the expected rate of user $1$ is, \begin{equation} \resizebox{1\hsize}{!}{$ \begin{aligned} \text{log}\Big(\bar{R}_1(&p_1,p_2,p_3)\Big) = \text{log}\Big(\bar{A}_1 p_1(1-p_2)(1-p_3) \\ &+ \bar{B}^2_1 p_1 p_2(1-p_3) + \bar{B}^3_1 p_1 p_3(1-p_2) + \bar{C}_1^{2,3}p_1p_2p_3\Big), \end{aligned} $} \end{equation} with a hessian matrix whose entries are given by $\mathbb{H}_{1,1}= \frac{-1}{p_1^2}$, $\mathbb{H}_{1,2}=0$, $\mathbb{H}_{1,3}=0$, $\mathbb{H}_{2,1}=0$, $\mathbb{H}_{2,2} = \frac{-\big[\bar{A}_1(1-p_3) - \bar{B}^2_1(1-p_3) + (\bar{B}^3_1-\bar{C}^{2,3}_1)p_3 \big]^2}{\big[\mathcal{F}(p_2,p_3) \big]^2}$, $\mathbb{H}_{2,3}= \mathbb{H}_{3,2}= \frac{\bar{A}_1\bar{C}^{2,3}_1 - \bar{B}^2_1\bar{B}^3_1}{\big[\mathcal{F}(p_2,p_3) \big]^2}$, $\mathbb{H}_{3,1}=0$, and $\mathbb{H}_{3,3} = \frac{-\big[\bar{A}_1(1-p_2) - \bar{B}^3_1(1-p_2) + (\bar{B}^2_1-\bar{C}^{2,3}_1)p_2 \big]^2}{\big[\mathcal{F}(p_2,p_3) \big]^2}$, where $\mathcal{F}(p_2,p_3)= \big(\bar{A}_1 (1-p_2)(1-p_3)+ \bar{B}^2_1 p_2(1-p_3) + \bar{B}^3_1 p_3(1-p_2) + \bar{C}_1^{2,3}p_2p_3\big)$. A sufficient condition for $\text{log}\Big(\bar{R}_1(p_1,p_2,p_3)\Big)$ to be strictly concave on $S_1^3$ is that $\mathbb{H} \prec 0, \forall \vect{p}\in S_1^3$, which is true if and only if the leading principle minors satisfy: (C1) $(-1)^1D_1 = -\mathbb{H}_{1,1} > 0$, (C2) $(-1)^2D_2 = \mathbb{H}_{1,1}\mathbb{H}_{2,2} > 0$, and (C3) $(-1)^3D_3 = -\mathbb{H}_{1,1}\big(\mathbb{H}_{2,2}\mathbb{H}_{3,3} - \mathbb{H}_{2,3}^2 \big) > 0$, $\forall \vect{p}\in S_1^3$. It can be observed that (C1) and (C2) are always satisfied, so it remains to investigate (C3). Notice that $-\mathbb{H}_{2,2}>0, -\mathbb{H}_{3,3} >0$, and suppose that (C3-1) $-\mathbb{H}_{2,2} > |\mathbb{H}_{2,3}|$ and (C3-2) $-\mathbb{H}_{3,2} > |\mathbb{H}_{2,3}|$ hold. Taking the log of (C3-1) and (C3-2) and adding the resulting two inequalities we obtain $\text{log}(-\mathbb{H}_{2,2}) + \text{log}(-\mathbb{H}_{3,3}) > 2\text{log}\big(|\mathbb{H}_{2,3}|\big)$, which can be simplified to $\text{log}(\mathbb{H}_{2,2}\mathbb{H}_{3,3}) > \text{log}\big(\mathbb{H}_{2,3}^2\big)$. By exponentiating both sides and rearranging the terms, we have that $\big(\mathbb{H}_{2,2}\mathbb{H}_{3,3}-\mathbb{H}_{2,3}^2 \big)> 0$. Since $-\mathbb{H}_{1,1} > 0$, we can conclude that (C3) is satisfied if the alternate conditions (C3-1) and (C3-2) are both satisfied. Hence, we now show that (C3-1) is satisfied $\forall p_3 \in (0,\Tilde{p}_3)$. Notice that (C3-1) is satisfied if $\big[\bar{A}_1(1-p_3) - \bar{B}^2_1(1-p_3) + (\bar{B}^3_1-\bar{C}^{2,3}_1)p_3 \big]^2 - |\bar{A}_1\bar{C}^{2,3}_1 - \bar{B}^2_1\bar{B}^3_1| = \big(\mathcal{C}_1\big)^2p_3^2 - 2\mathcal{C}_1(\bar{A}_1-\bar{B}_1^2)p_3 + (\bar{A}_1-\bar{B}_1^2)^2 - |\bar{A}_1\bar{C}^{2,3}_1 - \bar{B}^2_1\bar{B}^3_1| > 0 $, which is true $\forall p_3 < \Tilde{p}_3$ as $\Tilde{p}_3$ is the smaller root of the convex quadratic equation in $p_3$. Similarly, it can also be shown that (C3-2) is satisfied $\forall p_2 < \Tilde{p}_2$. $\blacksquare$ \end{proof*} Because the non-negative sum of concave functions is also concave, we can conclude based on the result of theorem 1 that $\mathcal{O}(p_1,p_2)$ is a strictly concave function on the convex set $S^2=S_1^2\cap S_2^2$ when $N=2$. For $N=3$, $\mathcal{O}(p_1,p_2,p_3)$ is a strictly concave function on the convex set $S^3=S_1^3\cap S_2^3\cap S_3^3$ if $\mathcal{C}_i= \bar{A}_i - \bar{B}_i^j - \bar{B}_i^k + \bar{C}_i^{j,k} > 0, \forall i,j,k \in \{1,2,3\}$ and $i\neq j \neq k$. It is worth mentioning that the condition $\mathcal{C}_i > 0$ means that the interference caused by users $j,k$ to transmission of user $i$ is non-negligible and degrades the achievable expected rate of user $i$, such that the surface of $\text{log}\Big(\bar{R}_i(p_i,p_j,p_k)\Big)$ has no flat regions w.r.t. $p_j$ or $p_k$. To further elaborate, consider a simple case of a large-scale fading channel. $\mathcal{C}_i> 0$ becomes ill-conditioned in the case where user $j$, or user $k$, or both, are far away from BS $m$ of user $i$ $(u^{i,m}=1)$, to the extent that their received transmission power at BS $m$ is much smaller than the order of the noise power $n_0$. As a specific example, suppose that $d_{j,m} >> d_{i,m}$ while $d_{k,m}$ is on the same order of $d_{i,m}$. In such case, we have $\bar{B}_i^j \rightarrow \bar{A}_i, \bar{C}_i^{j,k} \rightarrow \bar{B}_i^k$, then $\text{log}\Big(\bar{R}_i(p_i,p_j,p_k)\Big)\rightarrow \text{log}\Big(\bar{A}_i p_i(1-p_k)+ \bar{B}^k_i p_i p_k\Big)$. This implies that, i) $\frac{\partial }{\partial p_j} \text{log}\Big(\bar{R}_i(p_i,p_j,p_k)\Big) = 0$, i.e., user $j$'s transmission strategy has no impact on user $i$, and $p_j$ can be set to any arbitrary value $p_j \in (0,1]$ without impacting $\text{log}\Big(\bar{R}_i(p_i,p_j,p_k)\Big)$; ii) for any $p_j \in (0,1]$, $\text{log}\Big(\bar{R}_i(p_i,p_j,p_k)\Big)$ is a strictly concave function of $p_i,p_k$ on the convex set $S^2_i$ based on the result of theorem 1; and iii) $\mathcal{O}(p_1,p_2,p_3)$ is a strictly concave function on the convex set $S^3=\Tilde{S}_i\cap S_j^3\cap S_k^3=S_j^3\cap S_k^3$, if $\mathcal{C}_j > 0$ and $\mathcal{C}_k > 0$, where $\Tilde{S}_i =\{(p_1,p_2,p_3) |~p_1,p_2,p_3 \in (0,1]\}$. For a general case of $N > 3$ users, we conjecture that $\mathcal{O}(\vect{p})$ is a concave function over a convex set $S^N$, such that convex programming techniques can be applied to find the globally optimal transmission probability vector $\vect{p}^*$, although $\mathcal{O}(\vect{p})$ is not readily available in a closed-form. To obtain a closed form expression of $\mathcal{O}(\vect{p})$, the expectations of $N*\sum_{k=0}^{N-1} \binom{N-1}{k}= N*2^{N-1}$ R.V.s should be derived by considering each of $2^N-1$ possible transmission events, and evaluating the expectations based on network topology and the random channel model. This is not practically feasible for high-density networks with a large $N$. Estimating these expectations via Monte Carlo simulations can also be computationally prohibitive. Machine learning on the other hand, provides a data driven approach for system design, optimization, and control, and can be exploited to maximize \eqref{eq:system}. In the following section, a centralized learning-based optimization algorithm is proposed to optimize \eqref{eq:system}. \section{Centralized Learning-Based Optimization Algorithm} In this section, we design an active-learning-based algorithm in which a compatible surrogate model for $\mathcal{O}(\vect{p})$ is sequentially learned and optimized based on online-sampled training data, to find the optimal transmission probability vector $\vect{p}^*$. Notice that for a given transmission probability vector $\vect{p}_k$, $\mathcal{O}(\vect{p}_k)$ can be evaluated by estimating the expected user rates $\bar{R}_i(\vect{p}_k), \forall i \in \mathcal{N}$, over an observation window. Therefore, an initial data set of $H_{t=0}$ samples, $\mathcal{D}_0 =\{ \vect{p}_k,{\mathcal{O}}(\vect{p}_k) \}_{k=1}^{H_0}$, can be generated by independently and uniformly sampling $\vect{p}_k, \forall k \in [H_0]$ from $(0,1]^N$, and estimating the objective function values ${\mathcal{O}}(\vect{p}_k)$ at these samples. Based on $\mathcal{D}_0$, a compatible surrogate model for $\mathcal{O}(\vect{p})$ is learned in a system identification stage. Next, in the system control stage, the learned surrogate model is used to sample new data points $\vect{p}_k, \forall k \in [H_t]$, in a way to strike a trade-off between model exploration and model exploitation. The system identification and system control stages are iterated until the optimal transmission probability vector $\vect{p}^*$ is found, or the total sampling budget $H = \sum_{t=0} H_t$ is exhausted. In the following sub-sections, the system identification and system control stages are discussed in detail, and the overall active-learning-based optimization algorithm is presented. \subsection{System Identification} In model-based system identification, $\mathcal{O}(\vect{p})$ is modeled by $\mathcal{O}(\vect{p}) = \hat{\mathcal{O}}_\mu(\vect{p};\vect{\theta}) + \varepsilon(\vect{p};\vect{\theta})$, where $\hat{\mathcal{O}}_\mu(\vect{p};\vect{\theta})$ is a parameterized model which maps the transmission probability vector $\vect{p}$ and the set of model parameters $\vect{\theta}$ to the expected value of $\mathcal{O}(\vect{p})$, and $\varepsilon(\vect{p};\vect{\theta}) \sim \mathcal{N}\big(0,\sigma^2(\vect{p};\vect{\theta})\big)$ is a gaussian random variable with zero mean and variance $\sigma^2(\vect{p};\vect{\theta})$ to account for the heteroscedastic estimation errors in the observations. The optimal vector of model parameters $\vect{\theta}^*$ is estimated based on the current dataset $\mathcal{D}_T = \cup_{t=0}^T~ \mathcal{D}_t$ using Maximum Likelihood estimation, \begin{equation} \label{eq:MLest} \begin{aligned} \vect{\theta}^* &=\underset{\vect{\theta}}{\text{argmax}}~\text{log}\Big(\text{Pr}\big( {\mathcal{O}}(\vect{p}) \big| \vect{p} ; \vect{\theta}, \mathcal{D}_T \big) \Big)\\ & =\underset{\vect{\theta}}{\text{argmax}}~\text{log}\Big(\prod_{k} \text{Pr}\big( {\mathcal{O}}(\vect{p_k}) \big| \vect{p}_k ; \vect{\theta} \big) \Big)\\ & =\underset{\vect{\theta}}{\text{argmax}}~ \sum_{k} \text{log}\Big(\text{Pr}\big( {\mathcal{O}}(\vect{p_k}) \big| \vect{p}_k ; \vect{\theta} \big) \Big) \\ & =\underset{\vect{\theta}}{\text{argmin}}~ \frac{1}{2} \sum_{k} \Big[\frac{ \mathcal{O}(\vect{p}_k) - \hat{\mathcal{O}}_\mu(\vect{p}_k;\vect{\theta}) }{\sigma(\vect{p}_k;\vect{\theta})}\Big]^2 + \\ &~~~~~~~~~~~~~~~~~~~~~~~~~\frac{1}{2} \sum_{k} \text{log}\big(\sigma^2(\vect{p}_k;\vect{\theta}) \big), \end{aligned} \end{equation} i.e., the optimal surrogate model for $\mathcal{O}(\vect{p})$ can be learned through regression by minimizing the negative of the log-likelihood function. Notice that minimizing the negative log-likelihood criterion jointly minimizes the sum of squared prediction errors between the sample value $\mathcal{O}(\vect{p}_k)$ and the mean predicted value $\hat{\mathcal{O}}_\mu(\vect{p}_k;\vect{\theta})$ of the model, as well the variance of the predicted value $\sigma^2(\vect{p}_k;\vect{\theta})$ in the current dataset $\mathcal{D}_T$ \cite{ljung1999system}. The results of theorem 1, theorem 2, and our conjecture that $\mathcal{O}(\vect{p})$ is a strictly concave function on a convex set $S^N$ provide a key insight for efficient system identification as we can restrict the space of compatible models for $\mathcal{O}(\vect{p})$ to the class of concave functions. By learning an accurate concave model $\hat{\mathcal{O}}_\mu(\vect{p};\vect{\theta}^*)$, the globally optimal transmission probability vector $\vect{p}^*$ can be found using common convex optimization techniques, i.e., $\vect{p}^* = \underset{\vect{p}}{\text{argmax}}~\hat{\mathcal{O}}_\mu(\vect{p};\vect{\theta}^*)$. Deep neural networks (DNNs) are one of the most commonly adopted models because they are universal function approximators in the sense that they can approximate any continuous function of $N$ variables on a compact domain arbitrarily well \cite{poggio2019theoretical,hornik_approximation}. In DNNs, model parameters $\vect{\theta}$ represent the set of neuron weights and biases. While DNNs have been used for system identification to model high-dimensional systems with nonlinear maps \cite{narendra_approximation, jag_discrete}, their adoption can be challenging for optimal system control because DNNs are typically non-convex with respect to their inputs. To overcome this challenge, we construct DNNs which are convex with respect to their inputs, referred to as Input Convex Neural Networks (ICNNs), by leveraging two facts about the composition of convex functions \cite{amos2017input,chen2018optimal}, (i) a non-negative weighted sum of convex functions is itself convex, and (ii) composition of a convex function $g(x)$ and convex non-decreasing function $h(x)$ produces a convex function $h(g(x))$. Thus, by restricting the weights in the DNN to be non-negative and by choosing a convex non-decreasing activation function, an ICNN can be designed. In this work, the exponential linear activation function is adopted, \begin{equation} \phi(x) = \begin{cases} x, ~~~~~~~~~~x \geq 0, \\ \gamma(e^x - 1), x \leq 0, \end{cases} \end{equation} where $\gamma$ is a hyper-parameter that controls the value to which the activation function saturates for negative inputs. Figure \ref{ICNN} illustrates a general architecture of a feed-forward ICNN. Specifically, this model defines a deep neural network over the input $\vect{p}$ using the architecture for layers $k=0,1, \cdots, K-1$, \begin{equation} \begin{aligned} &\vect{z}_{k+1} = \phi\Big(\vect{W}_k^{(\vect{z})}\vect{z}_k + \vect{W}_k^{(\vect{p})} \vect{p} + \vect{b}_k \Big), \\ &\hat{\mathcal{O}}_\mu(\vect{p}; \vect{\theta}) = -\Big( \vect{W}_{K-1}^{(\vect{z})}\vect{z}_{K-1} + \vect{W}_{K-1}^{(\vect{p})} \vect{p} + \vect{b}_{K-1} \Big), \\ &\sigma^2(\vect{p};\vect{\theta}) = \text{log}\Big(1+\gamma+\phi \Big(\vect{W}^{(\sigma)}\vect{z}_{K-1} + \vect{b}_{\sigma}\Big) \Big), \end{aligned} \end{equation} where $\vect{W}_k^{(\vect{z})} \geq 0$ is a matrix of non-negative neuron weights for the $k$-th layer (with $\vect{z}_0,\vect{W}_0^{(\vect{z})}=\vect{0}$), $\vect{W}_k^{(\vect{p})}$ is a matrix of neuron weights for the $k$-the direct pass-through layer $k$, $\vect{b}_k$ is a column vector of neuron biases, and $\vect{\theta} = \big\{\vect{W}_{1:K-1}^{(\vect{z})}, \vect{W}_{0:K-1}^{(\vect{p})}, \vect{b}_{0:K-1},\vect{W}^{(\sigma)}, \vect{b}_\sigma \big\}$ is the set of ICNN model parameters. Notice that the ICNN network outputs two values in the final layer, corresponding to the predicted mean $\hat{\mathcal{O}}_\mu(\vect{p}; \vect{\theta})$ and variance $\sigma^2(\vect{p};\vect{\theta}) \geq 0$. Compared with a standard feed-forward DNN, an ICNN has the notable addition of the direct pass-through layers $\vect{W}_{0:K-1}^{(\vect{p})}$ which directly connect the input $\vect{p}$ to the hidden units in deep layers. These layers are necessary in ICNNs because the non-negativity constraints on $\vect{W}_{1:K-1}^{(\vect{z})}$ restricts previous hidden units from being mapped to subsequent hidden units with the identity mapping, and so explicitly including these direct pass-through layers enables the model to represent identity mappings. Notice that $\vect{W}_{0:K-1}^{(\vect{p})}$ can take any value because $\vect{W}_{k}^{(\vect{p})} \vect{p}$ are just linear functions with respect to $\vect{p}$ and hence convex. The output neuron corresponding to the predicted mean $\hat{\mathcal{O}}_\mu(\vect{p}; \vect{\theta})$ is multiplied by a negative sign to make the ICNN-based model a concave function of $\vect{p}$. Because the variance $\sigma^2(\vect{p};\vect{\theta})$ can be a non-convex function of $\vect{p}$, an additional layer is applied to $\vect{z}_{K-1}$ in which $\vect{W}^{(\sigma)}$ can take any value, such that $\sigma^2(\vect{p};\vect{\theta})$ can model any non-convex function. By learning $\sigma^2(\vect{p};\vect{\theta})$, the ICNN-based model captures aleatoric uncertainty, which is the noise inherent in the observations with respect to the inputs $\vect{p}$ \cite{kendall2017uncertainties}. To capture epistemic uncertainty, which is uncertainty in the model parameters due to scarcity of the data in some regions, we train an ensemble of ICNN models, where each ICNN model is trained on the current data set $\mathcal{D}_T$ with random initialization of the ICNN parameters \cite{lakshminarayanan2017simple}. The ensemble is treated as a uniformly-weighted Gaussian mixture model with mean and variance of the mixture given by, \begin{equation} \resizebox{1\hsize}{!}{$ \begin{aligned} &\hat{\mathcal{O}}_{\mu_*}(\vect{p}) = \frac{1}{E} \sum_{m=1}^E \hat{\mathcal{O}}_{\mu_m}(\vect{p};\vect{\theta}_m), \\ &\sigma^2_*(\vect{p}) = \frac{1}{E}\sum_{m=1}^E \big(\sigma^2_m(\vect{p};\vect{\theta}_m) + (\hat{\mathcal{O}}_{\mu_m}(\vect{p};\vect{\theta}_m))^2\big) - (\hat{\mathcal{O}}_{\mu_*}(\vect{p}))^2, \end{aligned} $} \end{equation} where $E$ is the number of models in the ensemble, and {$\hat{\mathcal{O}}_{\mu_m}(\vect{p};\vect{\theta}_m)$ and $\sigma^2_m(\vect{p};\vect{\theta}_m)$ are the predicted mean and variance of the individual models in the ensemble, respectively.} It is worth mentioning that epistemic uncertainty can be reduced by collecting more data points $\{\vect{p}_k,{\mathcal{O}}(\vect{p}_k) \}_{k}$ in regions where $\sigma^2_*(\vect{p})$ is high. \begin{figure} \centering \includegraphics[width=1\linewidth]{Figs/ICNN.pdf} \caption{Input Convex (Concave) Feed-Forward Neural Network } \label{ICNN} \vspace{-5mm} \end{figure} \subsection{System Control} By capturing both aleatoric and epistemic uncertainties, we can design an asymptotically competitive model-based learning algorithm in which the surrogate model is sequentially improved and optimized by sampling new data points in a way to strike a balance between model exploitation and model exploration. Specifically, in model exploitation, a new data point $\{p_k,\mathcal{O}(\vect{p_k})\}$, where $\vect{p}_k = \underset{\vect{p}}{\text{argmax}}~\hat{\mathcal{O}}_{\mu_*}(\vect{p})$, is sampled based on the current surrogate model in an attempt to maximize the true $\mathcal{O}(\vect{p})$. Notice that $\vect{p}_k$ can be found using common convex optimization techniques since $\hat{\mathcal{O}}_{\mu_*}(\vect{p})$ is a convex function of $\vect{p}$ by design. In model exploration, a new set of new data points $\mathcal{D}_t=\{p_k,\mathcal{O}(\vect{p_k})\}_{k=1}^{H_t}$ are sampled to reduce the predictive uncertainty of the learned surrogate model by $\vect{p}_k = \underset{\vect{p}}{\text{argmax}}~\sigma^2_*(\vect{p})$. Because $\sigma^2_*(\vect{p})$ is a non-convex function, a local derivative-free optimizer such as Nelder-Mead \cite{nelder1965simplex} can be started from a set of $H_t$ points which are independently and uniformly sampled from $\vect{p}_k \in (0,1]^N$, in order to find $H_t$ local maxima of $\sigma^2_*(\vect{p})$. Next, $\mathcal{O}(\vect{p_k})$ is estimated at the set of local maxima of $\sigma^2_*(\vect{p})$ to generate the new data set $\mathcal{D}_t$. By augmenting $\mathcal{D}_t$ to the existing data set and re-training the ICNN-based models, the predictive uncertainty of the surrogate model is improved. Model exploitation and model exploration can be combined in one-step by sampling points $\vect{p}_k$ which maximize an upper confidence bound (UCB), $\vect{p}_k = \underset{\vect{p}}{\text{argmax}}~\hat{\mathcal{O}}_{\mu_*}(\vect{p})+\beta \sigma_*(\vect{p})$, where $\beta \geq 0$ is a non-negative parameter to make a trade-off between model exploration and model exploitation. Therefore, by successively sampling new data points to maximize the UCB of the surrogate model (system control), and updating the surrogate model based on the new samples (system identification), the optimal transmission probability vector $\vect{p}^*$ which maximizes \eqref{eq:system} can be found asymptotically. In practice, system control and system identification stages are iterated until the total sampling budget $H = \sum_{t=0} H_t$ is exhausted, and $\vect{p}_k = \underset{k\in [H]}{\text{argmax}}~\mathcal{O}(\vect{p}_k)$ is considered to be a (sub)optimal solution. \subsection{The centralized learning algorithm} To execute the proposed centralized learning-based optimization algorithm, a back-end central controller successively constructs the data set $\mathcal{D}_T$ and iterates through the system control and system identification stages as shown in Algorithm 1, until the optimal transmission probability vector $\vect{p}^*$ is found or the sampling budget is exhausted. By exploiting the structure of the optimization problem and trading-off model exploration and model exploitation, Algorithm 1 offers an asymptotically efficient data-driven solution for optimizing the mathematically intractable objective of \eqref{eq:system}. Yet it may not scale well with the number of IoT devices due to the curse of dimensionality in learning high-dimensional models based on a finite number of samples To overcome these challenges, we further study the design of a scalable distributed learning-based optimization algorithm in the following section. \begin{algorithm} \label{Alg1} \SetKwInOut{Input}{Input} \SetKwInOut{Output}{Output} \Input{ Initial data set $\mathcal{D}_0 =\{ \vect{p}_k,{\mathcal{O}}(\vect{p}_k) \}_{k=1}^{H_0}$\\ Sampling budget vector $(H_1,\cdots,H_T)$ \\ Exploration parameter schedule $(\beta_1,\cdots,\beta_T)$ } \Output{(Sub)optimal transmission probability vector $\vect{p}^*$ } Set $\mathcal{D} = \mathcal{D}_0$\\ \For{$t=1,2 \cdots, T$} { Train an ensemble of ICNN-based models based on $\mathcal{D}$ using \eqref{eq:MLest}\\ Find $H_t$ transmission probability vectors $\vect{p}_k = \underset{\vect{p}}{\text{argmax}}~\hat{\mathcal{O}}_{\mu_*}(\vect{p})+\beta_t \sigma_*(\vect{p}), k\in[H_t]$, by starting a local optimizer from $H_t$ random points\\ Estimate \eqref{eq:system} at the new set of data points to generate $\mathcal{D}_t=\{p_k,\mathcal{O}(\vect{p_k})\}_{k=1}^{H_t}$\\ Augment new data set to training data set $\mathcal{D}= \{\mathcal{D},\mathcal{D}_{t}\}$\\ } $\vect{p}^* = \underset{k\in \mathcal{D}}{\text{argmax}}~ \mathcal{O}(\vect{p}_k)$ \caption{Centralized Learning-Based Network Optimization} \end{algorithm} \section{Distributed Learning-Based Optimization Algorithm} To design a scalable distributed learning-based optimization algorithm in which each individual IoT device adapts it transmission probability $p_i, \forall i \in \mathcal{N}$, we first reformulate the problem of optimizing \eqref{eq:system} as an $N$-player strategic game $\mathcal{G}=\langle \mathcal{N},\mathcal{A},\mathcal{U} \rangle$ which consists of, \begin{enumerate} \item \textbf{Players}: the set of players is the set of IoT devices $\mathcal{N}$. Each IoT device in the game $\mathcal{G}$ is a rational decision maker who makes decisions autonomously. \item \textbf{Action space}: the action space for each player $i$ is the compact convex set of transmission probabilities $\mathcal{A}_i = \{p_i |~ p_i \in [\varepsilon_p,1]\}$, where $\varepsilon_p$ is a small positive infinitesimal quantity to make the action space compact. The strategy profile $\mathcal{A}= \mathcal{A}_1 \times \cdots \mathcal{A_N}$ is a set of strategies for all players which fully specifies all actions in the game. \item \textbf{Utility functions}: a utility function of player $i$ is a function of the strategy profile of all players $\mathcal{U}_i : \mathcal{A} \rightarrow \mathbb{R}$. Every player $i$ selects an action $p_i$ considering the possible actions of all other players $\vect{p}_{-i} = (p_1,\cdots, p_{i-1}, p_{i+1}, \cdots, p_{N})$ to maximize its own utility $\mathcal{U}_i(p_i,\vect{p}_{-i})$. Let $\mathcal{U}$ be the utility profile of all players, $\mathcal{U}=\big(\mathcal{U}_1,\cdots, \mathcal{U}_N \big)$. In $\mathcal{G}$, all players have the same utility function $\mathcal{U}_i(\vect{p}) = \mathcal{O}(\vect{p}), \forall i \in \mathcal{N}$, as given by \eqref{eq:system}. \end{enumerate} A Nash equilibrium solution is the canonical solution for strategic games, which ensures a stable state of the game. Specifically, in a strategic game $\langle \mathcal{N},\mathcal{A},\mathcal{U} \rangle$ of $N$-players, the set of strategy profiles $\vect{p}^* \in \mathcal{A}$ constitute a set of Nash equilibria if $\forall i, p_i \in \mathcal{A}_i$, $\mathcal{U}_i(p_i^*, \vect{p}_{-i}^*) \geq \mathcal{U}_i(p_i, \vect{p}_{-i}^*)$, \begin{comment} \begin{equation} \mathcal{U}_i(p_i^*, \vect{p}_{-i}^*) \geq \mathcal{U}_i(p_i, \vect{p}_{-i}^*) \end{equation} \end{comment} i.e., a Nash equilibrium solution is an action profile $\vect{p}^* \in \mathcal{A}$ of all players with the property that no player $i$ can improve its utility $\mathcal{U}_i(\vect{p}^*)$ by unilaterally choosing an action $p_i$ different from $p_i^*$ given that every other player $j$ adheres to $p_j^* \in \mathcal{A}_j, \forall j \in \mathcal{N}\setminus\{ i\}$. \begin{definition} A game in which the strategy sets are compact convex sets and the utility functions $\mathcal{U}_i: \mathcal{A}\rightarrow \mathbb{R}, \forall i \in \mathcal{N}$ are continuously differentiable is a continuous potential game if there exists continuously differentiable function $\mathcal{P}: \mathcal{A}\rightarrow \mathbb{R}$ such that \cite{monderer1996potential}, \begin{comment} \begin{equation} P(p_i, \vect{p}_{-i}) - P(p_i^\prime, \vect{p}_{-i}) = \mathcal{U}_i(p_i,\vect{p}_{-i}) - \mathcal{U}_i(p_i^\prime,\vect{p}_{-i}), \forall i, p_i, p_i^\prime \end{equation} \end{comment} \begin{equation} \frac{\partial \mathcal{P}(p_i, \vect{p}_{-i})}{\partial p_i} = \frac{\partial \mathcal{U}_i(p_i,\vect{p}_{-i})}{\partial p_i}, \forall i \in \mathcal{N} \end{equation} \begin{comment} Furthermore, a potential game is a best-response potential game if $\forall i \in \mathcal{N}$ and $\forall \vect{p}_{-i} \in \mathcal{A}_{-i}$, $\mathcal{A}_{-i} = \prod_{j\neq i} \mathcal{A}_j$ \cite{voorneveld2000best,norde1998determinateness,voorneveld1999potential}, \begin{equation} \begin{aligned} \underset{p_i}{\text{argmax}}~ \mathcal{U}_i(p_i, \vect{p}_{-i}) = \underset{p_i}{\text{argmax}}~ \mathcal{P}(p_i, \vect{p}_{-i}) \end{aligned} \end{equation} \end{comment} \end{definition} \begin{proposition} The strategic game $\mathcal{G}$ is a continuous potential game. \end{proposition} \begin{proof*} Notice that the strategy profile of all players in $\mathcal{G}$ is the compact convex set $\mathcal{A}$. Because all players have the same continuous utility function $\mathcal{U}_i(p_i, \vect{p}_{-i}) = \mathcal{O}(p_i,\vect{p}_{-i}), \forall i \in \mathcal{N}$, $\mathcal{P}(\vect{p})=\mathcal{O}(\vect{p})$ is a potential function for the game $\mathcal{G}$. Hence, $\mathcal{G}$ is a continuous potential game. $\blacksquare$ \end{proof*} Continuous potential games with compact strategy sets have several useful properties. First, they possess at least one pure strategy Nash equilibrium \cite{monderer1996potential}. Second, every Nash equilibrium is a stationary point of $\mathcal{P}$, which includes the set of local maxima and saddle points of $\mathcal{P}$. If $\mathcal{P}$ is concave and bounded, then every pure Nash equilibrium is a maximum point of $\mathcal{P}$ which coincides with $\underset{\vect{p}}{\text{argmax}}~\mathcal{P}(\vect{p})$ \cite{neyman1997correlated}. Moreover, the pure Nash equilibrium is unique if $\mathcal{P}$ is strictly concave and bounded. Based on these properties and the results of theorems 1 and 2, we can conclude that $\mathcal{P}(\vect{p}) = \mathcal{O}(\vect{p})$ has a unique pure Nash equilibria which is the global maximizer of $\mathcal{P}(\vect{p})$ for the case of $N=2,3$ users, respectively. For a general case of $N>3$, we can conclude that $\mathcal{P}(\vect{p})$ has at least one pure Nash equilibrium. The existence of pure Nash equilibria in the strategic game $\mathcal{G}$ is important because it allows for the possibility to design a distributed algorithm which converges to a stable state when IoT devices unilaterally adapt their transmission probabilities to maximize their own utilities. Because a pure Nash equilibrium $\vect{p}^* \in \mathcal{A}$ is by definition a fixed point of the joint best-response (BR) mapping in which each player plays its best response $\mathcal{B}_i(\vect{p}_{-i}^*)$ to the actions of other players $\vect{p}_{-i}^*$, \begin{equation} p_i^* \in \mathcal{B}_i(\vect{p}_{-i}^*) = \underset{p_i\in[\varepsilon_p,1]}{\text{argmax}}~\mathcal{P}(p_i, \vect{p}_{-i}^*),~~\forall i \in \mathcal{N} , \end{equation} it is natural to design algorithms based on BR mappings so that players adaptively learn to play a pure Nash equilibrium strategy over time. Notice that $\mathcal{B}_i(\vect{p}_{-i})$ is a set-valued function because there may be many local maxima. While BR dynamics offer a simple approach to find a pure Nash equilibrium, in practice however, BR dynamics may cycle and never terminate \cite{voorneveld1999potential,wright2015coordinate}. Furthermore, BR dynamics require that every player either have an analytic form for $\mathcal{B}_i(\vect{p}_{-i})$ or be able to optimize $\mathcal{P}(p_i, \vect{p}_{-i})$ given the current strategy profile of all other players $\vect{p}_{-i}$. In the case of $\mathcal{G}$, neither $\mathcal{B}_i(\vect{p}_{-i})$ nor $\mathcal{P}(p_i, \vect{p}_{-i})$ is available in closed-form, and collecting the strategy profile of all other players $\vect{p}_{-i}$ will incur significant communication overhead for the algorithm. To tackle these challenges, we study the design of a distributed learning-based algorithm in which each player plays a best response strategy to an observable aggregate quantity that is a function of other players' strategies $\mathcal{J}_i(\vect{p}_{-i})$, therefore reducing the communication overhead. While economists have studied the design of action aggregators for simple utility functions and analyzed the convergence of BR learning to Nash equilibria \cite{dubey2006strategic,jensen2010aggregative,acemoglu2013aggregate}, the design of an action aggregator remains a game-specific challenge in general, in the sense that an action aggregator should fully capture the game structure and enable a player to play a convergent BR strategy. In the following sub-section, we design a learning-based BR algorithm with action aggregation for $\mathcal{G}$, and prove its convergence to a Nash equilibrium. \subsection{Best Response Dynamics with Action Aggregation} To design a suitable action aggregator $\mathcal{J}_i(\vect{p}_{-i})$ for $\mathcal{G}$, we first analyze the structure of the potential function $\mathcal{P}$ of the game. Recall that $\bar{R}_i(\vect{p})=\bar{R}_i(p_i, \vect{p}_{-i})$ is the expected rate of user $i$ given its transmission probability $p_i$ and the transmission probability vector of all other players $\vect{p}_{-i}$. Note that $\bar{R}_i(p_i, \vect{p}_{-i})=p_iV_i(\vect{p}_{-i})$, where $V_i(\vect{p}_{-i})$ is the conditional expected rate of user $i$ given that it transmits. To expose the impacts of user $j$ on the achievable expected rate by user $i$, $ \bar{R}_i(p_i,\vect{p}_{-i})$ can also be written as, \begin{equation} \label{eq:ji_impact} \bar{R}_i(\vect{p}) = p_j V_i(\vect{p}_{-j}) + (1-p_j)U_i( \vect{p}_{-j}) \end{equation} where $\vect{p}_{-j} = (p_1,\cdots, p_{j-1}, p_{j+1}, \cdots, p_{N})$ is the transmission probability vector of all users except of user $j$'s, $V_i(\vect{p}_{-j})$ is the conditional expected rate of user $i$ given that user $j$ transmits, and $U_i(\vect{p}_{-j})$ is the conditional expected rate of user $i$ given that user $j$ does not transmit. Notice that $U_i(\vect{p}_{-j}) > V_i(\vect{p}_{-j})$ because transmissions of user $j$ cause interference to user $i$'s transmissions and therefore degrade user $i$'s expected rate. W.L.O.G., set $i=1$ and consider the potential function $\mathcal{P}$ of the game $\mathcal{G}$ from the perspective of user $1$ given a fixed strategy profile of all other users $\vect{p}_{-1}$. By substituting \eqref{eq:ji_impact} with $i=k,\forall k\neq 1$, in $\eqref{eq:system}$, \begin{equation} \label{eq:p_from_i} \resizebox{1\hsize}{!}{$ \begin{aligned} &\mathcal{P}(p_1,\vect{p}_{-1}) = \frac{1}{N}\text{log}(\bar{R}_1(p_1, \vect{p}_{-1})) + \frac{1}{N}\sum_{k\neq 1} \text{log}(\bar{R}_k(p_1, \vect{p}_{-1})) \\ &=\frac{1}{N} \text{log}(p_1 V_1(\vect{p}_{-1})) + \frac{1}{N} \sum_{k\neq 1} \text{log}(p_1 V_k(\vect{p}_{-1}) + (1-p_1)U_k( \vect{p}_{-1})). \end{aligned}$} \end{equation} To design a BR strategy in which user $1$ adapts its transmission probability based on the action aggregator $\mathcal{J}_1(\vect{p}_{-1})$, the second summand in \eqref{eq:p_from_i} is approximated by the $K$-th order Taylor series expansion of the log function, \begin{equation} \label{eq:approx} \resizebox{1\hsize}{!}{$ \begin{aligned} & \sum_{k\neq 1} \text{log}(p_1 V_k(\vect{p}_{-1}) + (1-p_1)U_k( \vect{p}_{-1})) \\ &= \sum_{k\neq 1} \text{log}\Big(U_k( \vect{p}_{-1})\frac{U_k( \vect{p}_{-1})+p_1( V_k(\vect{p}_{-1}) -U_k( \vect{p}_{-1}))}{U_k( \vect{p}_{-1})} \Big) \\ &= \sum_{k\neq 1} \text{log}\big(U_k( \vect{p}_{-1}) \big) + \text{log}\Big(1+ p_1\frac{ V_k(\vect{p}_{-1}) -U_k( \vect{p}_{-1})}{U_k( \vect{p}_{-1})} \Big) \\ &\approx \sum_{k\neq 1} \Big[ \text{log}\big(U_k( \vect{p}_{-1}) \big) - \sum_{n=1}^K \frac{p_1^n \big(Q_k(\vect{p}_{-1})\big)^n}{n} \Big] \end{aligned} $} \end{equation} where $ Q_k(\vect{p}_{-1})= \frac{U_k(\vect{p}_{-1}) - V_k(\vect{p}_{-1})}{U_k(\vect{p}_{-1})} > 0$. Based on \eqref{eq:p_from_i} and \eqref{eq:approx}, the first and second partial derivatives of $\mathcal{P}(p_1,\vect{p}_{-1})$ with respect to $p_1$ for a given $\vect{p}_{-1}$ are \begin{equation} \resizebox{1\hsize}{!}{$ \begin{aligned} \frac{\partial \mathcal{P}(p_1,\vect{p}_{-1})}{\partial p_1}& \approx \frac{1}{N}\Bigg[ \frac{1}{p_1} - \sum_{k\neq 1} \Big[ \sum_{n=1}^K p_1^{n-1}{\big(Q_k(\vect{p}_{-1})\big)^n} \Big] \Bigg] \end{aligned}$} \end{equation} and \begin{equation} \resizebox{1\hsize}{!}{$ \begin{aligned} \frac{\partial \mathcal{P}^2(p_1,\vect{p}_{-1})}{\partial p_1^2}& \approx \frac{1}{N}\Bigg[ \frac{-1}{p_1^2} - \sum_{k\neq 1} \Big[ \sum_{n=2}^K (n-1)p_1^{n-2}{\big(Q_k(\vect{p}_{-1})\big)^n} \Big] \Bigg], \end{aligned} $} \end{equation} respectively. Because $\frac{\partial \mathcal{P}^2(p_1,\vect{p}_{-1})}{\partial p_1^2} <0, \forall p_1 \in [\varepsilon_p,1]$, $\mathcal{P}(p_1,\vect{p}_{-1})$ is a strictly concave function of $p_1$, and there exists at most one strict local maximum $p_1^* \in [\varepsilon_p,1]$, which is also the unique strict global maximum of $\mathcal{P}(p_1,\vect{p}_{-1})$ with respect to $p_1$. If $p_1^*$ exists, it satisfies the first-order optimality condition $\frac{\partial \mathcal{P}(p_1,\vect{p}_{-1})}{\partial p_1}=0$ given by the polynomial equation, \begin{equation} \label{eq:root} \begin{aligned} p_1 &= \frac{1}{\sum_{k\neq 1} \Big[ \sum_{n=1}^K p_1^{n-1}{\big(Q_k(\vect{p}_{-1})\big)^n} \Big]}\\ & = \frac{1}{ \langle \mathcal{J}_1(\vect{p}_{-1}), (1, p_1,\cdots, p_1^{K-1} ) \rangle }\\ &= \mathcal{F}_1(p_1) \end{aligned} \end{equation} where the action aggregator is the vector $\mathcal{J}_1(\vect{p}_{-1})$, \begin{equation} \begin{aligned} &\mathcal{J}_1(\vect{p}_{-1}) = \\ &\Big(\sum_{k\neq 1}Q_k(\vect{p}_{-1}), \sum_{k\neq 1} \big(Q_k(\vect{p}_{-1}) \big)^2,\cdots, \sum_{k\neq 1} \big(Q_k(\vect{p}_{-1}) \big)^K\Big) \end{aligned} \end{equation} and $\langle \mathcal{J}_1(\vect{p}_{-1}), (1, p_1,\cdots, p_1^{K-1}) \rangle$ denotes the inner product of $\mathcal{J}_1(\vect{p}_{-1})$ with the vector $(1, p_1 ,\cdots, p_1^{K-1})$. The dependence of $\mathcal{F}_1(p_1)$ on a fixed $\vect{p}_{-1} \in \mathcal{A}_{-1}$ has been suppressed for notational convenience. Notice that $\sum_{k\neq 1} \Big[ \sum_{n=1}^K p_1^{n-1}{\big(Q_k(\vect{p}_{-1})\big)^n} \Big] < K(N-1) $, hence $p_1=\mathcal{F}_1(p_1) > \frac{1}{K(N-1)} \geq \varepsilon_p$. The BR strategy of user $1$ to the actions of other players $\vect{p}_{-1}$ is therefore the unique root $p_1^* \in [\varepsilon_p,1]$ of \eqref{eq:root}, or otherwise $p_1^*=1$ in the case when user 1's transmissions are outside the interference range of other users in the network, \begin{equation} \label{p:fp} \begin{aligned} \Tilde{\mathcal{B}}_1(\vect{p}_{-1}) =\text{min}\big\{\mathcal{F}_1(p_1),1\big\} \end{aligned} \end{equation} To determine the single-valued BR strategy $\Tilde{\mathcal{B}}_1(\vect{p}_{-1})$ in practice, $\mathcal{J}_1(\vect{p}_{-1})$ should be first estimated over an observation window where $\vect{p}_{-1}$ is held fixed. This can be done in two steps. In the first step, user 1 transmits with probability $p_1$ over the first half of an observation window and the expected user rates $\bar{R}_k(p_1,\vect{p}_{-1}), \forall k \in \mathcal{N}\setminus \{1\}$ are estimated at their respective BSs. In the second step, user 1 abstains from transmission (i.e. $p_1=0$) in the second half of the observation window, and a new set of expected user rates $\bar{R}_k(0,\vect{p}_{-1}), \forall k \in \mathcal{N}\setminus \{1\}$ are estimated. $V_k(\vect{p}_{-1})$ and $U_k(\vect{p}_{-1})$ can be then obtained for every user $k \in \mathcal{N}\setminus \{1\}$ by solving the following system of linear equations, \begin{equation} \label{eq:lsystem} \begin{aligned} &\bar{R}_k(p_1,\vect{p}_{-1}) = p_1 V_k(\vect{p}_{-1}) + (1-p_1)U_k( \vect{p}_{-1}) \\ &\bar{R}_k(0,\vect{p}_{-1}) = U_k( \vect{p}_{-1}), \end{aligned} \end{equation} and so $Q_k(\vect{p}_{-1}), \forall k \in \mathcal{N}\setminus \{1\}$ can be computed and aggregated to obtain $\mathcal{J}_1(\vect{p}_{-1})$. Next, the roots of $p_1 = \mathcal{F}_1(p_1)$ should be found and $\Tilde{\mathcal{B}}_1(\vect{p}_{-1})$ is either $p_1^* = \mathcal{F}_1(p_1^*) \in [\varepsilon_p,1]$ or $p_1^*=1$. Finding the roots of high order polynomials, however, is challenging in practice. For instance, by the Abel–Ruffini theorem, there is no algebraic solution in radicals to general polynomial equations of degree $K\geq 5$ with arbitrary coefficients. Rather than finding the set of all roots, it suffices to find the root $p_1^* \in [\varepsilon_p,1]$ if it exists. To this end, we propose a method based on fixed point iteration in which user $i=1$ find its optimal transmission probability using the sequence, \begin{equation} \label{ep:fp} \begin{aligned} p_i^{n+1} = \Tilde{\mathcal{B}}_i(p_i^n,\vect{p}_{-i}) = \text{min}\big\{ \mathcal{F}_i(p_i^n),1 \big\}. \end{aligned} \end{equation} Analyzing the convergence \eqref{ep:fp} requires the degree of the polynomial $K$ to be specified. Notice that the higher the order of Taylor approximation $K$ is, the better the approximation of $\mathcal{P}(p_1, \vect{p}_{-1})$ \eqref{eq:p_from_i}. However, increasing $K$ also increases the communication overhead as the aggregation vector $\mathcal{J}_1(\vect{p}_{-1})$ is of dimension $K$. To balance computational accuracy with communication overhead, $K$ is set to $5$. Before presenting convergence analysis of \eqref{ep:fp}, we first introduce the definition of a Lipschitz function and prove an intermediate lemma regarding the composition of Lipschitz function with point-wise minimum. \begin{definition} Let a function $f: [a,b] \rightarrow \mathbb{R}_+$ be such that for some constant $L$ and $\forall x,y \in [a,b]$, $$ |f(x)-f(y)| \leq L|x-y|, $$ then the function $f$ is called a Lipschitz function on $[a,b]$, and the least constant $q= \underset{x\neq y }{\text{sup}} \frac{|f(x)-f(y)|}{|x-y|}$ is called the Lipschitz constant. \end{definition} \begin{lemma} Suppose a function $f(x): x\in [a,b] \rightarrow \mathbb{R}_+$ has a Lipschitz constant $q$, then $g(x) = \text{min} \{f(x), 1\}$ has a Lipschitz constant that is at most $q$. \end{lemma} \begin{proof*} Notice that $g(x) = \text{min} \{f(x), 1\} = \frac{f(x) + 1 - |f(x)-1|}{2}$. Then, \begin{equation} \begin{aligned} |&g(x) - g(y)| \\&= \Big|\frac{f(x) - f(y)+|f(y)-1| - |f(x)-1| }{2} \Big| \\ &\leq \Big|\frac{ f(x) - f(y)+|f(y)- f(x)| }{2} \Big| \\ &\leq |f(x) - f(y)| \end{aligned} \end{equation} where the first inequality is obtained based on the reverse triangle inequality $|x|-|y| \leq |x-y|$, and the second inequality is obtained based on the fact that $x-y \leq |x-y|$. Since $f(x)$ has a Lipschitz constant $q$, we have that, \begin{equation} |g(x) - g(y)| \leq |f(x) - f(y)| \leq q |x-y|, \end{equation} i.e., the Lipschitz constant of $g(x)$ is at most $q$. $\blacksquare$ \end{proof*} \begin{lemma} Given that $Q_k(\vect{p}_{-1})>0, \forall \vect{p}_{-1} \in \mathcal{A}_{-1}$, $\big[\sum_{k\neq 1} Q_k(\vect{p}_{-1}) \big]^2 > \sum_{k\neq 1} \big(Q_k(\vect{p}_{-1})\big)^2 , \forall N \geq 3$ \end{lemma} \begin{proof*} The general case of $N\geq 3$ can be proved by induction. For the base case of $N=3$, $\big[Q_2(\vect{p}_{-1}) +Q_3(\vect{p}_{-1}) \big]^2 = \big(Q_2(\vect{p}_{-1}) \big)^2 + \big(Q_2(\vect{p}_{-1}) \big)^2 + 2Q_2(\vect{p}_{-1})Q_3(\vect{p}_{-1}) > \big(Q_2(\vect{p}_{-1})\big)^2 +\big(Q_3(\vect{p}_{-1})\big)^2$. For the induction step, suppose that $\big[\sum_{k\neq 1} Q_k(\vect{p}_{-1}) \big]^2 > \sum_{k\neq 1} \big(Q_k(\vect{p}_{-1})\big)^2$ is true for $N=N^\prime$, then for $N=N^\prime+1$, $\big[\sum_{k\neq 1} Q_k(\vect{p}_{-1}) +Q_{N^\prime+1}(\vect{p}_{-1}) \big]^2=\big[\sum_{k\neq 1} Q_k(\vect{p}_{-1})\big]^2 + \big( Q_{N^\prime+1}(\vect{p}_{-1})\big)^2 + 2\big[\sum_{k\neq 1} Q_k(\vect{p}_{-1})\big]Q_{N^\prime+1}(\vect{p}_{-1}) > \sum_{k\neq 1} \big(Q_k(\vect{p}_{-1})\big)^2 + \big( Q_{N^\prime+1}(\vect{p}_{-1})\big)^2$ since $2\big[\sum_{k\neq 1} Q_k(\vect{p}_{-1})\big]Q_{N^\prime+1}(\vect{p}_{-1})>0$. $\blacksquare$ \end{proof*} The convergence of \eqref{ep:fp} is analyzed in proposition 2 and its proof therein. \begin{proposition} Starting from an arbitrary $p_1^0 \in [\varepsilon_p,1]$, the sequence $\{p_1^n\}$ defined by \eqref{ep:fp}, i.e., $p_i^{n+1} = \Tilde{\mathcal{B}}_i(p_i^n,\vect{p}_{-i}) = \text{min}\big\{ \mathcal{F}_i(p_i^n),1 \big\}$, converges to a unique fixed point $p_1^*$ for $n\geq1$ if the number of users is $N \geq 3$. \end{proposition} \begin{proof*} The map governing the dynamics of \eqref{ep:fp} is $\mathcal{T}: p_1 \rightarrow p_1^\prime$, where $p_1^\prime = \Tilde{\mathcal{B}}_1(p_1, \vect{p}_{-1})$. Notice that $\mathcal{T}: p_1 \in \mathcal{A}_1 \rightarrow p_1^\prime \in \mathcal{A}_1$, i.e., $p_1, p_1^\prime \in [\varepsilon_p,1]$. Define a distance metric $d(p_1,p_1^{\prime \prime})$ $\forall p_1, p_1^{\prime \prime} \in \mathcal{A}_1$ as the $\text{L}_1$ norm, $d(p_1,p_1^{\prime \prime}) = |p_1-p_1^{\prime \prime}|$. Then, by definition, the map $\mathcal{T} : \mathcal{A}_1 \rightarrow \mathcal{A}_1$ on the complete metric space $(\mathcal{A}_1,d)$ is called a contraction mapping on $\mathcal{A}_1$ if there exists $q_1 \in [0, 1)$ such that $d(\mathcal{T}(p_1),\mathcal{T}(p_1^{\prime \prime})) \leq q_1d(p_1,p_1^{\prime \prime}), \forall p_1, p_1^{\prime \prime} \in \mathcal{A}_1$. That is if, \begin{equation} \begin{aligned} d(\mathcal{T}(p_1),\mathcal{T}(p_1^{\prime \prime})) &= |\Tilde{\mathcal{B}}_1(p_1, \vect{p}_{-1})-\Tilde{\mathcal{B}}_1(p_1^{\prime \prime}, \vect{p}_{-1})| \\ &\leq q_1 |p_1 - p_1^{\prime \prime}|, \forall \vect{p}_{-1}\in \mathcal{A}_{-1},~~~ q<1. \end{aligned} \end{equation} To prove that such $q_1 \in [0, 1)$ exits, we first show that the Lipschitz constant of $\mathcal{F}_1(p_1)$ is strictly less than $1$. To this end, we investigate the maximum absolute rate of change of $\mathcal{F}_1(p_1)$ with respect to $p_1$ given a fixed strategy profile of all other players $\vect{p}_{-1}$, \begin{equation} \label{eq:sup} \underset{p_1}{\text{sup}} \left\lvert \frac{\partial \mathcal{F}_1(p_1)}{ \partial p_1}\right\rvert = \underset{p_1}{\text{sup}} \frac{\sum_{k\neq 1} \sum_{n=2}^5 (n-1)p_1^{n-2}{\big(Q_k(\vect{p}_{-1})\big)^n} }{\Bigg[\sum_{k\neq 1} \Big[ \sum_{n=1}^5 p_1^{n-1}{\big(Q_k(\vect{p}_{-1})\big)^n} \Big] \Bigg]^2}. \end{equation} Notice that, \begin{equation} \resizebox{1\hsize}{!}{$ \begin{aligned} &\Bigg[\sum_{k\neq 1} \Big[ \sum_{n=1}^5 p_1^{n-1}{\big(Q_k(\vect{p}_{-1})\big)^n} \Big] \Bigg]^2\\ &=\Bigg[\sum_{k\neq 1} Q_k(\vect{p}_{-1}) + p_1 Q_k^2(\vect{p}_{-1}) + p_1^2 Q_k^3(\vect{p}_{-1}) + p_1^3 Q_k^4(\vect{p}_{-1}) + p_1^4Q_k^5(\vect{p}_{-1})\Bigg]^2 \\ &>\Bigg[\sum_{k\neq 1} Q_k(\vect{p}_{-1}) \Bigg]^2 + \Bigg[\sum_{k\neq 1} p_1Q_k^2(\vect{p}_{-1}) + p_1^2Q_k^3(\vect{p}_{-1}) \Bigg]^2 \\ &~~~~~~~~~~~~~~+ 2\Bigg[\sum_{k\neq 1} Q_k(\vect{p}_{-1}) \Bigg]\Bigg[ \sum_{k\neq 1} p_1Q_k^2(\vect{p}_{-1}) +p_1^2Q_k^3(\vect{p}_{-1}) +p_1^3Q_k^4(\vect{p}_{-1}) \Bigg] \\ &>\Bigg[\sum_{k\neq 1} Q_k(\vect{p}_{-1}) \Bigg]^2 + \Bigg[\sum_{k\neq 1} p_1Q_k^2(\vect{p}_{-1}) \Bigg]^2 + 2\Bigg[\sum_{k\neq 1} p_1Q_k^2(\vect{p}_{-1}) \Bigg]\Bigg[\sum_{k\neq 1} p_1^2Q_k^3(\vect{p}_{-1}) \Bigg]\\ &~~~~~~~~~~~~~~+ 2\Bigg[\sum_{k\neq 1} p_1Q_k^3(\vect{p}_{-1}) \Bigg] + 2\Bigg[\sum_{k\neq 1} p_1^2Q_k^4(\vect{p}_{-1}) \Bigg] + 2\Bigg[\sum_{k\neq 1} p_1^3Q_k^5(\vect{p}_{-1}) \Bigg] \\ &>\Bigg[\sum_{k\neq 1} Q_k(\vect{p}_{-1}) \Bigg]^2 + 2\Bigg[\sum_{k\neq 1} p_1Q_k^3(\vect{p}_{-1}) \Bigg] + 3\Bigg[\sum_{k\neq 1} p_1^2Q_k^4(\vect{p}_{-1}) \Bigg] + 4\Bigg[\sum_{k\neq 1} p_1^3Q_k^5(\vect{p}_{-1}) \Bigg], \end{aligned}$} \end{equation} where the strict inequalities come from the fact that some positive terms of the form $p_1^{l^\prime}Q_k^{l^{\prime \prime}}(\vect{p}_{-1})> 0$ for some integers $l^\prime,l^{\prime \prime} $, along with some positive product terms when expanding the parentheses and summations have been dropped. Based on lemma 2, $\big[\sum_{k\neq 1} Q_k(\vect{p}_{-1}) \big]^2 > \sum_{k\neq 1} \big(Q_k(\vect{p}_{-1})\big)^2 , \forall N \geq 3$. This shows that the denominator of \eqref{eq:sup} is strictly larger than its numerator. Hence, $\underset{p_1}{\text{sup}} \left\lvert \frac{\partial \mathcal{F}_1(p_1)}{ \partial p_1}\right\rvert < 1$ and there exists $q_1 \in [0,1)$ for which $\underset{p_1}{\text{sup}} \left\lvert \frac{\partial \mathcal{F}_1(p_1)}{ \partial p_1}\right\rvert \leq q_1$. By the mean value theorem from calculus, there exists some $\xi \in (p_1, p_1^{\prime \prime})$ such that $\forall p_1, p_1^{\prime \prime} \in \mathcal{A}_1$ \begin{equation} \label{eq:mvt} \mathcal{F}_1^\prime (\xi) = \frac{\mathcal{F}_1(p_1)-\mathcal{F}_1(p_1^{\prime \prime})}{p_1 - p_1^{\prime \prime}}. \end{equation} By taking the absolute value of both sides in \eqref{eq:mvt} and noting that $|\mathcal{F}_1^\prime (\xi)| \leq q_1$, \begin{equation} \left\lvert \mathcal{F}_1^\prime (\xi) \right\rvert = \left\lvert \frac{\mathcal{F}_1(p_1)-\mathcal{F}_1(p_1^{\prime \prime})}{p_1 - p_1^{\prime \prime}} \right\rvert \leq q_1 \end{equation} i.e., the Lipschitz constant of $\mathcal{F}_1(p_1)$ is $q_1$, which is strictly less than $1$. Based on the result of lemma 1, $\forall p_1,p_1^{\prime \prime} \in \mathcal{A}_1$ and $\forall \vect{p}_{-1} \in \mathcal{A}_{-1}$, \begin{equation} \label{eq:lcineq1} \begin{aligned} &\left\lvert \Tilde{\mathcal{B}}_1(p_1,\vect{p}_{-1}) -\Tilde{\mathcal{B}}_1(p_1^{\prime \prime},\vect{p}_{-1}) \right\rvert \leq q^* \left\lvert{p_1 - p_1^{\prime \prime}}\right\rvert. \end{aligned} \end{equation} Convergence of \eqref{ep:fp} to a unique fixed point $p_1^* \in [\varepsilon_p,1]$ can be concluded based on Banach fixed point theorem, which guarantees that the contraction mapping $\mathcal{T}$ admits a unique fixed-point $p_1^* \in \mathcal{A}_1$, and that the sequence $\{p_1^0, p_1^2, \cdots\}$ converges to $p_1^*$. $\blacksquare$ \end{proof*} The analysis and the result of proposition 2 enable the design of a practical discrete-time BR dynamics algorithm in which users sequentially play a best response strategy to the observable action aggregator $\mathcal{J}_i(\vect{p}_{-i}^t)$ of all other users. As shown in Algorithm 2, in each iteration $t\geq0$, one user $i \in \mathcal{N}$, updates its transmission probability using \eqref{ep:fp} to the unique fixed point $p_i^{t*} = \Tilde{\mathcal{B}}_i(p_i^{t*},\vect{p}_{-i}^t)$. Notice that the algorithm terminates when the change in the common utility function of users is less than a small positive infinitesimal quantity $\varepsilon_T$. The convergence of Algorithm 2 to a pure Nash equilibrium is formalized in Theorem 3. \begin{algorithm} \label{Alg2} \SetKwInOut{Input}{Input} \SetKwInOut{Output}{Output} \Input{Instance of the strategic form game $\mathcal{G}=\langle \mathcal{N},\mathcal{A},\mathcal{U} \rangle$\\ Initial transmission probability vector $\vect{p}^0 \in \mathcal{A}$} \Output{Nash equilibrium $\vect{p}^*$ } Estimate expected user rates $\bar{R}_i(\vect{p}^{0}), \forall i \in \mathcal{N}$\\ \For{$t=0,1, \cdots$, } { Randomly pick a user $i \in \mathcal{N}$\\ Set $p_i=0$ and estimate expected user rates $\bar{R}_k(0,\vect{p}^{t}_{-i}), \forall k \in \mathcal{N} \setminus \{i\}$\\ Compute $V_k(\vect{p}_{-i}^t)$ and $U_k(\vect{p}_{-i}^t)$ by solving the linear system \eqref{eq:lsystem} using $\bar{R}_k(p_i^t,\vect{p}^{t}_{-i})$ and $\bar{R}_k(0,\vect{p}^{t}_{-i})$, $\forall k \in \mathcal{N} \setminus \{i\} $ \\ Compute $Q_k(\vect{p}_{-i}^t) = \frac{U_k(\vect{p}_{-i}^t) - V_k(\vect{p}_{-i}^t)}{U_k(\vect{p}_{-i}^t)}, \forall k \in \mathcal{N} \setminus \{i\} $ \\ Compute the action aggregator $\mathcal{J}_i(\vect{p}_{-i}^t)$ \\ Set $p_i^\prime = p_i^t, \varepsilon_{\text{MAE}}=1$\\ \While{$\varepsilon_{\text{MAE}}\geq \varepsilon_T$} { $p_i^{\prime \prime}= \text{min}\Big\{\mathcal{F}_i(p_i^\prime),1\Big\}$\\ $\varepsilon_{\text{MAE}}= |p_i^\prime - p_i^{\prime \prime} |$\\ Set $p_i^{\prime } = p_i^{\prime \prime}$ } Set $p_i^{t+1} = p_i^\prime$\\ Set $\vect{p}^{t+1}=(p_1^t, \cdots, p_{i-1}^t,p_i^{t+1},p_{i+1}^t,\cdots,p_N^t)$\\ Estimate expected user rates $\bar{R}_i(\vect{p}^{t+1}), \forall i \in \mathcal{N}$\\ \If{ $|\mathcal{O}(\vect{p}^{t})- \mathcal{O}(\vect{p}^{t+1})| \leq \varepsilon_T$ } {Break} Set $\vect{p}^{t}= \vect{p}^{t+1}$\\ } \caption{BR Dynamics with Action Aggregation} \end{algorithm} \begin{theorem} Algorithm 2 converges to a pure Nash equilibrium $\vect{p}^*$ of the strategic form game $\mathcal{G} = \langle \mathcal{N}, \mathcal{A}, \mathcal{U} \rangle$ if the number of players is $N \geq 3$. \end{theorem} \begin{proof*} In every iteration $t$ of Algorithm 2, one user $i \in \mathcal{N}$ deviates from its current strategy $p_i^t$ to $p_i^{t+1}$ such that $p_i^{t+1} = \underset{p_i}{\text{argmax}}~\mathcal{P}(p_i, \vect{p}_{-i}^t)$, where $p_i^{t+1} \in [\varepsilon_p,1]$ is the unique strict global maximizer of $\mathcal{P}(p_i, \vect{p}_{-i}^t)$ given the current strategy profile of all other users $\vect{p}_{-1}^t \in \mathcal{A}_{-i}$, or $p_i^{t+1}=1$ in the case of $\mathcal{F}_i(p_i) > 1, \forall p_i \in [\varepsilon_p, 1)$. If $p_i^{t+1}$ is the strict global maximizer, $\mathcal{P}(p_i^{t+1}, \vect{p}_{-i}^t) > \mathcal{P}(p_i^t, \vect{p}_{-i}^t)$, $\forall p_i^t \neq p_i^{t+1} \in [\varepsilon_p,1]$. In the case of $\mathcal{F}_i(p_i) > 1$, $\frac{\partial \mathcal{P}(p_i,\vect{p}_{-i}^t)}{\partial p_i}=\frac{1}{N}\Big[\frac{1}{p_i} - \frac{1}{\mathcal{F}_i(p_i)} \Big] > 0, \forall p_i \in [\varepsilon_p,1)$, and so $\mathcal{P}(p_i^{t+1}=1, \vect{p}_{-i}^t) > \mathcal{P}(p_i^t, \vect{p}_{-i}^t),\forall p_i^t \in [\varepsilon_p,1) $ because $\mathcal{P}(p_i, \vect{p}_{-i}^{t})$ is a strictly monotonously increasing function on $p_i \in [\varepsilon_p,1)$. Hence, a deviation from $p_i^t$ to $p_i^{t+1}$ where $p_i^t\neq p_i^{t+1}$ necessarily improves the potential function of the game $\mathcal{G}$. Because $\mathcal{P} < \infty, \forall \vect{p} \in \mathcal{A}$, Algorithm 2 must terminate when no user can deviate from its current strategy to further improve $\mathcal{P}$. $\blacksquare$ \end{proof*} \section{Performance Evaluation} We have developed a simulator in Python and set up a multi-cell Wireless IoT network with NOMA as described in section \ref{sec:sysmod}, and implemented the proposed centralized and distributed learning algorithms in TensorFlow. Unless mentioned otherwise, the network consists of $N$ IoT devices and $M$ BSs, {where IoT devices are deployed independently and uniformly randomly within a square deployment area of $[-500,500] \times [-500,500]$m, and BSs are deployed in the cluster centroids as determined by Lloyd's ($K=M$)-means clustering algorithm \cite{lloyd1982least} for each realization of the random IoT device deployment. A Rayleigh fading channel with distance-dependent free-space path-loss is adopted as in \cite{khairy2020constrained}.} \begin{comment} Let the location of IoT device $i$ be $(\hat{x}^i,\hat{y}^i), \forall i \in \mathcal{N}$, and let $(x^m, y^m)$ denote the location of BS $m, \forall m \in \mathcal{M}$. In our simulations, we assume that the power of the signal transmitted by an IoT device $i$ to BS $m$ is subject to independent and identically distributed Rayleigh fading, $h_{i,m}$, and a distance-dependent free-space path-loss $d_{i,m}^{-\alpha}$, where $\alpha$ is the path-loss exponent, and $d_{i,m}$ is the propagation distance between IoT device $i$ and BS $m$, $d_{i,m} = \sqrt{ (x^m-\hat{x}^i)^2 + (y^m-\hat{y}^i)^2}$. Based on this model, the received power at BS $m$ from IoT device $i$ in a communication slot $t_n$ given that user $i$ transmits is, \begin{equation} \label{rxPwr} \begin{gathered} \begin{aligned} P^{i,m}_{RX} = \begin{cases} c_0 h_{i,m} P_{TX}d_0^{-\alpha},~d_{i,m}\leq d_0, \\ c_0 h_{i,m} P_{TX} d_{i,m}^{-\alpha}, d_{i,m}\geq d_0, \end{cases} \end{aligned} \end{gathered} \end{equation} where $c_0 = \frac{\lambda^\alpha}{(4\pi)^\alpha}$ is a constant which depends on the wavelength of the transmitted signal, $\lambda$, and $d_0$ is a reference distance. \end{comment} For the centralized learning-based algorithm, an ensemble of $E=10$ ICNN-based models is used, where each ICNN model is a fully connected multi-layer perceptron network as shown in Fig. 1, with three hidden layers of $128$ neurons to predict $-\hat{\mathcal{O}}_\mu(\vect{p}; \vect{\theta})$. An additional hidden layer of $128$ neurons is also used to predict $\sigma^2(\vect{p};\vect{\theta})$. The main simulation parameters used in the experiments are tabulated in Table \ref{table:simparam}. \begin{table}[ht] \caption{Simulation Parameters} \centering \begin{tabular}{c c | c c } \hline\hline Parameter & Value & Parameter & Value \\ [0.5ex] \hline $P_{TX}$ & $30~dBm$ & Hidden layers & $3$ \\ $\alpha$ & $2$ & Neurons per layer & $128$ \\ $f_0$ & $900$ MHz & Number of models $E$ & $10$ \\ $d_0$ & $1m$ &$T$ & $10$ \\ $h_{i,m}$ & $exp(1)$ & $H_t, \forall t \in [T]$ & $100$ \\ $n_0$ & $-100dBm$ & $\beta_t$ & $\frac{1}{9}(10-t)$\\ $\mathcal{W}$ & $1Hz$ & Dim$[\vect{W}^{(\sigma)}]$ & $1 \times 128$ \\ $\text{SNIR}_\text{Th}$ & $-5.1dBm$ & $\epsilon_T$ & $1\times 10^{-6}$ \\ \hline \end{tabular} \label{table:simparam} \end{table} \subsection{Comparison of Learning Algorithms} \vspace{-1mm} First, we compare the performance of the proposed centralized and distributed learning algorithms with some common state-of-art derivative-free off-the-shelf optimizers implemented in the NLopt nonlinear optimization package~\cite{nlopt}, namely, BOBYQA~\cite{powell2009bobyqa}, COBYLA~\cite{powell1994direct,powell1998direct}, and Nelder-Mead~\cite{nelder1965simplex}, on $10$ random deployments of a small scale network, i.e., $M=2$ BSs and $N=\{4, 8, 16\}$ IoT devices. The performance of our proposed algorithms is compared with gradient-free methods because analytical gradients of $\eqref{eq:system}$ are not readily available, and estimating the gradient requires at least two evaluations per gradient step for each $p_i,\forall i \in \mathcal{N}$, which makes gradient-based methods noncompetitive in terms of the required number of objective function evaluations. Starting from $10$ random initialization for $\vect{p}^0$, each optimizer is given a budget of $1000$ objective function evaluation to find the optimal transmission probability vector $\vect{p}^*$. In Fig. \ref{fig:optimizerPerformance}, the mean approximation ratio across $100$ runs ($10$ deployments $\times 10$ random initializations) of the proposed and baseline optimization algorithms, is shown as a function of objective function evaluation for the cases of (a) $N=4$, (b) $N=8$, and (c) $N=16$ IoT devices. The approximation ratio is defined as the ratio of the best $\mathcal{O}(\vect{p}^t)$ value attained by an optimizer up to evaluation $t$, to the optimal objective value for each deployment. The optimal objective value for each deployment is the best-found value by any optimization algorithm in any of its $10$ runs. For smaller-scale deployments (e.g. $N=4,8$), the proposed centralized and distributed learning-based optimization algorithms perform comparably in terms of the quality of the solution, although the distributed learning algorithm converges faster. The observation that the distributed learning-based algorithm performs as well as the centralized learning-based algorithm in which a concave surrogate model of $\vect{p}$ is learned, supports our conjecture that \eqref{eq:system} is a concave function of $\vect{p}$ over a convex set $S^N$. The proposed centralized learning-based optimization algorithm however, suffers from the curse of dimensionality as the problem scale increases as evident from Fig. \ref{fig:optimizerPerformance}(c). Both of our proposed machine-learning-based algorithms outperform the commonly used off-the-shelf, derivative-free optimizers such as Nelder-Mead, BOBYQA, COBYLA, which do not exploit any structure present in the optimization problems. In Fig. \ref{fig:topPerformance}, the optimization trajectories of the proposed centralized and distributed learning algorithms, as well as Nelder-Mead (best performing off-the-shelf optimizer) on a random topology of $N=16$ IoT devices and $M=2$ BSs are shown. Each optimizer is randomly initialized $10$ times and the mean value of $\mathcal{O}(\vect{p})$ along with the $5$-th and $95$-th percentiles are plotted. The proposed distributed learning-based optimization algorithm converges to the optimal solution much faster than other algorithms, and exhibits smaller variance in its optimization trajectory. These experiments demonstrate the superiority of our proposed distributed learning-based algorithm compared with other existing algorithms. \begin{figure*}[ht] \centering \subfloat[$N=4$]{\includegraphics[width=0.33\linewidth]{Figs/opt_perf_M_2_N_4.pdf}} \hfill \centering \subfloat[$N=8$]{\includegraphics[width=0.33\linewidth]{Figs/opt_perf_M_2_N_8.pdf}} \hfill \centering \subfloat[$N=16$]{\includegraphics[width=0.33\linewidth]{Figs/opt_perf_M_2_N_16.pdf}} \hfill \caption{Mean approximation ratio comparison of proposed and baseline optimization algorithms on $10$ random deployments of (a) $N=4$, (b) $N=8$, and (c) $N=16$ IoT devices and $M=2$ BSs.} \label{fig:optimizerPerformance} \end{figure*} \begin{figure}[ht] \centering \includegraphics[width=1.0\columnwidth]{Figs/opt_top_0_M_2_N_16.pdf} \caption{Optimization trajectories of different optimization methods on a random topology of $N=16$ IoT devices and $M=2$ BSs.} \label{fig:topPerformance} \end{figure} \subsection{Network Densification with NOMA} Next, we study the impact of network density with and without NOMA on the geometric mean of expected user rates in Fig. \ref{fig:NomaGain}. Each data point in Figs. \ref{fig:NomaGain}(a) and \ref{fig:NomaGain}(b) represent the mean of the optimal objective function $\mathcal{O}({\vect{p}^*})$ across $10$ random deployments, where the optimal transmission probability vector $\vect{p}^*$ is learned by the distributed learning based algorithm. In Fig. \ref{fig:NomaGain}(a), the number of IoT devices $N$ is varied in $\{100,200,\cdots, 900\}$ while $M$ is fixed to $2$ BSs. The geometric mean of the expected user rates decreases as more users join the network and time-share the wireless broadcast channel. It can also be observed that when the BSs support SIC-based decoding, the expected user rate is increased by about $33\%$ compared to the case without NOMA . In Fig. \ref{fig:NomaGain}(b), the number of IoT devices is fixed to $N=200$ while the number of BSs varies in $\{1,2,\cdots, 9\}$. Generally, increasing the number of BSs improves the geometric mean of expected user rates because the impacts of distance-dependent path loss become less severe with more deployed BSs. Notably however, the geometric mean of expected user rates is higher when there is only one NOMA-capable BS, compared with the cases when there are $M=\{2,3,4\}$ NOMA-capable BSs. This is because in a multi-cell network, it is less likely that both of the transmissions with the highest and second highest received SNIRs are from users associated with the same BS compared with single-cell networks. This can also be deduced by evaluating the NOMA gain as a function of $M$. When there is one NOMA-capable BS, NOMA gain is about $63\%$, compared with only $33\%, 16.2\%,8.9\%$ when there are $2,5, 9$ NOMA-capable BSs, respectively. \begin{figure}[ht] \centering \subfloat[$M=2$]{\includegraphics[width=1.0\columnwidth]{Figs/User_density.pdf}} \hfill \centering \subfloat[$N=200$]{\includegraphics[width=1.0\columnwidth]{Figs/BS_density.pdf}}\\ \caption{Geometric mean of expected user rates with and without NOMA in random deployments of (a) $M=2$ BSs and variable number of IoT devices $N$, and (b) $N=200$ IoT devices and variable number of BSs. } \label{fig:NomaGain} \end{figure} \subsection{Heterogeneous Access} Last but not least, we look at the transmission probability allocation of users with and without NOMA in a single-cell and a multi-cell IoT network. To this end, we consider networks of $N=144$ IoT devices which are deployed on a mesh grid of $[-500,500] \times [-500,500]$m. In Fig. \ref{fig:hetprob}(a) and Fig. \ref{fig:hetprob}(b), one BS is deployed at $(0,0)$m, whereas in Fig. \ref{fig:hetprob}(d) and Fig. \ref{fig:hetprob}(e) four BSs are deployed at $(-250,-250),~(250,-250),~(-250,250),~(250,250)$m. In Fig. \ref{fig:hetprob}(a) and Fig. \ref{fig:hetprob}(d), heatmaps of the heterogeneous access transmission probabilities learned by the distributed algorithm when the BSs do not support NOMA decoding are shown. As it can be seen from Fig. \ref{fig:hetprob}(a), edge IoT devices have the highest transmission probability (darkest blue shade), while IoT devices which are close to the BS have the lowest transmission probability (lightest blue shade). This allocation strategy maximizes the geometric mean of expected user rates by giving far users more chances to transmit compared with near users, thereby countering the impacts of distance-dependent path-loss on far users in the time domain and achieving a high Jain's rate fairness index of $0.9778$. A similar allocation strategy can be observed in the multi-cell case in Fig. \ref{fig:hetprob}(d), with the notable exception that central users in the middle of the 4 BSs are allocated low transmission probability, although they are relatively far from their respective BSs. This is because these central users cause significant interference to transmissions of users in all cells, unlike users at the edge of the deployment which mainly interfere with transmissions of users from their cell. In this case, the optimal transmission probability allocation also achieves a high Jain's rate fairness index of $0.9657$. On the other hand, the heatmaps of the heterogeneous access transmission probabilities learned by the distributed algorithm when the BSs support NOMA decoding are shown in Fig. \ref{fig:hetprob}(b) and Fig. \ref{fig:hetprob}(e). It can be seen that the allocation of transmission probabilities is quite different in these cases: users which are far from their serving BS are allocated lower transmission probabilities compared with users which are close to the BS. Thanks to NOMA decoding, transmissions of near users can be decoded in the first NOMA iteration, while transmissions of far users are decoded in the second NOMA iteration. Conceptually, a fewer number of near users compete to have their transmissions decoded in the first NOMA iteration, while a larger number of far users compete to have their transmissions decoded in the second NOMA iteration. Hence, near users are allocated higher transmission probability compared with farther users, and NOMA decoding enables a win-win type situation among near-far users, with high Jain's rate fairness indices of $0.9741$ and $0.9572$ for cases (b) and (e), respectively. In Fig. \ref{fig:hetprob}(c), a boxplot of the achievable expected user rates for the networks considered in Fig. \ref{fig:hetprob}(a,b,d,e) is shown. The boxplot summarizes the distribution of achievable expected user rates by showing the minimum, the maximum, the median, and the first and third quartiles of the expected user rate, in addition to outliers which are depicted by individual points. It can be observed that when BSs support NOMA decoding, the distribution of expected user rates is shifted upwards which hints that all users benefit from having NOMA-capable BSs. It is also evident that NOMA gain is higher in the single-cell case compared with the multi-cell case, which is consistent with the observations drawn from Fig. \ref{fig:NomaGain}(b). Moreover, it can be seen that the variation in expected rates achieved by different users is relatively narrow, and that the are no starving users as all users attain a positive expected rate, which is why the allocation strategies attained by maximizing the geometric mean of expected user rates achieve high Jain's fairness index overall. Note that if the arithmetic mean of expected user rates is to be maximized by choice of $\vect{p}$, the achieved Jain's fairness index will be $\frac{1}{N}$ when BSs do not support NOMA, or at most $\frac{2}{N}$ when BSs support NOMA. This is because the maximum arithmetic mean is attained at one of the extreme points of the convex set $\vect{p} \in [0,1]^N$, which grants the channel exclusively to one or two users without time sharing with other users, leading to very poor fairness. Because maximizing the arithmetic mean by choice of $\vect{p}$ produces adverse solutions, in Fig. \ref{fig:hetprob}(e) we study how our proposed geometric-mean based formulation compares with maximizing the arithmetic mean of expected user rates using a homogeneous transmission probability, that is, $p_i = p, \forall i \in \mathcal{N}$. Fig. \ref{fig:hetprob}(e) shows the heterogeneous access fairness gain, defined as the ratio of Jain rate fairness index achieved by maximizing the geometric mean of expected user rates using our proposed framework, to the Jain rate fairness index achieved by maximizing the arithmetic mean of expected user rates using a homogeneous transmission probability among all users, as a function of the path-loss exponent $\alpha$. It can be observed that tuning the transmission probability of individual users by maximizing the geometric mean yields significant fairness gains up to $250\%$ at higher path-loss exponents. This is because the variance of the received powers at BSs due to the spatial distribution of users is higher when $\alpha$ increases, which necessitates the tuning of the transmission probability at the user level to counter the impacts of distance-dependent path-loss and maintain rate fairness among users. \begin{figure*}[ht] \centering \subfloat[$\vect{p}^*$ in an $M=1$ network without NOMA \newline $~~~~~~\text{JF}\big(\bar{R}_1(\vect{p}^*), \cdots,\bar{R}_{144}(\vect{p}^*) \big)=0.9778$]{\includegraphics[width=0.33\linewidth,valign=c]{Figs/M1woNOMA.pdf}} \centering \subfloat[$\vect{p}^*$ in an $M=1$ network with NOMA \newline $~~~~~\text{JF}\big(\bar{R}_1(\vect{p}^*), \cdots,\bar{R}_{144}(\vect{p}^*) \big)=0.9741$]{\includegraphics[width=0.33\linewidth,valign=c]{Figs/M1wNOMA.pdf}} \centering \subfloat[Boxplot of the achievable expected user rates for the considered single- and multi-cell networks with and without NOMA]{\includegraphics[width=0.33\linewidth,valign=c]{Figs/box.pdf}}\\ \subfloat[$\vect{p}^*$ in an $M=4$ network without NOMA \newline $~~~~~~\text{JF}\big(\bar{R}_1(\vect{p}^*), \cdots,\bar{R}_{144}(\vect{p}^*) \big)=0.9657$]{\includegraphics[width=0.33\linewidth,valign=t]{Figs/M4woNOMA.pdf}} \centering \subfloat[$\vect{p}^*$ in an $M=4$ network with NOMA \newline $~~~~~\text{JF}\big(\bar{R}_1(\vect{p}^*), \cdots,\bar{R}_{144}(\vect{p}^*) \big)=0.9572$]{\includegraphics[width=0.33\linewidth,valign=t]{Figs/M4wNOMA.pdf}} \centering \subfloat[Jain rate fairness gain achieved by optimizing the geometric mean of expected user rates with heterogeneous transmission probabilities. The baseline is Jain rate fairness achieved by optimizing the arithmetic mean of expected user rates with homogeneous transmission probabilities, i.e., $p_i=p, \forall i$.]{\includegraphics[width=0.33\linewidth,valign=t]{Figs/barhom.pdf}} \caption{Heatmaps of the optimal heterogeneous access transmission probabilities learned by the distributed algorithm for a mesh grid deployment of $N=144$ IoT devices (blue squares) and (a) $M=1$ BS without NOMA, (b) $M=1$ BS with NOMA, (d) $M=4$ BSs without NOMA, (e) $M=4$ BSs with NOMA. In (a,b,d,e), red circles represent BSs, while the shade of blue squares correspond to the transmission probability of IoT devices (darker shades correspond to higher transmission probability). In (c), a boxplot of the achievable expected user rates for the four networks considered in (a,b,d,e) is shown. In (f), Jain fairness gain of heterogeneous access is shown with respect to optimal homogeneous access that maximizes the arithmetic mean of expected user rates. } \label{fig:hetprob} \end{figure*} \section{Conclusion} In this paper, we have proposed a novel formulation for random channel access of IoT devices in which the transmission probability of each IoT device is tuned to maximize the geometric mean of users' expected capacity. As the proposed optimization problem is high-dimensional and mathematically intractable, an efficient centralized learning algorithm and a provably convergent distributed learning-based algorithm have been proposed. Our formulation and proposed algorithms provide a versatile {data-driven} framework for optimizing single- and multi-cell random access based wireless IoT networks with and without NOMA decoding techniques, and achieves high capacity fairness among the spatially distributed IoT devices. The proposed framework can be leveraged to evaluate various deployment scenarios and provide guidelines for integrating NOMA techniques in slotted-Aloha systems in support of massive machine type communications in the beyond 5G era. \section*{Acknowledgment} This work is supported in part by the NSF grant ECCS1554576 and by the U.S. Department of Energy, Office of Science, under contract DE-AC02-06CH11357. We gratefully acknowledge the computing resources provided on Bebop, a high-performance computing cluster operated by the Laboratory Computing Resource Center at Argonne National Laboratory. \renewcommand{\thepage} {\arabic{page}} \bibliographystyle{IEEEtran}
{'timestamp': '2021-03-12T02:25:20', 'yymm': '2101', 'arxiv_id': '2101.00464', 'language': 'en', 'url': 'https://arxiv.org/abs/2101.00464'}
arxiv
\section{The Problem} At first glance, it is surprising why BMDL \cite{Jensen2019} is not used as a standard approach today, mainly because of the disadvantages of the NOEAL approach \cite{Kodell2009}. NOAEL depends on the design, i.e. sample size $n_i$, number of doses, chosen dose intervals, kind of endpoints, available historical controls, GLP conditions. In biomedical research, there are few better standardized studies than the in vivo and in vitro assays in regulatory toxicology, especially with respect to the criteria of minimum sample sizes, recommended number of doses, and a-priori defined endpoints. Thus, in the scenario considered here, the NOAEL does not combine all the described disadvantages of significance testing in mostly unplanned observational studies. Given the many alternative uncertainties, it should be accepted that the NOAEL is 'only' an experimental, i.e. designed dose and not, like BMDL, an interpolated estimate in the hundredths range with a spurious accuracy. Especially since an uncertainty factor with a wide definition range is added to NOAEL for the risk assessment. Practically, the BMD concept has at least four main difficulties: i) its model dependence (which can be reduced by model averaging \cite{Ritz2013}, ii) the necessary choice of BMR, which remains an unresolved challenge for multiple, continuous end points with different scales, variances, and relevance ranges, iii) the considerable width of the confidence interval for designs with only a few doses ( e.g., $k=3+1$ design), and iv) the sometimes non-textbook shape of dose-response dependencies (e.g., pronounced plateaus or even downward effects). e.g., the common $k=3+1$ design), and iv) the sometimes non-textbook shape of dose-response dependencies (e.g., pronounced plateaus or even downward effects at high dose(s)). Furthermore, dose selection in the design phase is more difficult to obtain a smooth log-logistic curve, required for the BMD concept- compared to a design with at least one non-significant and one significant dose (required for the NOAEL concept).\\ The main difference between NOEAL and BMD lies in the sparseness of assumptions: i) NOEAL assumes only significance of a point null hypothesis and monotonicity of the dose-response relationship for $D_i>NOEAL$ (more precisely the monotonicity of p-values $<0.05$), ii) BMD assumes a perfect fit of a specific nonlinear model as well as interpolation to the dose scale based on a selected BMR value (inverse regression).\\ NOAEL should be in fact estimated as the maximum safe dose, i.e., by a proof-of-safety approach \cite{Hothorn2008} as step-up non-inferiority tests. This approach is not currently used at all, mainly because it depends on the a priori definition of a threshold value that can still be interpreted, which is difficult practically. Therefore the simple alternative of a proof-of-hazard approach is used: $NOAEL=MED-1$, where minimum effective dose (MED) is the lowest significant dose, although all higher doses must also be significant. The Dunnett method \cite{DUNNETT1955} is often used for this purpose.\\ As basic law in toxicological risk assessment, the Paracelsus theorem can be regarded \textit{'All things are poison, and nothing is without poison. The dose alone makes a thing not poison'}. This requires non-significant effects both below and up to the NOAEL, and also significant effects beyond the NOAEL. Based on this model one can derive an order constraint assumption. The Williams procedure \cite{Williams1971} is based exactly on this assumption, but makes no statement about the individual doses (except $D_{max}$).\\ Two approaches to NOAEL estimation are described below, which were derived as special cases of the close testing procedure (CTP) \cite{MARCUS1976} for comparisons to the control and monotonicity assumption. \section{Closed testing procedures assuming order restriction} CTP is a general and flexible test principle for multiple testing, which is based on a decision tree of closed partition hypotheses tested by intersection-union-tests (IUT). The definition of the elementary hypotheses of interest is essential. For NOAEL estimation exactly the individual comparisons against control are of interest only, for example $H_0^{01}=\mu_1-\mu_0$, $H_0^{02}=\mu_2-\mu_0$, $H_0^{03}=\mu_3-\mu_0$. Based on these $H_0^\xi$, all intersection hypotheses are created up to the final global hypothesis in order to obtain a closed intersection hypotheses system:\\ \textit{partition hypotheses:} $H_0^{012}=\mu_2=\mu_1-\mu_0$, $H_0^{013}=\mu_3=\mu_1-\mu_0$, $H_0^{023}=\mu_3=\mu_2-\mu_0$,\\ \textit{global hyothesis:} $H_0^{0122}=\mu_3=\mu_2=\mu_1-\mu_0$\\ An elementary hypothesis of interest is rejected if it is rejected exactly, as are all partition hypotheses and the global hypothesis containing them, each with a test at the $\alpha$ level. Because any level-$\alpha$-test can be used, the closure test is flexible. If one assumes one-sided tests with an order restriction $\mu_0\leq \mu_1\leq...\leq \mu_k$ (for any pattern of equalities and inequalities, but at least $\mu_0< \mu_k$) due to a monotonic dose-response relationship, the following applies: if $H_0^{0122}=\mu_3=\mu_2=\mu_1-\mu_0$ is rejected, $H_0^{013}=\mu_3=\mu_1-\mu_0$, $H_0^{023}=\mu_3=\mu_2-\mu_0$, $H_0^{03}=\mu_3-\mu_0$ must also be rejected, without testing it. This allows the use of simple pairwise tests for \textit{all} hypotheses. Here, pairwise contrast tests are used \cite{Hothorn2021} to exploit the full degree of freedom of the k-sampling problem.\\ The adjusted p-value for the elementary hypothesis of interest results from the maximum of all p-values in its hypothesis tree (IUT):\\ $H_0^{01}: H_0^{01} \subset H_0^{012} \subset H_0^{0123} \Rightarrow p_{01}=max(p_{01}, p_{02}, p_{03})$\\ $H_0^{02}: H_0^{02} \subset H_0^{012} \subset H_0^{0123} \Rightarrow p_{02}=max(p_{02}, p_{03})$\\ $H_0^{03}: H_0^{03} \subset H_0^{0123} \Rightarrow p_{03}= p_{03}$\\ From a toxicological point of view, it is interesting that the comparison $D_{max}-0$ is performed with an unadjusted level $\alpha$-test (and thus of maximum possible power). The $D_{max-1}-0, D_{max-2}-0,...$ comparisons with slightly higher, increasing conservatism (because on the IUT condition). This is an intuitive, simple and powerful method for NOAEL estimation. In particular, it can be generalized to many situations that occur in toxicology: parametric and non-parametric tests, assuming homogeneous variance or not, considering proportions, counts, poly-k-estimates, using a mixed effect model (e.g. to take within/between-litter dependencies into account), etc.. Related R-software is available, see examples in the Appendix. \section{Demonstration the procedures for four selected in-vivo bioassay} The first example contains body weight changes for Fischer 344 rats treated with 0, 100, 200, 500, and 750 mg/kg doses of aconiazide over a 14-day period \cite{West2005}. The second example considers relative kidney weight data in a feeding study with a crop-protecting compound \cite{Tamhane2004}. The third example use severity scores of lesions in epithelium after exposure to formaldehyde in doses of 0, 2, 6, and 15 ppm in Fisher 344 rats \cite{Yanagawa1997}. The fourth example considers effect of vinylcyclohexene diepoxide exposure to 0 mg/ml, (group 0), 25 mg/ml (group 1), 50 mg/ml (group 2), and 100 (group 3) mg/ml, on the incidence of alveolar/bronchiolar tumors in a long term rodent carcinogenicity study on female B6C3F1 mice \cite{Piegorsch1997}. Figure 1 shows three boxplots (for examples 1,2,3 from the left to the right, and the mosaicplot for the crude tumor proportions in example 4, right panel). This random selection shows designs with only 3 dose groups (and 4 dose groups in example 1). \begin{figure}[htbp] \centering \includegraphics[width=0.232\textwidth]{BoxWest.jpeg} \includegraphics[width=0.232\textwidth]{BoxTamh.jpeg} \includegraphics[width=0.232\textwidth]{BoxYana.jpeg} \includegraphics[width=0.232\textwidth]{Mosaicbronch.jpeg} \caption{Raw data plots for the four data examples (from left to right examples 1, 2, 3, 4)} \label{fig:BoxTamh} \end{figure} Since normal distribution and homogeneous variances can be assumed for the endpoint body weight gain in example 1, the closure test with parametric multiple contrast is estimated. (R-Code see Appendix 1). In the original paper of example 2 ratio-to-control tests under variance heterogeneity were used \cite{Tamhane2004}. Therefore a closure test is used by simultaneous ratio-to-control tests \cite{Hothorn2011} (R-Code see Appendix 2). The severity score endpoint in example 3 is analysed by a nonparametric multiple contrast test for the relative effect size \cite{Konietschke2012} (p-value in brackets) and alternatively by contrast test using the most likely transformation model for count data \cite{Siegfried2020} (R-Code see Appendix 3). In long-term carcinogenicity bioassay, the complex relationship between tumor development and mortality can be modeled with the poly-k-test \cite{BIELER1993} whereas related multiple contrast tests are available in the R package MCPAN \cite{Schaarschmidt2008}. This uses a generalized contrast test for the difference of proportions, more precisely, weighted proportions. (R-Code see Appendix 4). Table 1 shows for these 4 examples the adjusted p-values of the specific closure tests for the respective control comparisons and the estimated NOAEL (marked in bold). In example 2, no NOAEL can be estimated as there is no non-significant dose, contrary to the original work \cite{Tamhane2004}, so the control 0 is marked in bold (an inappropriate dose selection in this assay). The nonparametric approach in example 3 reveals the same decision as the most likely transformation approach, but with slightly different p-values $(0.058; 0.00061; <0.00001)$. \begin{table}[ht] \centering \begin{tabular}{ll|ll|ll|ll} \multicolumn{2}{c}{Exa. 1} & \multicolumn{2}{c}{Exa. 2} & \multicolumn{2}{c}{Exa. 3} & \multicolumn{2}{c}{Exa. 4} \\ Comp. & $p^{adj}$ & Comp. & $p^{adj}$ & Comp. & $p^{adj}$ & Comp. & $p^{adj}$ \\ \hline 100-0 & 0.48 & 1/\textbf{0} & 0.012 & \textbf{2}-0 & 0.058 & \textbf{25}-0 & 0.059 \\ \textbf{200}-0 & 0.11 & 2/0 & $<0.00001$ & 6-0 & 0.00016 & 50-0 & 0.017 \\ 500-0 & 0.00086 & 3/0 & $<0.00001$ & 15-0 & $<0.00001$ & 100-0 & 0.017 \\ 750-0 & $<0.00001$ & - & ... & - & ... & - & ... \\ \end{tabular} \caption{Adjusted p-values and estimated NOAEL (bold) for the four examples} \end{table} These examples have been selected to demonstrate that this approach can be applied to numerous scenarios, i.e. different endpoints, different effect sizes, different test principles, different assumptions.\\ To assess the difference between without/with assumption of order restriction, the p-values for the Dunnett procedure and the CTP are compared directly in Table 2. The same NOAEL is estimated in both approaches. The p-values differ slightly, but within the accuracy range of a multivariate t-distribution. \begin{table}[ht] \centering \begin{tabular}{ll|ll} \multicolumn{2}{c}{CTP} & \multicolumn{2}{c}{Dunnett procedure} \\ \hline \hline Comp. & $p^{adj}$ & Comp. & $p^{adj}$ \\ \hline 100-0 & 0.483 & 100-0 & 0.960 \\ \textbf{200}-0 & 0.1108 & \textbf{200-0} & 0.173 \\ 500-0 & 0.000864 & 500-0 & $9.01e-05$ \\ 750-0 & $1.969225e-11$ & 750-0 & $ 5.37e-14$ \\ \end{tabular} \caption{Adjusted p-values for Dunnett procedure and CTP in example 1} \end{table} \section{Conclusions} An intuitive, simple and flexible closure test with pairwise contrast tests is proposed to estimate NOAEL. It is based only on the assumption of a monotonic dose-response relationship. Notice, all discussed disadvantages of the NOAEL approach compared to the BMD approach remain. Nevertheless, it can be recommended as a possibility for the usual routine evaluation of in vivo and in vitro bioassays in regulatory toxicology, particularly for the common-used designs with a few doses or concentrations only. Extensions for multiple primary endpoints, e.g. multiple tumors, and the mixed model for litter-dependencies in reprotoxicological bioassays will be described next. \footnotesize \subsubsection*{Acknowledgement} Dr. Christian Ritz, University of Copenhagen I thank for valuable suggestions for a better visualization of the approach. \footnotesize
{'timestamp': '2021-01-05T02:15:56', 'yymm': '2101', 'arxiv_id': '2101.00427', 'language': 'en', 'url': 'https://arxiv.org/abs/2101.00427'}
arxiv
\section{Introduction} With the rapid development of Internet of Things (IoT), timely status updates have become increasingly critical in many emerging IoT applications, such as wireless industrial automation, autonomous vehicles, and healthcare monitoring \cite{b11}, \cite{b10}. In fact, the conventional performance metrics, e.g., throughput and delay, cannot adequately characterize the timeliness of the status updates \cite{b12}. For example, throughput can be maximized by generating and transmitting the status updates as frequent as possible. However, excessive update rates may lead to severe network congestion, which makes the status updates suffer from long transmission and queuing delays. Such long delays can be reduced by lowering the update rate. On the other hand, if the update rate is reduced too much, the monitor will receive undesired outdated status updates. Motivated by these facts, the age of information (AoI), defined as the time elapsed since the generation of the latest received status update, has been recently introduced to quantify the information freshness from the perspective of the receiver that monitors a remote process \cite{b14}. Unlike the conventional performance metrics, the AoI is related to both the transmission delay and the update generation rate \cite{b13}. As a result, the AoI has attracted increasing attention as a more comprehensive evaluation criterion for information freshness. \subsection{Background} Since the AoI concept was first proposed to characterize the information freshness in a vehicular status update system \cite{b1}, extensive studies focusing on the analysis and optimization of the AoI have appeared. Most existing work was concerned with the AoI performance of single-hop wireless networks \cite{b15, b16, b17, b18, b20, b21, b2, b19, b22, b23,b24,b25,b26,b27,b28,b29,b31, b30,b32,b33}. On the other hand, the AoI performance of multi-hop networks has also been studied in \cite{ b34,b35, b36, b37, b38,b39}. References \cite{ b34,b35, b36, b37} focused on the multi-hop networks with a single source. The authors in \cite{b34} considered a general multi-hop network, where a single source disseminates status updates through a gateway to the whole network. They proved that the preemptive Last Generated First Served (LGFS) policy is age-optimal among all causal policies when the packet transmission time is exponentially distributed, and for arbitrary general distribution of packet transmission time, the non-preemptive LGFS policy minimizes the age among all non-preemptive work-conserving policies. In \cite{b35}, the authors considered a simple three-node relay network where the relay not only forwards packets generated by another stream, but also needs to transmit its own age-sensitive packets. Under this scenario, a closed-form expression of the average AoI of the relay's packets was provided by leveraging specific queuing theory tools. Reference \cite{b36} characterized the average AoI at the input and output of each node in a line network, where a source delivers status updates to a destination monitor through a series of relay nodes. In \cite{b37}, both the optimal offline and online scheduling policies were proposed to minimize the AoI of a two-hop energy harvesting network. Both \cite{b38} and \cite{b39} focused on the AoI in multi-source, multi-monitor, and multi-hop networks. In \cite{b38}, the AoI of the considered multi-hop networks was studied under general interference constraints, and the optimal stationary policy minimizing the AoI in the studied system was also derived. The authors in \cite{b39} studied the multi-hop networks from a \textit{global} perspective in the sense that every node in the network is both a source and a monitor, and derived the lower bounds for peak and average AoI. An algorithm generating near-optimal periodic status update schedules was derived in \cite{b39}. \subsection{Motivation and Contributions} All the aforementioned work on multi-hop networks overlooked the direct link between the source and destination. Therefore, the updates from the source can only be transmitted to the destination via the relay. As far as we know, although leveraging the direct link between the source and destination can potentially enhance the information freshness, no existing work has designed the relaying strategy and analyzed the average AoI of a cooperative IoT system with the existence of a direct link. Such a design is indeed non-trivial. This is because delivering the status updates via the one-hop direct link takes a shorter transmission time at the cost of incurring a potentially higher error probability, while the delivery of status updates through the two-hop relay link could be more reliable at the cost of suffering longer transmission time. By considering the AoI at all three nodes, the optimal design can be attained by applying the Markov design process (MDP) tool. However, considering the limited capabilities of IoT devices \cite{b40}, the optimal policy of the MDP problem with three-dimensional state space may not be suitable for most practical IoT systems since it generally has a complex multi-threshold structure. Besides, in practical IoT system design, the closed-form expression of the average AoI is crucial to quickly verify whether the required AoI performance can be guaranteed with a given set of system parameters. The performance of the MDP policy is normally hard to analyze, which makes the verification difficult to be implemented. In this context, two natural questions arise: \textit{For the considered system, are there any policies with simple structures that can achieve near-optimal AoI performance? What is the average AoI performance of such simple policies?} To the best of the authors' knowledge, these questions have not been answered in the literature. Motivated by this gap, in this paper, we investigate a three-node cooperative IoT system, in which a source aims to timely report randomly generated status updates to its destination with the help of a relay. With the existence of a direct link between the source and destination, the transmission of status updates can either go through the one-hop direct link or the two-hop relay link. The goal of this paper is to design, analyze, and optimize simple policies, which can achieve near-optimal AoI performance of the considered system. The main contributions of this paper are summarized as follows: \begin{itemize} \item We first propose two age-oriented relaying (AoR) protocols with simple structures from the perspective of minimizing the AoI in the considered system, namely the source-prioritized AoR (SP-AoR) protocol and the relay-prioritized AoR (RP-AoR) protocol. To ensure that the latest status updates generated at the source can be timely transmitted, we propose the SP-AoR protocol, in which the relay opportunistically replaces the source to retransmit the successfully received status updates that have not been correctly delivered to the destination, but the retransmission at the relay can be preempted by the arrival of a new status update at the source. However, we find that the SP-AoR protocol may not perform well in reducing the AoI in some cases, e.g., the direct link of the considered system suffers from severe channel fading while the generation of new status updates at the source is frequent. Inspired by such cases, we then propose the RP-AoR protocol, in which the retransmission from the relay will not be preempted by a new status update arrival at the source. The two proposed protocols can complement each other in performance under various system parameters. \item Based on the AoI evolution process, we define some necessary time intervals to mathematically express the average AoI of both proposed protocols. By representing these time-interval definitions in terms of key system parameters, including the generation probability of the status updates and the transmission success probabilities of three links, we then attain closed-form expressions of the average AoI for both proposed AoR protocols. Note that the analysis is non-trivial compared to the point-to-point case because the AoI of the one-hop direct link and the two-hop relay link is coupled together. In particular, the analysis of the RP-AoR protocol is rather complicated since the possible system state is not unique when a status update is received by the destination through the relay link. Specifically, at the moment of the reception, the considered system may have two possible states: $(a)$ a fresher status update has been generated at the source; $(b)$ there are no fresher status updates at the source. This makes some defined time intervals not independent of each other, resulting in a challenging analysis. \item We further minimize the average AoI of both proposed protocols by optimizing the status generation probability at the source. Based on the optimization results, we find that generating status updates as frequently as possible can minimize the average AoI of the RP-AoR protocol. However, in the SP-AoR protocol, generating status updates too frequently in turn increases the average AoI in some cases, e.g., when the channel between the source and destination suffers from severe fading. Simulation results are then provided to validate the theoretical analysis, and demonstrate that the proposed protocols can outperform each other under various system parameters. Note that based on the analytical results, we can quickly determine which protocol to apply in the considered system to achieve better AoI performance. It is also shown that the protocol with better performance can achieve near-optimal performance compared with the optimal scheduling policy attained by the MDP tool. \end{itemize} \subsection{Organization} The rest of the paper is organized as follows. Section \uppercase\expandafter{\romannumeral2} introduces the system model. We propose, analyze, and optimize the SP-AoR protocol in Section \uppercase\expandafter{\romannumeral3}. Section \uppercase\expandafter{\romannumeral4} provides the design, analysis, and optimization of the RP-AoR protocol. Numerical results are presented in Section \uppercase\expandafter{\romannumeral5} to validate the theoretical analysis and the effectiveness of the proposed AoR protocols. Finally, conclusions are drawn in Section \uppercase\expandafter{\romannumeral6}. \section{System Model and AoI Definition} In this section, we describe the system model and present the AoI evolution at each node in the considered system. \subsection{System Description} Consider a three-node cooperative IoT system, in which a source node ($S$) aims to transmit randomly generated status updates to a destination node ($D$) as timely as possible with the help of a relay node ($R$). With the existence of a direct link between $S$ and $D$, the transmission of the status updates can either go through the $S$-$D$ link or the $S$-$R$-$D$ link. We assume that all nodes are equipped with a single antenna and work in the half-duplex mode. Time is divided into slots of equal durations, and the transmission of each status update takes exactly one time slot. We assume that all channels suffer from block fading, i.e., the channel responses remain invariant within one time slot but vary independently from one time slot to another. To quantify the timeliness of the status updates, we adopt a recently proposed AoI metric, first coined in \cite{b1}. At the beginning of each time slot, the considered cooperative system can have three transmission operations: $(a)$ $\mathbf{O}_{\mathbf{S}}$: $S$ broadcasts a status update to both $R$ and $D$; $(b)$ $\mathbf{O}_{\mathbf{R}}$: $R$ forwards a status update to $D$; $(c)$ $\mathbf{O}_{\mathbf{N}}$: Neither $S$ nor $R$ transmits a status update. In operation $\mathbf{O}_{\mathbf{S}}$, if $D$ successfully receives the status update from $S$, an acknowledgement (ACK) is sent back to $S$ at the end of the current time slot. If $R$ successfully receives the status update from $S$, in addition to feeding back an ACK to $S$ at the end of the current time slot, it also stores the received status update in its buffer for possible operation $\mathbf{O}_{\mathbf{R}}$ in the following time slot(s). For implementation simplicity, we assume that both $S$ and $R$ can only store one status update, which is discarded when a fresher status update is received successfully. Note that in age-oriented systems, it is meaningless to store stale status updates when a fresher status update is obtained. In operation $\mathbf{O}_{\mathbf{R}}$, $R$ forwards the stored status update to $D$, and $D$ transmits an ACK to $S$ at the end of the current time slot if it successfully receives the status update. The ACK link from both $R$ and $D$ to $S$ is considered to be error-free and delay-free. \subsection{Age of Information} Taking into account channel fading, we define $P_{1}$, $P_{2}$, and $P_{3}$ to denote the transmission success probabilities through the $S$-$D$ link, $S$-$R$ link, and $R$-$D$ link, respectively. We follow \cite{b2} and adopt a Bernoulli process to model the stochastic generation of status updates at $S$. Specifically, a new status update is generated with probability $p$ at the beginning of each time slot. Note that the stochastic generation of status updates at $S$ can also be considered as a transmission process through a virtual link with a transmission time of 0. Specifically, we can consider that a transmitter node generates a status update at the beginning of each time slot, and immediately transmits the status update to $S$ through the virtual link with a transmission success probability of $p$. Denote by $U_i(t)$, $i \in \{S, R, D\}$, the generation time of the most recent status update at the receiver side $i$ of a transmission link until time slot $t$. The AoI at receiver $i$ in time slot $t$ can then be defined as \begin{equation} \Delta_{i}(t)=t-U_{i}(t). \end{equation} As the receiver of the virtual link, if $S$ successfully receives the status update from the transmitter node, its local AoI will decrease to 0, otherwise its local AoI will increase by 1. Mathematically, the AoI evolution at $S$ is given by \begin{equation}\label{aois} \Delta_{S}(t+1)=\left\{ \begin{array}{rcl} \Delta_{S}(t)+1, & & g(t+1)=0,\\ 0, & & g(t+1)=1, \end{array} \right. \end{equation} where $g(t+1)$ denotes the indicator that is equal to 1 when $S$ successfully receives a status update in the virtual transmission (i.e., a status update is generated at $S$) at the beginning of time slot $t+1$, and $g(t+1)=0$ otherwise. As the receiver of the $S$-$R$ link, if $R$ successfully receives the status update from $S$, it will update the local AoI to match that at $S$, otherwise its local AoI will increase by 1. Mathematically, the AoI evolution at $R$ can be expressed as \begin{equation} \Delta_{R}(t+1)=\left\{ \begin{array}{rcl} \Delta_{S}(t)+1, & & w_S(t)=1\ \text{and}\ r_R(t)=1,\\ \Delta_{R}(t)+1, & & \text{otherwise}, \end{array} \right. \end{equation} where $w_S(t)=1$ denotes that the cooperative system chooses transmission operation $\mathbf{O}_{\mathbf{S}}$ (i.e., $S$ broadcasts a status update to both $R$ and $D$) in time slot $t$, and $r_R(t)=1$ denotes that $R$ successfully receives the status update from $S$ in time slot $t$. Similarly, we can also express the AoI evolution at $D$ as \begin{equation}\label{aoid} \Delta_{D}(t+1)=\left\{ \begin{array}{rcl} \Delta_{S}(t)+1, & & w_S(t)=1\ \text{and}\ r_D(t)=1,\\ \Delta_{R}(t)+1, & & w_R(t)=1,\ r_D(t)=1,\\ & &\ \text{and}\ \Delta_{R}(t) < \Delta_{D}(t),\\ \Delta_{D}(t)+1, & & \text{otherwise}, \end{array} \right. \end{equation} where $w_R(t)=1$ denotes that the cooperative system transmits with operation $\mathbf{O}_{\mathbf{R}}$ (i.e., $R$ forwards the stored status update to $D$) in time slot $t$, and $r_D(t)=1$ denotes that $D$ successfully receives a status update in time slot $t$. The first case in \eqref{aoid} corresponds to the case where $S$ broadcasts a status update and $D$ successfully receives it. In this case, the AoI at $D$ will be updated to match that at $S$. The second case in \eqref{aoid} corresponds to the case where the considered cooperative system transmits with operation $\mathbf{O}_{\mathbf{R}}$ and the stored status update at $R$ is successfully forwarded to $D$. In this case, the AoI at $D$ will be updated to match that at $R$ if the status update from $R$ is fresher. When no update is received at $D$ or the update is staler than the current status at $D$, i.e., the third case in \eqref{aoid}, the AoI will simply increase by 1. Note that, in the considered system, we focus on the long-term average AoI at $D$, which is given by \begin{equation} \bar{\Delta}_{D}=\lim\limits_{T \to \infty}\sup\frac{1}{T}\sum_{t=1}^{T}\Delta_{D}(t). \end{equation} With the help of the ACK, $S$ can have a table of the AoI evolution at each node in the considered system. As such, we assume that the nodes in the system are scheduled in a centralized manner and $S$ serves as the system coordinator. Specifically, based on the ACK received at the end of the current time slot, $S$ has the knowledge of the local AoI at $R$ and $D$ in the next time slot. At the beginning of the next time slot, after updating its own local AoI in the table, $S$ will determine the transmission operation of the system and immediately notify $R$ of the decision. For simplicity, we ignore the time for updating and making decisions at $S$, and the time for notifying $R$ of the decisions. Note that, in the considered system, we always have $\Delta_{S}(t)\leq\Delta_{R}(t)$ and $\Delta_{S}(t)\leq \Delta_{D}(t)$. This is because a new status update is first generated at $S$, and then broadcast to $R$ and $D$. Thus, the status updates at $R$ and $D$ cannot be fresher than that at $S$. It is obvious that, if there is $\Delta_{S}(t)=\Delta_{D}(t)$ in the AoI table, i.e., there are no new status updates to be transmitted in the system, $S$ coordinates the system to select $\mathbf{O}_{\mathbf{N}}$. Otherwise, either $\mathbf{O}_{\mathbf{S}}$ or $\mathbf{O}_{\mathbf{R}}$ is chosen to transmit the new status update to reduce the AoI at $D$. Specifically, if there is $\Delta_{S}(t)=\Delta_{R}(t)<\Delta_{D}(t)$ in the table, i.e., $S$ and $R$ have the same new status update to transmit, $S$ coordinates the system to transmit with $\mathbf{O}_{\mathbf{R}}$. Note that the channel gain of the $R$-$D$ link is generally better than that of the $S$-$D$ link. Retransmitting the same status update by $R$ instead of $S$ has a greater probability to reduce the AoI. If there is $\Delta_{S}(t)<\Delta_{R}(t)$ and $\Delta_{R}(t)>\Delta_{D}(t)$ in the table, the system obviously chooses $\mathbf{O}_{\mathbf{S}}$ for transmission. However, if there is $\Delta_{S}(t)<\Delta_{R}(t)<\Delta_{D}(t)$, one natural question arises: \textit{Which of $\mathbf{O}_{\mathbf{S}}$ and $\mathbf{O}_{\mathbf{R}}$ should be chosen to reduce the AoI at $D$? Operating in $\mathbf{O}_{\mathbf{S}}$ could lead to a fresher status update while operating in $\mathbf{O}_{\mathbf{R}}$ results in a higher transmission success probability.} The optimal answer to the question can be obtained with the help of the MDP tool. For the MDP problem with three-dimensional state space, the optimal policy generally has a complex multi-threshold structure, which makes the performance of the policy hard to analyze. This difficulty also exists in our considered three-node cooperative IoT system \cite{b42}. Considering the limited capabilities of IoT devices and the requirements for average AoI performance in certain practical IoT applications, we propose two low-complexity protocols for the considered system and derive their average AoI performance in closed form in the following sections. \vspace{-0.12cm} \section{Source-Prioritized AoR Protocols}\label{3} In this section, we propose a low-complexity SP-AoR protocol to reduce the AoI of the considered system. By analyzing the evolution of the AoI, we manage to attain the closed-form expression of the average AoI for the protocol. Given reasonable value sets of $P_1$, $P_2$, and $P_3$, we further minimize the average AoI by optimizing the status generation probability $p$. \vspace{-0.12cm} \subsection{Protocol Description} In conventional cooperation protocols, which are designed mainly from a physical layer perspective, dedicated channel resources are normally allocated for $R$ to facilitate the cooperation \cite{b5}. However, if the transmission success probability of the $S$-$D$ link is relatively large, it is apparent that transmitting more status updates through the $S$-$D$ link reduces the AoI. Therefore, conventional cooperation protocols may not perform well from the perspective of minimizing the AoI. We note that a network-level cooperation protocol, where $R$ utilizes the silence periods of $S$ terminals to execute cooperation, was proposed in \cite{b6} to improve the cooperative system performance. Inspired by such a protocol, to ensure that fresh status updates can be transmitted in a timely manner in the SP-AoR protocol, we enforce $S$ to preempt the retransmission from $R$ in case of a new status update arrival. Hence, even if $R$ has a status update to forward at the beginning of one time slot, it still needs to wait for the instruction from $S$. If $S$ has a new status update to transmit, it informs $R$ that the system transmits with $\mathbf{O}_{\mathbf{S}}$ in the current time slot. $R$ then discards its current status update and attempts to decode the new one sent by $S$. Otherwise, $S$ coordinates the system to keep retransmitting the update at $R$ with $\mathbf{O}_{\mathbf{R}}$ until the successful reception at $D$ or the preemption by $S$. It is worth mentioning that the design in \cite{b6} focused on the throughput maximization rather than the AoI minimization. To the best of the authors' knowledge, the SP-AoR protocol is the first effort towards the design and analysis of the considered cooperative system from the perspective of the AoI. \vspace{-0.13cm} \subsection{Analysis of Average AoI}\label{3B} For the ease of understanding the AoI evolution of the SP-AoR protocol, we illustrate an example staircase path for 10 consecutive time slots with an initial value of one in Fig. 1. We denote by $t_k$ the generation time of the $k$th status update received by $D$ and denote by $t_k'$ its arrival time at $D$. Moreover, we denote by $t_*$ the generation time of the discarded status updates in the considered system. \begin{figure} \centering \includegraphics[width=0.9\linewidth]{aoi_sp_revised} \vspace{-0.1cm} \caption{Sample staircase path of the AoI evolution for the SP-AoR protocol. We use $S\!\rightarrow\! D$, $S\!\rightarrow\! R$, $R\!\rightarrow\! D$, and Failure to denote the successful transmission through the $S$-$D$ link, the successful transmission through the $S$-$R$ link, the successful transmission through the $R$-$D$ link, and the failed transmission, respectively. Moreover, we use $\bullet$, {\scriptsize{$\triangle$}}, and $*$ to denote the events that none of the links are active, the $S$-$R$ link and the $S$-$D$ link are active, and the $R$-$D$ link is active, respectively.} \label{fig:aoisp} \vspace{-0.4cm} \end{figure} Note that we also define some time intervals in Fig. 1 to facilitate the calculation of the AoI. We define $S_k$ as the service time of the $k$th status update received by $D$, which is given by $S_k=t_k'-t_k$. $T_k$ is defined as the time duration between the generation time of the first status update after $t'_{k-1}$ and the arrival time of the $k$th received update at $D$ (i.e., $t'_k$). In addition, the interdeparture time between two consecutive arrivals of status updates at $D$ is given by $Z_k=t'_k-t'_{k-1}$ and $Z_k=T_k+W_k$, with $W_k$ being the waiting time from the arrival of the $(k-1)$th received update at $D$ (i.e., $t'_{k-1}$) to the generation of the first status update at $S$ after $t'_{k-1}$. According to the renewal process theory \cite{b43}, the observed time slots $[1,T]$ can be viewed as $X_T$ renewal periods. As depicted in Fig. 1, we denote by $Q_k$ the area under the AoI curve of the $k$th renewal period. Therefore, the average AoI of the SP-AoR protocol can be expressed by \begin{equation}\label{aoisp1} \bar{\Delta}_{SP}=\lim\limits_{T \to \infty }{\frac{X_{T}}{T}\frac{1}{X_{T}}\sum_{k=1}^{X_{T}}Q_{k}}=\frac{\mathbb{E}[Q_{k}]}{\mathbb{E}[Z_{k}]}. \end{equation}For further simplification, we represent $Q_{k}$ in terms of the time intervals defined above and it can be expressed as \begin{equation}\label{qksp} \begin{aligned} Q_{k}&=S_{k-1}+(S_{k-1}+1)+\cdots+(S_{k-1}+Z_{k}-1)\\ &=S_{k-1}Z_{k}+\frac{Z_{k}^2-Z_{k}}{2}. \end{aligned} \end{equation} \noindent By substituting \eqref{qksp} into \eqref{aoisp1}, we can express the average AoI as \begin{equation}\label{aoisp2} \bar{\Delta}_{SP}=\frac{\mathbb{E}[S_{k-1}Z_{k}]}{\mathbb{E}[Z_{k}]}+\frac{\mathbb{E}\big[Z_k^2\big]}{2\mathbb{E}[Z_{k}]}-\frac{1}{2}. \end{equation} In order to further simplify \eqref{aoisp2}, we have the following lemma. \begin{lemma} \label{lemma1} {In the SP-AoR protocol, the service time of the $(k-1)$th received update at $D$ is independent of the interdeparture time between the $(k-1)$th and the $k$th received update at $D$ such that \begin{equation} \mathbb{E}[S_{k-1}Z_{k}]=\mathbb{E}[S_{k-1}]\cdot \mathbb{E}[Z_{k}]. \end{equation}} \end{lemma} \begin{proof} As we have $Z_k=W_k+T_k$, Lemma \ref{lemma1} can be proved if the service time of the $(k-1)$th received update at $D$, i.e, $S_{k-1}$, is independent of both $W_k$ and $T_k$. It is straightforward to find that $S_{k-1}$ is independent of $T_k$ since the two random variables are defined for different updates. Recall that in the SP-AoR protocol, $S$ can preempt the transmission of $R$ when there is a new status update arrival. This indicates that the waiting time $W_k$ only depends on the generation probability $p$. This completes the proof. \end{proof} \noindent By applying Lemma 1, the expression of the average AoI can be simplified as \vspace{-0.1cm} \begin{equation}\label{aoisp3} \bar{\Delta}_{SP}=\mathbb{E}[S_{k-1}]+\frac{\mathbb{E}\big[Z_{k}^2\big]}{2\mathbb{E}[Z_{k}]}-\frac{1}{2}. \end{equation} To obtain the average AoI of the SP-AoR protocol, we now derive the terms $\mathbb{E}[S_{k-1}]$, $\mathbb{E}[Z_{k}]$ and $\mathbb{E}\big[Z_{k}^2\big]$ one by one in the following. \subsubsection{First Moment of the Service Time $\mathbb{E}[S_{k-1}]$} In the SP-AoR protocol, there are two types of status updates that can be successfully received by $D$ without being preempted, i.e., the updates successfully received by $D$ through the direct link and the updates successfully delivered to $D$ through the two-hop relay link. Therefore, $\mathbb{E}[S_{k-1}]$ is a weighted sum of the average service time of these two types. For the first type of successful updates, the probability that an update is successfully received after $l$ times of transmissions by $S$ can be expressed as \vspace{-0.05cm} \begin{equation}\label{PL} P_{l} = (1-p)^{l-1}(1-P_{2})^{l-1}(1-P_{1})^{l-1}P_{1}. \vspace{-0.05cm} \end{equation} The corresponding first moment of the service time can be calculated by \begin{equation}\label{EL} \mathbb{E}[l|\mathfrak{D}]=\frac{\sum_{l=1}^{\infty}P_{l}\cdot l}{\sum_{l=1}^{\infty}P_{l}}, \end{equation} where event $\mathfrak{D}$ denotes that the status updates successfully received by $D$ are transmitted through the direct link without preemption. Similarly, for the second type of successful status updates, the first moment of the service time can be expressed as \vspace{-0.05cm} \begin{equation}\label{EMN} \mathbb{E}[m+n|\mathfrak{R}]=\frac{\sum_{n=1}^{\infty}\sum_{m=1}^{\infty}P_{mn}\cdot(m+n)}{\sum_{n=1}^{\infty}\sum_{m=1}^{\infty}P_{mn}}, \end{equation} \noindent where event $\mathfrak{R}$ denotes that the status updates successfully received by $D$ are transmitted through the two-hop relay link without preemption. $m$ and $n$ denote the number of transmission times via the $S$-$R$ link and the $R$-$D$ link, respectively. $P_{mn}$ is the probability that an update is successfully received by $D$ after transmitting $(m+n)$ times, which can be expressed as \vspace{-0.025cm} \begin{equation}\label{PMN} \resizebox{.98\hsize}{!}{$P_{mn} \!=\! (1-p)^{m-1}(1-P_{2})^{m-1}(1-P_{1})^{m}P_{2}(1-p)^{n}(1-P_{3})^{n-1}P_{3}$}. \end{equation} Since the above two types of updates make up all the updates that can be received by $D$ without being preempted, the first moment of the service time for the SP-AoR protocol can be evaluated as \begin{equation}\label{Ssp1} \begin{aligned} \mathbb{E}[S_{k-1}]\!=\!&\ \mathbb{E}[l|\mathfrak{D}]\!\cdot\!\frac{\sum_{l=1}^{\infty}P_{l}}{\sum_{l=1}^{\infty}P_{l}\!+\!\sum_{n=1}^{\infty}\!\sum_{m=1}^{\infty}\!P_{mn}}\\ &\,\!+\! \mathbb{E}[m\!+\!n|\mathfrak{R}]\!\cdot\!\frac{\sum_{n=1}^{\infty}\!\sum_{m=1}^{\infty}\!P_{mn}}{\sum_{l=1}^{\infty}P_{l}\!+\!\sum_{n=1}^{\infty}\!\sum_{m=1}^{\infty}\!P_{mn}}, \end{aligned} \end{equation} \noindent which follows according to the law of total probability. \begin{figure*} \begin{subequations}\label{finite} \begin{equation} \begin{aligned} \sum_{k'=1}^{K}aq^{k'-1}=\frac{a(q^K-1)}{q-1},\ {\rm{with}} \ q\neq 1, \end{aligned} \end{equation} and \begin{equation} \sum_{k'=0}^{K-1}(a+k'r)q^{k'}=\frac{a-[a+(K-1)r]q^K}{1-q}+\frac{rq(1-q^{K-1})}{(1-q)^2},\ {\rm{with}}\ q\neq1 \ {\rm{and}} \ K>1. \end{equation} \end{subequations} \vspace{-0.2cm} \noindent\rule[0.05\baselineskip]{\textwidth}{0.5pt} \end{figure*} By applying the finite sum equations given in \eqref{finite} at the top of this page \cite[Eqs. (0.112) and (0.113)]{b7}, we can further simplify \eqref{Ssp1} to \begin{equation}\label{Ssp2} \mathbb{E}[S_{k-1}]=\frac{1}{1-\beta}+\frac{1}{1-\alpha}\cdot\frac{\gamma}{P_{1}(1-\alpha)+\gamma}, \end{equation} where $\alpha=(1-p)(1-P_{3})$, $\beta=(1-p)(1-P_{1})(1-P_{2})$ and $\gamma=P_{2}P_{3}(1-p)(1-P_{1})$. \subsubsection{First Moment of the Interdeparture Time $\mathbb{E}[Z_{k}]$} \begin{figure*} \begin{equation}\label{Tsp1} \begin{aligned} \mathbb{E}[T_{k}]=&\ \sum_{l=1}^{\infty}P_{l}\cdot l + \sum_{n=1}^{\infty}\sum_{m=1}^{\infty}P_{mn}\cdot (m+n) + \sum_{l=1}^{\infty}(1-P_{1})^{l}(1-P_{2})^{l}(1-p)^{l-1}p\cdot \big(l+\mathbb{E}\big[T'_{k}\big]\big)\\ &\,+\sum_{n=0}^{\infty}\sum_{m=1}^{\infty}\Big[(1-P_{1})^{m}(1-P_{2})^{m-1}P_{2}(1-p)^{m-1} \times(1-p)^{n}(1-P_{3})^{n}p\cdot \big(m+n+\mathbb{E}\big[T'_{k}\big]\big)\!\Big].\\ \end{aligned} \end{equation} \vspace{-0.5cm} \noindent\rule[0.05\baselineskip]{\textwidth}{0.5pt} \end{figure*} As we have $Z_{k}=W_{k}+T_{k}$, the first moment of the interdeparture time can be written as $\mathbb{E}[Z_{k}]=\mathbb{E}[W_{k}]+\mathbb{E}[T_{k}]$. Recall that, in the SP-AoR protocol, the waiting time $W_{k}$ only depends on the generation probability $p$. Since the status updates are generated according to a Bernoulli process, $W_{k}$ follows a geometric distribution with parameter $p$, and its first moment can be readily given by $\mathbb{E}[W_{k}]=(1-p)/p$. We then move on to the calculation of the term $\mathbb{E}[T_{k}]$. Note that in the SP-AoR protocol, $T_{k}$ behaves differently for the following four possible cases: $(a)$ The update is successfully received by $D$ through the $S$-$D$ link without being preempted; $(b)$ The update is successfully received by $D$ through the $S$-$R$-$D$ link without being preempted; $(c)$ The update is preempted by a new update before being successfully received by either $R$ or $D$, and the new update may be preempted by multiple new updates; $(d)$ The update is preempted by a new update generated at $S$ after being successfully received by $R$, and the new update may be preempted by multiple new updates at $S$. We note that the number of preemptions can approach infinity in the third and fourth cases, which generally makes the first moment of $T_{k}$ difficult to derive mathematically. To tackle this issue, we resort to the recursive method applied in \cite{b8} and evaluate the first moment of $T_{k}$ as \eqref{Tsp1} at the top of the next page. Note that the four terms on the right hand side of \eqref{Tsp1} correspond to the above four cases, respectively, and $T'_{k}$ is the time duration between the preemption time (i.e., the generation time of the second status update after $t'_{k-1}$) and the arrival time of the $k$th received update at $D$. As $T_{k}$ is defined as the time duration between the generation time of the first status update after $t'_{k-1}$ and the arrival time of the $k$th received update at $D$, following the idea of recursion, we have $\mathbb{E}[T_{k}]=\mathbb{E}\big[T'_{k}\big]$. After some manipulations by applying \cite[Eqs. (0.112) and (0.113)]{b7}, we have \begin{equation}\label{Tsp2} \mathbb{E}[T_{k}]=\frac{(1-\alpha)+\beta\cdot P'_{2}}{P_{1}(1-\alpha)+\gamma}, \end{equation} where $P'_{2} = P_{2}/(1-P_{2})$. By combining $\mathbb{E}[W_{k}]=(1-p)/p$ and \eqref{Tsp2}, we now attain a closed-form expression of the term $\mathbb{E}[Z_{k}]$, given by \begin{equation}\label{Zsp} \begin{aligned} \mathbb{E}[Z_{k}]=\mathbb{E}[W_{k}]+\mathbb{E}[T_{k}]=\frac{(1-\alpha)(1-\beta)}{p\big[P_{1}(1-\alpha)+\gamma\big]}. \end{aligned} \end{equation} \subsubsection{Second Moment of the Interdeparture Time $\mathbb{E}\big[Z_{k}^{2}\big]$}The second moment of the interdeparture time $Z_k$ can be expressed as \begin{equation}\label{Z^2sp} \mathbb{E}\big[Z_k^2\big]\!\!=\!\mathbb{E}\big[(W_{k}+T_{k})^2\big]\!\!=\!\mathbb{E}\big[W_{k}^{2}\big]+2\mathbb{E}[W_{k} T_{k}]+\mathbb{E}\big[T_{k}^{2}\big]. \end{equation} It is readily to find that $W_{k}$ and $T_{k}$ are independent. Thus, we have $\mathbb{E}[W_{k}T_{k}]=\mathbb{E}[W_{k}]\cdot \mathbb{E}[T_{k}]$. As $W_{k}$ follows a geometric distribution with parameter $p$, we have $\mathbb{E}\big[W_{k}^2\big]=(p^2-3p+2)/p^2$. In order to evaluate $\mathbb{E}\big[Z_{k}^2\big]$, the only remaining task is to calculate $\mathbb{E}\big[T_{k}^2\big]$. \begin{figure*} \begin{equation}\label{T^2sp1} \resizebox{.99\hsize}{!}{$\begin{aligned} \mathbb{E}\big[T_{k}^{2}\big]\!=\!\!&\ \sum_{l=1}^{\infty}P_{l}\!\cdot\! l^2 \!+\! \sum_{n=1}^{\infty}\!\sum_{m=1}^{\infty}\!P_{mn}\!\cdot\! \big(m^2\!+\!2mn\!+\!n^2\big) \!+\!\sum_{l=1}^{\infty}\!\bigg[\!(1\!-\!P_{1})^{l}(1\!-\!P_{2})^{l}(1\!-\!p)^{l-1}p \!\cdot\!\Big(l^2\!+\!2l\!\cdot\!\mathbb{E}\big[T_{k}\big]\!+\!\mathbb{E}\big[T_{k}^{2}\big]\Big)\!\bigg]\\ &\,\!+\! \sum_{n=0}^{\infty}\!\sum_{m=1}^{\infty}\!\bigg[\!(1\!-\!P_{1})^{m}(1\!-\!P_{2})^{m-1}P_{2}(1\!-\!p)^{m-1} (1\!-\!p)^{n}(1\!-\!P_{3})^{n}p \!\cdot\! \Big(\!m^2\!+\!n^2\!+\!\mathbb{E}\big[T_{k}^{2}\big]\! +\!2mn\!+\!2m\!\cdot\!\mathbb{E}[T_{k}]\!+\!2n\!\cdot\!\mathbb{E}[T_{k}]\!\Big)\!\bigg]. \end{aligned}$} \vspace{-0.05cm} \end{equation} \vspace{-0.45cm} \noindent\rule[0\baselineskip]{\textwidth}{0.4pt} \end{figure*} Similar to \eqref{Tsp1}, the second moment of $T_k$ can be evaluated as \eqref{T^2sp1} at the top of the next page. Similar to the process of obtaining \eqref{Tsp2} from \eqref{Tsp1}, we can rewrite $\mathbb{E}\big[T_{k}^2\big]$ as \begin{equation}\label{T^2sp2} \resizebox{.98\hsize}{!}{$\begin{aligned} \mathbb{E}\big[T_{k}^2\big]\!= &\,\frac{1}{(1-\alpha)(1-\beta)-(1-\alpha)\beta\cdot p'-\beta\cdot p'\cdot P'_{2}}\\ &\times\!\frac{1}{(1-\alpha)(1-\beta)}\\ &\times\!\bigg\{\!(1-\alpha)^2(1+\beta)+(3-\alpha-\beta-\alpha\beta)\beta\cdot P'_{2}\\ &\qquad\!\!+2\mathbb{E}[T_{k}]\!\cdot\!\Big[(1\!-\!\alpha)^2\beta\!\cdot \!p'\!+\!(1\!-\!\alpha\beta)\beta\!\cdot\! p'\!\cdot\! P'_{2} \Big]\!\bigg\}, \end{aligned}$} \end{equation} where $p'=p/(1-p)$. \subsubsection{Average AoI} By substituting the terms derived in \eqref{Ssp2}, \eqref{Tsp2}, \eqref{Zsp}, \eqref{Z^2sp} and \eqref{T^2sp2} into \eqref{aoisp3}, the exact closed-form expression of the average AoI for the SP-AoR protocol can be presented in the following theorem. \begin{theorem}\label{Theorem 1} The average AoI of the SP-AoR protocol is given by \begin{equation} \bar{\Delta}_{SP}\!=\!\frac{\big[1\!-\!(1\!-\!p)(1\!-\!P_{3})\big]\!\cdot\!\big[1\!-\!(1\!-\!p)(1\!-\!P_{1})(1\!-\!P_{2})\big]}{p\!\cdot\!\big[pP_{1}\!+\!(1\!-\!p)P_{3}\!-\!(1\!-\!p)(1\!-\!P_{1})(1\!-\!P_{2})P_{3}\big]}. \end{equation} \end{theorem} \subsection{Optimization of Average AoI} Since the channel gain of the relay links is generally better than that of the direct link in cooperative communication systems, we assume that $0<P_{1}<P_{2}<1$ and $0<P_{1}<P_{3}<1$ in the optimization. We then acquire the optimal generation probability $p$ that minimizes the average AoI given by the following theorem. \begin{theorem} \label{Theorem 2} {The optimal generation probability that minimizes the average AoI of the SP-AoR protocol is given by \begin{equation}\label{psp} p^*_{SP}\!=\!\left\{ \begin{aligned} &\frac{-\!\lambda\!+\!\sqrt{\lambda^2\!-\!4\mu \xi}}{2\mu},\\ &\quad \mathrm{if} \ 0\!<\!P_{1}\!<\!\frac{P_{2}\!+\!P_{2}P_{3}\!-\!\sqrt{(P_{2}\!-\!P_{2}P_{3})^2\!+\!4P_{2}P_{3}}}{2(P_{2}\!-\!1)},\\ &1, \\ &\quad \mathrm{if} \ \frac{P_{2}\!+\!P_{2}P_{3}\!-\!\sqrt{(P_{2}\!-\!P_{2}P_{3})^2\!+\!4P_{2}P_{3}}}{2(P_{2}\!-\!1)}\!<\!P_{1}\!<\!1, \end{aligned} \right. \end{equation} \noindent where $\lambda\!=\!-2P_{3}(P_{1}\!+\!P_{2}\!-\!P_{1}P_{2})(P_{1}\!-\!P_{1}P_{3}\!-\!P_{2}P_{3}\!+\!P_{1}P_{2}P_{3})$, $\mu\!=\!P_{2}P_{3}(1\!-\!P_{2}P_{3})\!-\!P_{1}^2(1\!-\!P_{2})(1\!-\!P_{3})^2\!-\!P_{1}P_{2}P_{3}^2(1\!-\!P_{2})(2\!-\!P_{1})\!-\!P_{1}P_{2}(1\!-\!P_{3})$ and $\lambda^2\!-\!4\mu \xi\!=\!4P_{2}P_{3}^2(P_{3}\!-\!P_{1})(1\!-\!P_{1})(P_{1}\!+\!P_{2}\!-\!P_{1}P_{2})^2$.} \end{theorem} \begin{proof} See Appendix \ref{prof3}. \end{proof} \begin{remark} \label{remark1} {For the second case in Theorem \ref{Theorem 2}, the average AoI is minimized by setting $p=1$ and it is given by \begin{equation}\label{SP_AoI} \bar\Delta_{SP}^{min}=\frac{1}{P_{1}}. \end{equation} Note that in the considered system, the minimum possible time required for a successful status update transmission through the $S$-$D$ link is one time slot, while that through the $S$-$R$-$D$ link is at least two time slots. Therefore, when the transmission success probability of the $S$-$D$ link (i.e., $P_{1}$) is relatively large, having more status updates successfully delivered through the $S$-$D$ link is beneficial to reduce the average AoI. If the generation probability of the status updates is 1, S always has a new status update to transmit (i.e., the generate-at-will model \cite{b9}). This means that in the SP-AoR protocol, the update received by $R$ in the previous time slot is always preempted. As a result, all the status updates received by $D$ can only come from the $S$-$D$ link, which minimizes the average AoI. On the other hand, for the first case in Theorem \ref{Theorem 2}, the transmission success probability of the $S$-$D$ link is relatively small compared to the second case. Hence, the updates successfully delivered through the $S$-$R$-$D$ link also have a significant contribution on minimizing the average AoI. As mentioned above, if the generation probability is 1, the updates can only be successfully delivered to $D$ through the $S$-$D$ link. Obviously, this is no longer optimal for minimizing the average AoI in this case, which means that $p=1$ should not be the optimal status generation probability to minimize the average AoI.} \end{remark} \vspace{-0.3cm} \section{Relay-Prioritized AoR Protocol} In this section, a low-complexity relay-prioritized AoR (RP-AoR) protocol is proposed to reduce the AoI of the considered system. Based on the analysis of the AoI evolution, we derive the closed-form expression of the average AoI for the RP-AoR protocol. The optimal status generation probability $p$ is also analyzed to minimize the average AoI. \vspace{-0.2cm} \subsection{Protocol Description} Based on Theorem \ref{Theorem 2} and Remark \ref{remark1}, if the considered system suffers from severe channel fading on the $S$-$D$ link while the generation of new status updates at $S$ is frequent, the SP-AoR protocol may not have good performance in reducing the AoI. Inspired by this case, we propose the RP-AoR protocol, in which the retransmission from $R$ will not be preempted by a new status update arrival at $S$. Different from the SP-AoR protocol, if $R$ has a status update to forward, $S$ coordinates the system to keep transmitting with $\mathbf{O}_{\mathbf{R}}$ until it receives an ACK from $D$ (i.e., the forwarded update is successfully received at $D$). After the reception of the ACK, if $S$ has a fresher status update than that at $D$, $S$ coordinates the system to transmit with $\mathbf{O}_{\mathbf{S}}$. Otherwise, the considered system is coordinated by $S$ to choose $\mathbf{O}_{\mathbf{N}}$. \vspace{-0.3cm} \subsection{Analysis of Average AoI} For the ease of understanding the AoI evolution of the RP-AoR protocol, we illustrate an example staircase path for 14 consecutive time slots with an initial value of one in Fig. 2. Note that $t_k$, $t_k'$, $t_*$, $S_k$, $T_k$, $Z_k$ and $W_k$ have the same definitions as those in Fig. 1. To facilitate the calculation of the AoI for the RP-AoR protocol, we further denote by $H_k$ the time that the $k$th status update received by $D$ waits in the system before being served, and denote by $Y_k$ the total time that the $k$th update received by $D$ spends in the system. For convenience, we refer to the system where the local AoI at neither $S$ nor $R$ is lower than that at $D$ (i.e., neither $S$ nor $R$ has a fresher status update than that at $D$ to transmit) as an empty system in the rest of this section. \begin{figure} \centering \includegraphics[width=0.9\linewidth]{aoi_rp_revised} \caption{Sample staircase path of the AoI evolution for the RP-AoR protocol. We use $S\!\rightarrow\! D$, $S\!\rightarrow\! R$, $R\!\rightarrow\! D$, and Failure to denote the successful transmission through the $S$-$D$ link, the successful transmission through the $S$-$R$ link, the successful transmission through the $R$-$D$ link, and the failed transmission, respectively. Moreover, we use $\bullet$, {\scriptsize{$\triangle$}}, and $*$ to denote the events that none of the links are active, the $S$-$R$ link and the $S$-$D$ link are active, and the $R$-$D$ link is active, respectively.} \label{fig:aoirp} \vspace{-0.4cm} \end{figure} Similar to the process of obtaining \eqref{aoisp2}, we can express the average AoI of the RP-AoR protocol as \begin{equation}\label{aoirp1} \bar{\Delta}_{RP}=\frac{\mathbb{E}[Y_{k-1}Z_{k}]}{\mathbb{E}[Z_{k}]}+\frac{\mathbb{E}[Z_{k}^2]}{2\mathbb{E}[Z_{k}]}-\frac{1}{2}. \end{equation} Note that in the RP-AoR protocol, if there is a status update waiting for transmission (i.e., the system is not empty) at $t_{k-1}'$, the $(k-1)$th status update received by $D$ can only be transmitted through the $S$-$R$-$D$ link. However, if the system is empty at $t_{k-1}'$, the $(k-1)$th status update received by $D$ can be transmitted through either the $S$-$D$ link or the $S$-$R$-$D$ link. Therefore, for the two system states at $t_{k-1}'$, the distributions of the corresponding service time $S_{k-1}$ are different. In terms of the interdeparture time $Z_k$, it is affected by whether the $(k-1)$th status update received by $D$ leaves behind an empty system. As shown in Fig. 2, the system is not empty at $t_2'$, but empty at $t_4'$. During the interdeparture time $Z_3$, the system directly starts the service with the update left in the system at $t_2'$, while the system needs to wait for a status update generation to start the transmission within $Z_5$. This indicates that the system state at $t_{k-1}'$ determines whether the interdeparture time $Z_k$ includes the system waiting time $W_k$, and thus affects the distribution of $Z_k$. Based on the above analysis, it is apparent that the service time $S_{k-1}$ and the interdeparture time $Z_k$ are not independent in the RP-AoR protocol. As $Y_{k-1}=H_{k-1}+S_{k-1}$, we can find that $Y_{k-1}$ and $Z_k$ are not independent as well. To obtain the average AoI of the RP-AoR protocol, we derive the terms $\mathbb{E}[Y_{k-1}Z_{k}]$, $\mathbb{E}[Z_k]$ and $\mathbb{E}[Z_k^2]$ in the following. \subsubsection{Stationary Distribution of System State} Prior to deriving the terms in the average AoI expression, we first need to find the stationary distribution of the system state. We define $v(t) \triangleq \big(s(t), r(t)\big)$ as the system state of the considered cooperative system at the end of time slot $t$, where $s(t)$ indicates whether the local AoI at $S$ is lower than that at both $R$ and $D$ (i.e., whether $S$ has the freshest status update in the system to broadcast), and $r(t)$ indicates whether the local AoI at $R$ is lower than that at $D$ (i.e., whether $R$ has a fresher status update than that at $D$ to forward). Specifically, $s(t)=0$ and $s(t)=1$ indicate that at the end of time slot $t$, the status update at $S$ is not the freshest in the system and $S$ has the freshest status update in the system, respectively. Moreover, $r(t)=0$ and $r(t)=1$ indicate that at the end time slot $t$, $R$ has no fresher status updates than that at $D$ to forward, and $R$ has a fresher status update than that at $D$ to forward, respectively. Fig. \ref{Markov} depicts the state transition diagram. Based on the state transition, we can find that $\{v(t), t=1,2,...\}$ is an irreducible, positive-recurrent embedded Markov chain. \begin{figure} \centering \includegraphics[width=0.9\linewidth]{markov_chain} \caption{Markov chain for the system state $v(t)$ of the considered cooperative IoT system.} \label{Markov} \vspace{-0.4cm} \end{figure} With the transition probabilities in Fig. \ref{Markov}, we derive the stationary distribution of the Markov chain for the RP-AoR protocol, given by \begin{subequations} \begin{equation} \pi_{0,0}=\frac{P_3\cdot\left[pP_1+(1-p)P_3\right]}{P_3(1-\alpha)(1+\beta)+p^2P_2(1-P_1)}, \end{equation} \begin{equation} \pi_{0,1}=\frac{pP_2P_3(1-P_1)}{P_3(1-\alpha)(1+\beta)+p^2P_2(1-P_1)}, \end{equation} \begin{equation} \pi_{1,0}=\frac{p^2P_3(1-P_1)+pP_3^2\beta}{P_3(1-\alpha)(1+\beta)+p^2P_2(1-P_1)}, \end{equation} \begin{equation} \pi_{1,1}=\frac{p^2P_2(1-P_1)(1-P_3)}{P_3(1-\alpha)(1+\beta)+p^2P_2(1-P_1)}, \end{equation} \end{subequations} where $\alpha$ and $\beta$ are defined in Section \ref{3B}. \subsubsection{First Moment of the Interdeparture Time $\mathbb{E}[Z_k]$} To evaluate $\mathbb{E}[Z_{k}]$, we condition on whether the $(k-1)$th status update received by $D$ leaves behind an empty system. We denote this event as $\Upsilon_{k-1}$ and its complement as $\bar{\Upsilon}_{k-1}$. Based on the Bayes formula, the probability of $\Upsilon_{k-1}$ can be expressed as \begin{equation}\label{Pempt} \mathrm{Pr}(\Upsilon_{k-1})=\frac{\mathrm{Pr}(A,B)}{\mathrm{Pr}(A)}, \end{equation} where event $A$ denotes that $D$ receives a status update in time slot $t$, and event $B$ denotes that the reception at $D$ leaves behind an empty system. In terms of the denominator, event $A$ occurs in four cases, which have different system states $v'$ at the end of the previous time slot (i.e., time slot $t-1$) and different corresponding conditions during the current time slot (i.e., time slot $t$): $(a)$ When $v'=(0,0)$, a new status update is generated at $S$ and successfully received by $D$ through the $S$-$D$ link during the current time slot; $(b)$ When $v'=(0,1)$, the update stored at $R$ is successfully forwarded to $D$ during the current time slot; $(c)$ When $v'=(1,0)$, a status update at $S$ is transmitted to $D$ through the $S$-$D$ link during the current time slot; $(d)$ When $v'=(1,1)$, the update stored at $R$ is successfully forwarded to $D$ during the current time slot. In terms of the numerator, when event $B$ occurs together with event $A$, some of the above cases no longer meet the requirements. Specifically, if the successful reception at $D$ is through the $R$-$D$ link, the case where $S$ has the freshest status update in the system at the time of the reception are no longer applicable. Therefore, it is obvious that case $(d)$ will not appear in the calculation of the numerator. In addition, in case $(b)$, there should be no new status updates generated at $S$ during the forward by $R$. Based on the above analysis, we can rewrite \eqref{Pempt} as \begin{equation}\label{P_empty} \begin{aligned} \mathrm{Pr}(\Upsilon_{k-1})&=\frac{\pi_{0,0}\cdot pP_1+\pi_{0,1}\cdot (1-p)P_3+\pi_{1,0}\cdot P_1}{\pi_{0,0}\cdot pP_1+\pi_{0,1}\cdot P_3+\pi_{1,0}\cdot P_1+\pi_{1,1}\cdot P_3}\\ &=\frac{pP_1+P_3(1-p-\beta)}{(1-\alpha)\cdot[1-(1-P1)(1-P2)]}, \end{aligned} \end{equation} and $\mathrm{Pr}(\bar{\Upsilon}_{k-1})=1-\mathrm{Pr}(\Upsilon_{k-1})$. \begin{figure*} \begin{equation}\label{T} \begin{aligned} \mathbb{E}[T_k]&=\sum_{l=1}^{\infty}(1-p)^{l-1}(1-P_1)^{l-1}(1-P_2)^{l-1}P_1\cdot l\\ &\quad + \sum_{n=1}^{\infty}\sum_{m=1}^{\infty}(1-p)^{m-1}(1-P1)^m(1-P_2)^{m-1}P_2(1-P_3)^{n-1}P_3\cdot (m+n)\\ &\quad +\sum_{l=1}^{\infty}(1-P_1)^l(1-P_2)^l(1-p)^{l-1}p\cdot \big(l+\mathbb{E}\big[T_k'\big]\big). \end{aligned} \end{equation} \vspace{-0.3cm} \noindent\rule[0\baselineskip]{\textwidth}{0.4pt} \end{figure*} Under the condition of $\Upsilon_{k-1}$, the system is empty at $t_{k-1}'$. Therefore, the corresponding interdeparture time $Z_k$ is the sum of the system waiting time for the generation of the first status update after $t_{k-1}'$ and the system transmission time from the generation to $t_k'$. We thus have $\mathbb{E}[Z_k|\Upsilon_{k-1}]=\mathbb{E}[W_k|\Upsilon_{k-1}]+\mathbb{E}[T_k|\Upsilon_{k-1}]$. Similarly, the first moment of the interdeparture time conditioned on $\bar{\Upsilon}_{k-1}$ can be expressed as $\mathbb{E}\big[Z_k|\bar{\Upsilon}_{k-1}\big]=\mathbb{E}\big[T_k|\bar{\Upsilon}_{k-1}\big]$. In terms of $\mathbb{E}[Z_k|\Upsilon_{k-1}]$, the waiting time $W_k$ only depends on the generation probability $p$ since the $(k-1)$th status update received by $D$ leaves behind an empty system. As the status updates are generated according to a Bernoulli process, $W_{k}$ conditioned on $\Upsilon_{k-1}$ follows a geometric distribution with parameter $p$, and its first moment can be readily given by $\mathbb{E}[W_k|\Upsilon_{k-1}]=(1-p)/p$. We then move on to the calculation of the terms $\mathbb{E}[T_k|\Upsilon_{k-1}]$ and $\mathbb{E}\big[T_k|\bar{\Upsilon}_{k-1}\big]$. Under both conditions of $\Upsilon_{k-1}$ and $\bar{\Upsilon}_{k-1}$, $T_k$ behaves as the following three possible cases: $(a)$ The update is successfully received by $D$ through the $S$-$D$ link without being preempted; $(b)$ The update is successfully received by $D$ through the $S$-$R$-$D$ link without being preempted; $(c)$ The update is preempted by a new status update before being successfully received by either $R$ or $D$, and the new update may be preempted by multiple new updates. Therefore, the first moment of $T_{k}$ is the same under both conditions and we have $\mathbb{E}[T_k|\Upsilon_{k-1}]=\mathbb{E}\big[T_k|\bar{\Upsilon}_{k-1}\big]=\mathbb{E}[T_k]$. Based on the above possible cases, $\mathbb{E}[T_k]$ can be expressed by \eqref{T} at the top of the next page. After some manipulations by applying the recursive method \cite{b8} and the finite sum equations given in \cite[Eqs. (0.112) and (0.113)]{b7}, we have \begin{equation}\label{T_simplify} \mathbb{E}[T_k]=\frac{P_3+P_2(1-P_1)}{P_3[1-(1-P_1)(1-P_2)]}. \end{equation} By combing $\mathbb{E}[W_k|\Upsilon_{k-1}]=(1-p)/p$ and \eqref{T_simplify}, we attain closed-form expressions for the first moment of $Z_k$, given by \begin{subequations}\label{Z} \begin{equation} \mathbb{E}\big[Z_{k}| \bar{\Upsilon}_{k-1}\big]=\frac{P_2(1-P_1)+P_3}{P_3[1-(1-P_1)(1-P_2)]}, \end{equation} and \begin{equation} \mathbb{E}[Z_{k}|\Upsilon_{k-1}]=\frac{1-p}{p}+\mathbb{E}\big[Z_{k}| \bar{\Upsilon}_{k-1}\big]. \end{equation} \end{subequations} \subsubsection{Second Moment of the Interdeparture Time $\mathbb{E}\big[Z_{k}^{2}\big]$} Recall that under the conditions of $\Upsilon_{k-1}$ and $\bar{\Upsilon}_{k-1}$, we have $Z_k=W_k+T_k$ and $Z_k=T_k$, respectively. Therefore, the corresponding second moment of $Z_k$ can be expressed as \begin{subequations}\label{Z^2} \begin{equation} \resizebox{.98\hsize}{!}{$\begin{aligned} \mathbb{E}\big[Z_k^2|\Upsilon_{k-1}\big]&\!=\!\mathbb{E}\big[(W_k\!+\!T_k)^2|\Upsilon_{k-1}\big]\\ &\!=\!\mathbb{E}\big[W_k^2|\Upsilon_{k-1}\big]\!+\!2\mathbb{E}[W_kT_k|\Upsilon_{k-1}]\!+\!\mathbb{E}\big[T_k^2|\Upsilon_{k-1}\big]. \end{aligned}$} \end{equation} and \begin{equation} \mathbb{E}\big[Z_k^2|\bar{\Upsilon}_{k-1}\big]=\mathbb{E}\big[T_k^2|\bar{\Upsilon}_{k-1}\big]. \end{equation} \end{subequations} It is readily to find that $W_k$ and $T_k$ are conditionally independent under $\Upsilon_{k-1}$. Thus, we have $\mathbb{E}[W_kT_k|\Upsilon_{k-1}]=\mathbb{E}[W_k|\Upsilon_{k-1}]\cdot \mathbb{E}[T_k|\Upsilon_{k-1}]$. As $W_k$ follows a geometric distribution with parameter $p$, we have $\mathbb{E}\big[W_k^2|\Upsilon_{k-1}\big]\!=\!(p^2-3p+2)/p^2$. In order to evaluate $\mathbb{E}\big[Z_k^2\big]$, the only remaining task is to calculate $\mathbb{E}\big[T_k^2|\Upsilon_{k-1}\big]$ and $\mathbb{E}\big[T_k^2|\bar{\Upsilon}_{k-1}\big]$. \begin{figure*} \begin{equation}\label{T^2} \begin{aligned} \mathbb{E}\big[T_k^2\big]&=\sum_{l=1}^{\infty}(1-p)^{l-1}(1-P_1)^{l-1}(1-P_2)^{l-1}P_1\cdot l^2\\ &\quad + \sum_{n=1}^{\infty}\sum_{m=1}^{\infty}(1-p)^{m-1}(1-P1)^m(1-P_2)^{m-1}P_2(1-P_3)^{n-1}P_3\cdot (m^2+2mn+n^2)\\ &\quad +\sum_{l=1}^{\infty}(1-P_1)^l(1-P_2)^l(1-p)^{l-1}p\cdot \left(l^2+2l\cdot \mathbb{E}[T_k]+\mathbb{E}\big[(T_k')^2\big]\right). \end{aligned} \end{equation} \vspace{-0.4cm} \noindent\rule[0\baselineskip]{\textwidth}{0.4pt} \end{figure*} Similar to \eqref{T}, $\mathbb{E}\big[T_k^2| \Upsilon_{k-1}\big]$ and $\mathbb{E}\big[T_k^2|\bar{\Upsilon}_{k-1}\big]$ have the same value, which can be expressed by \eqref{T^2} at the top of the next page. Similar to the process of obtaining \eqref{T_simplify} from \eqref{T}, we can rewrite $\mathbb{E}\big[T_k^2\big]$ as \begin{equation}\label{T^2_simplify} \resizebox{.98\hsize}{!}{$\begin{aligned} \mathbb{E}\big[T_k^2\big]\!=\!\ &\frac{1}{P_3^2\!\cdot\![1\!-\!(1\!-\!P_1)(1\!-\!P_2)]^2}\\ &\times\!\Big\{\!P_2^2\!\cdot\!(1\!-\!P_1)^2\!\cdot\!(2\!-\!P_3)\!+\!P_3^2\!\cdot\![1\!+\!(1\!-\!P_1)(1\!-\!P_2)]\\ &\quad \ +\!P_2(2\!-\!P_1)\!\cdot\![1\!-\!(1\!-\!P_1)(1\!-\!P_3)]\!-\!P_1^2P_2\Big\}. \end{aligned}$} \end{equation} Based on the above analysis, the second moment of $Z_k$ can be expressed as \begin{subequations}\label{Z^2_final} \begin{equation} \resizebox{.98\hsize}{!}{$\begin{aligned} \mathbb{E}\big[Z_{k}^2|\bar{\Upsilon}_{k-1}\big]\!=\!\ &\frac{1}{P_3^2\!\cdot\![1\!-\!(1\!-\!P_1)(1\!-\!P_2)]^2}\\ &\!\times\!\Big\{\!P_2^2\!\cdot\!(1\!-\!P_1)^2\!\cdot\!(2\!-\!P_3)\!+\!P_3^2\!\cdot\![1\!+\!(1\!-\!P_1)(1\!-\!P_2)]\\ &\quad \ +\!P_2(2\!-\!P_1)\!\cdot\![1\!-\!(1\!-\!P_1)(1\!-\!P_3)]\!-\!P_1^2P_2\Big\}, \end{aligned}$} \end{equation} and \begin{equation} \begin{aligned} \mathbb{E}\big[Z_{k}^2|\Upsilon_{k-1}\big]&=\mathbb{E}\big[Z_{k}^2|\bar{\Upsilon}_{k-1}\big]+\frac{p^2-3p+2}{p^2}\\ &\,\quad +\frac{(2-2p)\cdot[P_2(1-P_1)+P_3]}{p P_3\cdot[1-(1-P_1)(1-P_2)]}. \end{aligned} \end{equation} \end{subequations} \subsubsection{$\mathbb{E}[Y_{k-1}Z_k]$} We finally evaluate the term $\mathbb{E}[Y_{k-1}Z_k]$. The total time that the $(k-1)$th status update received by $D$ spends in the system is the sum of its waiting time before being served and its service time. Therefore, we have $Y_{k-1}=H_{k-1}+S_{k-1}$. Under the condition of $\Upsilon_{k-1}$, the first moment of $Y_{k-1}$ can be expressed by $\mathbb{E}[Y_{k-1}|\Upsilon_{k-1}]=\mathbb{E}[H_{k-1}|\Upsilon_{k-1}]+\mathbb{E}[S_{k-1}|\Upsilon_{k-1}]$. To further compute $\mathbb{E}[Y_{k-1}Z_k|\Upsilon_{k-1}]$, we have the following lemma. \begin{lemma}\label{lemma2} In the RP-AoR protocol, if the $(k-1)$th status update received by $D$ leaves behind an empty system, the total time that the $(k-1)$th status update received by $D$ spends in the system is independent of the interdeparture time between the $(k-1)$th and the $k$th received status update at $D$ such that \begin{equation} \label{lemma2equation} \mathbb{E}[Y_{k-1}Z_k|\Upsilon_{k-1}]=\mathbb{E}[Y_{k-1}|\Upsilon_{k-1}]\cdot \mathbb{E}[Z_k|\Upsilon_{k-1}]. \end{equation} \end{lemma} \begin{proof} Since we have $Y_{k-1}=H_{k-1}+S_{k-1}$, Lemma \ref{lemma2} holds if the interdeparture time $Z_k$ is independent of both $H_{k-1}$ and $S_{k-1}$ under the condition of $\Upsilon_{k-1}$. In the RP-AoR protocol, $H_{k-1}$ is conditioned on whether the system is empty when the generation of the $(k-1)$th status update received by $D$ occurs, but as we mentioned, $Z_k$ is conditioned on whether the $(k-1)$th update received by $D$ leaves behind an empty system. This indicates that $Z_k$ is independent of $H_{k-1}$. Similar to the proof of Lemma \ref{lemma1}, we can readily prove that $Z_k$ is conditionally independent of $S_{k-1}$ under $\Upsilon_{k-1}$. This completes the proof. \end{proof} \noindent Similarly, we can have $\mathbb{E}\big[Y_{k-1}Z_k|\bar{\Upsilon}_{k-1}\big]=\mathbb{E}\big[Y_{k-1}|\bar{\Upsilon}_{k-1}\big]\cdot \mathbb{E}\big[Z_k|\bar{\Upsilon}_{k-1}\big]$, where $\mathbb{E}\big[Y_{k-1}|\bar{\Upsilon}_{k-1}\big]=\mathbb{E}\big[H_{k-1}|\bar{\Upsilon}_{k-1}\big]+\mathbb{E}\big[S_{k-1}|\bar{\Upsilon}_{k-1}\big]$ and $\mathbb{E}\big[Z_k|\bar{\Upsilon}_{k-1}\big]=\mathbb{E}\big[T_k|\bar{\Upsilon}_{k-1}\big]$. The proof is similar to the above and is thus omitted for brevity. Since $\mathbb{E}[Z_k|\Upsilon_{k-1}]$ and $\mathbb{E}\big[Z_k|\bar{\Upsilon}_{k-1}\big]$ is derived in \eqref{Z}, the remaining tasks of calculating $\mathbb{E}[Y_{k-1}Z_{k}]$ are to evaluate $\mathbb{E}[Y_{k-1}|\Upsilon_{k-1}]$ and $\mathbb{E}\big[Y_{k-1}|\bar{\Upsilon}_{k-1}\big]$. Recall that we have $Y_{k-1}=H_{k-1}+S_{k-1}$. To compute $\mathbb{E}[Y_{k-1}]$, we first consider the packet waiting time before being served, i.e., $H_{k-1}$. As we mentioned, in the RP-AoR protocol, $H_{k-1}$ is conditioned on whether the system is empty when the generation of the $(k-1)$th status update received by $D$ occurs. In other words, it is conditioned on the system state when the $(k-2)$th update received by $D$ leaves the system, rather than the system state when the $(k-1)$th update received by $D$ leaves the system, which indicates that $\mathbb{E}[H_{k-1}|\Upsilon_{k-1}]=\mathbb{E}\big[H_{k-1}|\bar{\Upsilon}_{k-1}\big]=\mathbb{E}[H_{k-1}]$. Obviously, if the $(k-2)$th status update received by $D$ leaves the system empty, we have $H_{k-1}=0$. Otherwise, $H_{k-1}$ is determined by whether the update left in the system at $t_{k-2}'$ is successfully received by $D$. We denote by $\Theta$ the event that the left update is preempted during the transmission (i.e., not successfully received by $D$) and by $\bar{\Theta}$ its complement. The probability that the left update is preempted before the $j$th transmission starts can be expressed as \vspace{-0.01cm} \begin{equation} P_{preempt}=(1-p)^{j-1}(1-P_1)^{j-1}(1-P_2)^{j-1}p. \vspace{-0.01cm} \end{equation} Therefore, the probability of event $\Theta$ are given by \vspace{-0.01cm} \begin{equation} \mathrm{Pr}(\Theta)=\sum_{j=1}^{\infty}P_{preempt}=\frac{p}{1-\beta}, \vspace{-0.01cm} \end{equation} and $\mathrm{Pr}(\bar{\Theta})=1-\mathrm{Pr}(\Theta)$. Under the condition of $\Theta$, a fresher status update preempts the update left in the system and starts to be served without waiting. Thus, we can have $H_{k-1}=0$ conditioned on $\Theta$, and the only remaining task to evaluate $\mathbb{E}[H_{k-1}]$ is to calculate $\mathbb{E}\big[H_{k-1}|\bar{\Theta}\big]$. If an update is left in the system at $t_{k-2}'$, it can only be generated at $S$ after the $(k-2)$th status update received by $D$ has arrived at $R$. This means that $\mathbb{E}\big[H_{k-1}|\bar{\Theta}\big]$ is the residual transmission time of the $(k-2)$th update received by $D$ on the $R$-$D$ link. After the update left in the system at $t_{k-2}'$ is generated at $S$, the probability that the transmission on the $R$-$D$ link performs $n$ times can be expressed as \vspace{-0.02cm} \begin{equation} P_{n}=(1-p)^{n-1}(1-P_3)^{n-1}P_3. \vspace{-0.01cm} \end{equation} The corresponding first moment of the transmission time, i.e., $\mathbb{E}\big[H_{k-1}|\bar{\Theta}\big]$, can be calculated by \vspace{-0.01cm} \begin{equation} \mathbb{E}\big[H_{k-1}|\bar{\Theta}\big]=\frac{\sum_{n=1}^{\infty}P_n\cdot n}{\sum_{n=1}^{\infty}P_n}=\frac{1}{1-\alpha}. \end{equation} By conditioning on whether the $(k-2)$th status update received by $D$ leaves the system empty or not, we now evaluate the first moment of $H_{k-1}$ for the RP-AoR protocol, given by \begin{equation}\label{H} \begin{aligned} \mathbb{E}[H_{k-1}]\!=&\Big\{\mathbb{E}\big[H_{k-1}|\bar{\Theta}\big]\cdot \mathrm{Pr}\big(\bar{\Theta}\big)+0 \times \mathrm{Pr}(\Theta)\Big\}\times \mathrm{Pr}\big(\bar{\Upsilon}_{k-1}\big)\\ &\ +0 \times \mathrm{Pr}(\Upsilon_{k-1})\\ &\!\!\!\!\!\!=\frac{p P_2(1-p)(1-P_1)}{(1-\alpha)^2(1-\beta)}. \end{aligned} \end{equation} After the calculation of $\mathbb{E}[H_{k-1}]$, we then move on to the other component of $Y_{k-1}$, i.e., $S_{k-1}$. Under the condition of $\Upsilon_{k-1}$, the $(k-1)$th status update received by $D$ leaves behind an empty system. Therefore, the first moment of the service time $\mathbb{E}[S_{k-1}|\Upsilon_{k-1}]$ is composed of the average service time for the same two types of status updates as in the SP-AoR protocol. Based on \eqref{PL}$-$\eqref{Ssp2}, the first moment of the service time conditioned on $\Upsilon_{k-1}$ are given by \begin{equation}\label{S1} \mathbb{E}[S_{k-1}|\Upsilon_{k-1}]=\frac{1}{1-\beta}+\frac{1}{1-\alpha}\cdot\frac{\gamma}{P_{1}(1-\alpha)+\gamma}. \end{equation} Under the condition of $\bar{\Upsilon}_{k-1}$, the system is not empty when the $(k-1)$th status update received by $D$ leaves the system. This means that the status update must be transmitted through the $S$-$R$-$D$ link, and there must be fresher status updates generated at $S$ after it arrives at $R$. The first moment of the service time conditioned on $\bar{\Upsilon}_{k-1}$ can thus be expressed as \begin{equation}\label{RS1} \resizebox{.98\hsize}{!}{$\begin{aligned} \mathbb{E}\big[S_{k-1}| \bar{\Upsilon}_{k-1}\big]\!=\!\frac{\sum_{n=1}^{\infty}\!\sum_{m=1}^{\infty}\!P\!\left(S\!\rightarrow\! R\!\rightarrow\! D|\bar{\Upsilon}_{k-1}\right)\!\cdot\! (m\!+\!n)}{\sum_{n=1}^{\infty}\!\sum_{m=1}^{\infty}\!P\!\left(S\!\rightarrow\! R\!\rightarrow\! D|\bar{\Upsilon}_{k-1}\right)}, \end{aligned}$} \end{equation} where $m$ and $n$ are defined in Section \ref{3B}. $P\left(S\rightarrow R\rightarrow D|\bar{\Upsilon}_{k-1}\right)$ is the probability that the status update is received by $D$ after transmitting $(m+n)$ times conditioned on $\bar{\Upsilon}_{k-1}$, which can be expressed as \begin{equation} \begin{aligned} P\!\left(S\!\rightarrow \!R\!\rightarrow\! D|\bar{\Upsilon}_{k-1}\right)\!=\!\ &(1\!-\!p)^{m-1}(1\!-\!P_1)^m(1\!-\!P_2)^{m-1}P_2\\ &\!\times(1\!-\!P_3)^{n-1}P_3\left[1\!-\!(1\!-\!p)^n\right]. \end{aligned} \end{equation} By applying \cite[Eqs. (0.112) and (0.113)]{b7}, we can simplify \eqref{RS1} as \begin{equation}\label{S2} \mathbb{E}\big[S_{k-1}|\bar{\Upsilon}_{k-1}\big]=\frac{2}{P_3}+\frac{1}{1-\beta}-\frac{P_3^2(1-p)+p}{P_3(1-\alpha)}. \end{equation} Based on \eqref{H}, \eqref{S1}, and \eqref{S2}, we attain closed-form expressions for the first moment of $Y_{k-1}$, given by \begin{subequations} \label{Y} \begin{equation} \begin{aligned} \mathbb{E}\big[Y_{k-1}|\bar{\Upsilon}_{k-1}\big]=\ &\frac{pP_2(1-p)(1-P_1)}{(1-\alpha)^2(1-\beta)}+\frac{1}{1-\beta}\\ &\!+\frac{2}{P_3}-\frac{P_3^2(1-p)+p}{P_3(1-\alpha)}, \end{aligned} \end{equation} and \begin{equation} \begin{aligned} \mathbb{E}[Y_{k-1}|\Upsilon_{k-1}]=\ &\frac{pP_2(1-p)(1-P_1)}{(1-\alpha)^2(1-\beta)}+\frac{1}{1-\beta}\\ &+\frac{\gamma}{P_1(1-\alpha)^2+\gamma(1-\alpha)}. \end{aligned} \end{equation} \end{subequations} \subsubsection{Average AoI} Based on the above analysis, the exact closed-form expression of the average AoI for the RP-AoR protocol can be presented in the following theorem. \begin{theorem}\label{Theorem 3} The average AoI of the RP-AoR protocol is given by \begin{equation} \resizebox{.98\hsize}{!}{$\begin{aligned} \bar{\Delta}_{RP}&\!=\!\frac{1}{\mathbb{E}[Z_k|\Upsilon_{k-1}]\!\cdot\! \mathrm{Pr}(\Upsilon_{k-1})\!+\!\mathbb{E}\big[Z_k|\bar{\Upsilon}_{k-1}\big]\!\cdot\! [1\!-\!\mathrm{Pr}(\Upsilon_{k-1})]}\\ &\quad\!\times\Big\{\mathbb{E}[Y_{k-1}|\Upsilon_{k-1}]\cdot\mathbb{E}[Z_k|\Upsilon_{k-1}]\cdot \mathrm{Pr}(\Upsilon_{k-1})\\ &\quad\quad \quad \!\!\! +\mathbb{E}\big[Y_{k-1}|\bar{\Upsilon}_{k-1}\big]\cdot\mathbb{E}\big[Z_k|\bar{\Upsilon}_{k-1}\big]\cdot \big[1\!-\!\mathrm{Pr}(\Upsilon_{k-1})\big]\\\ &\quad \quad \quad \!\!\! +\frac{1}{2}\cdot \mathbb{E}\big[Z_k^2|\Upsilon_{k-1}\big]\cdot\mathrm{Pr}(\Upsilon_{k-1})\\ &\quad \quad \quad \!\!\!+\frac{1}{2}\cdot \mathbb{E}\big[Z_k^2|\bar{\Upsilon}_{k-1}\big]\cdot\big[1-\mathrm{Pr}(\Upsilon_{k-1})\big]\Big\}-\frac{1}{2}, \end{aligned}$} \end{equation} \noindent where $\mathrm{Pr}(\Upsilon_{k-1})$ is given in \eqref{P_empty}, $\mathbb{E}[Z_k|\Upsilon_{k-1}]$ and $\mathbb{E}\big[Z_k|\bar{\Upsilon}_{k-1}\big]$ are given in \eqref{Z}, $\mathbb{E}\big[Z_k^2|\Upsilon_{k-1}\big]$ and $\mathbb{E}\big[Z_k^2|\bar{\Upsilon}_{k-1}\big]$ are given in \eqref{Z^2_final}, and $\mathbb{E}[Y_{k-1}|\Upsilon_{k-1}]$ and $\mathbb{E}\big[Y_{k-1}|\bar{\Upsilon}_{k-1}\big]$ are given in \eqref{Y}. \end{theorem} \subsection{Optimization of Average AoI} The optimal generation probability $p$ that minimizes the average AoI of the RP-AoR protocol is given by the following theorem. \begin{theorem}\label{Theorem 4} In the RP-AoR protocol, the optimal generation probability that minimizes the average AoI is given by \begin{equation} p_{RP}^*=1. \end{equation} \end{theorem} \begin{proof} Recall that in the RP-AoR protocol, the system can have three transmission operations in each time slot, i.e., $\mathbf{O}_{\mathbf{S}}$, $\mathbf{O}_{\mathbf{R}}$ and $\mathbf{O}_{\mathbf{N}}$. If the system decides to transmit with $\mathbf{O}_{\mathbf{S}}$ in one time slot, generating new status update at $S$ in each slot (i.e., $p_{RP}^*=1$) ensures that the transmitted update is always the freshest. If the system chooses $\mathbf{O}_{\mathbf{R}}$ in one time slot, the forwarded update by $R$ will not be preempted by new status updates generated at $S$. In this case, $p_{RP}^*=1$ keeps the status update waiting for transmission at $S$ as fresh as possible. Furthermore, when the generation probability at $S$ is 1, $\mathbf{O}_{\mathbf{N}}$ will never be adopted by the system, which is apparently beneficial for the AoI minimization. This completes the proof. \end{proof} \begin{remark}\label{remark_2} For the RP-AoR protocol, the average AoI is minimized by setting $p=1$ (i.e., the generate-at-will model) and it is given by \begin{equation}\label{RP_AoI} \bar{\Delta}^{min}_{RP}\!=\!\frac{P_2(1\!-\!P_1)}{P_3(P_2\!+\!P_3\!-\!P_1P_2)}\!+\!\frac{P_2\!+\!P_3\!-\!P_1P_2}{P_3[1\!-\!(1\!-\!P_1)(1\!-\!P_2)]}. \end{equation} If the considered system adopts the generate-at-will model, by solving the simultaneous equations of \eqref{SP_AoI} and \eqref{RP_AoI}, we have: $(a)$ When $P_1<f(P_2,P_3)$, where $f(P_2,P_3)=\frac{2P_2+P_3+P_2P_3-\sqrt{P_2^2(P_3-2)^2+P_3(8P_2+5P_3-6P_2P_3)}}{4P_2-2}$, the RP-AoR protocol has a better AoI performance than the SP-AoR protocol; $(b)$ When $P_1>f(P_2,P_3)$, the SP-AoR protocol has a better AoI performance that the RP-AoR protocol. \end{remark} \section{Numerical Results and Discussions} In this section, we present simulation results to validate the theoretical analysis and the effectiveness of the two proposed AoR protocols in the considered cooperative IoT system. Each simulation curve presented in the section is averaged over $10^7$ time slots. We first plot the average AoI of the proposed AoR protocols and the optimal MDP policy against the generation probability $p$, as shown in Fig. \ref{simulation_1}, for different transmission success probabilities (i.e., $P1$, $P2$ and $P_3$). Specifically, we consider five combinations of $(P_1,P_2,P_3)$, which are $(0.2,0.3,0.3)$, $(0.2,0.3,0.8)$, $(0.2,0.8,0.3)$, $(0.2,0.8,0.8)$, and $(0.7,0.8,0.8)$, to represent the systems where all channels suffer from severe fading, both the $S$-$D$ link and the $S$-$R$ link suffer from severe fading while the $R$-$D$ link is in good condition, both the $S$-$D$ link and the $R$-$D$ link suffer from severe fading while the $S$-$R$ link is in good condition, the $S$-$D$ link suffers from severe fading while both the $S$-$R$ link and the $R$-$D$ link are in good condition, and all channels are in good condition, respectively. It can be observed that in all the cases, the simulation results of the average AoI for both the SP-AoR protocol and the RP-AoR protocol are consistent with the corresponding analytical results. This observation verifies the correctness of Theorems \ref{Theorem 1} and \ref{Theorem 3}. We can also observe that in Fig. \ref{simulation_1} (a), the optimal generation probability to minimize the average AoI of the SP-AoR protocol in the case of $(P_1,P_2,P_3)=(0.2,0.3,0.3)$, $(P_1,P_2,P_3)=(0.2,0.8,0.8)$, and $(P_1,P_2,P_3)=(0.7,0.8,0.8)$ are $p=1$, $p=0.616$, and $p=1$, respectively. In Fig. \ref{simulation_1} (b), the optimal generation probability of the SP-AoR protocol in the case of $(P_1,P_2,P_3)=(0.2,0.3,0.8)$ and $(P_1,P_2,P_3)=(0.2,0.8,0.3)$ are $p=0.662$ and $p=0.826$, respectively. The optimal generation probabilities coincide well with the results calculated by the formula in Theorem \ref{Theorem 2}. It is also worth mentioning that the average AoI of the RP-AoR protocol is minimized when $p=1$ in all the cases, which are consistent with Theorem \ref{Theorem 4}. \begin{figure} \centering \subfigure[\scriptsize{$(P_1, P_2, P_3)=(0.2,0.3,0.3), (0.2,0.8,0.8)$ and $(0.7,0.8,0.8)$}]{\includegraphics[width=0.85\linewidth]{fig_1}} \qquad\qquad \subfigure[\scriptsize{$(P_1, P_2, P_3)=(0.2,0.3,0.8)$ and $ (0.2,0.8,0.3)$}]{\includegraphics[width=0.85\linewidth]{fig_2}} \caption{Average AoI of the SP-AoR protocol, the RP-AoR protocol and the optimal MDP policy against the generation probability $p$ for different transmission success probabilities, i.e., $(P_1, P_2, P_3)$.} \label{simulation_1} \vspace{-0.5cm} \end{figure} Based on Fig. \ref{simulation_1}, we can see that the SP-AoR protocol and the RP-AoR protocol outperform each other in different cases. Note that in the considered cooperative IoT system, we can quickly determine which protocol to apply for better AoI performance with the help of the analytical results. More importantly, the protocol with better performance can achieve near-optimal performance compared with the optimal scheduling policy solved by the MDP tool. Specifically, the RP-AoR protocol has better AoI performance than the SP-AoR protocol when $(P_1, P_2,P_3)=(0.2,0.8,0.8)$ and $(P_1,P_2,P_3)=(0.2,0.3,0.8)$, as shown in Fig. \ref{simulation_1} (a) and Fig. \ref{simulation_1} (b), respectively. Also, the performance of the RP-AoR protocol is almost the same as that of the optimal MDP policy in both cases. This is because, in both cases, the $S$-$D$ link suffers from severe channel fading while the $R$-$D$ link has good channel condition. This means that it is difficult to successfully transmit status updates to $D$ through the $S$-$D$ link, while the status updates forwarded by $R$ have a high probability of being received by $D$. In such cases, even if a new status update is generated at $S$, the system should give the priority to $R$ for transmitting, which is consistent with the principle of the RP-AoR protocol. We can also observe that the SP-AoR protocol results in lower average AoI than the RP-AoR protocol in the case of $(P_1, P_2,P_3)=(0.2,0.3,0.3)$ and $(P_1, P_2,P_3)=(0.2,0.8,0.3)$, as shown in Fig. \ref{simulation_1} (a) and Fig. \ref{simulation_1} (b), respectively. The rationale behind this is that when neither $S$-$D$ link nor $R$-$D$ link has good channel condition, it is difficult for both $S$ and $R$ to successfully transmit status updates to $D$. Therefore, the SP-AoR protocol, in which $S$ has the priority to transmit newly generated status updates, is more beneficial for reducing the AoI at $D$ in such cases. In these two cases, although there is a performance gap between the SP-AoR protocol and the optimal MDP policy when the generation probability $p$ is large, the SP-AoR can still achieve near-optimal performance. In addition, as shown in Fig. \ref{simulation_1} (a), the SP-AoR protocol has a better AoI performance than the RP-AoR protocol when $(P_1,P_2,P_3)=(0.7,0.8,0.8)$, and the performance almost matches that of the optimal MDP policy. \begin{figure} \centering \includegraphics[width=0.85\linewidth]{simulation_2_c} \caption{AoI difference between the RP-AoR protocol and the SP-AoR protocol versus the transmission success probabilities $P_2$ and $P_3$ when $P_1=0.2$ and $p=0.8$.} \label{simulation_2} \vspace{-1cm} \end{figure} Fig. \ref{simulation_2} shows the AoI difference between the RP-AoR protocol and the SP-AoR protocol against the transmission success probabilities of the $S$-$R$ link and the $R$-$D$ link (i.e., $P_2$ and $P_3$) when $P_1=0.2$ and $p=0.8$. In the figure, if the AoI difference is less than 0, the RP-AoR protocol has a lower average AoI. Otherwise, the average AoI of the SP-AoR protocol is lower. It can be observed that when $P_3$ is greater than about 0.45, the RP-AoR protocol always has a better AoI performance. The rationale behind this is similar to what we explained in the case of $(P_1,P_2,P_3)=(0.2,0.8,0.8)$ and $(0.2,0.3,0.8)$ in Fig. \ref{simulation_1}. When $P_1=0.2$ and $P_3>0.45$, it is difficult to have successful status update transmission through the $S$-$D$ link, while the $R$-$D$ link has a higher probability of successfully forwarding status updates to $D$. Therefore, in this case, the updates successfully delivered to $D$ by $R$ have a significant contribution on minimizing the average AoI. Since it is assumed that $p=0.8$ (i.e., the generation of status updates at $S$ is frequent), in the SP-AoR protocol, the updates at $R$ will always be preempted by $S$ and cannot be transmitted to $D$ to effectively reduce the AoI. However, the RP-AoR protocol will not be affected by the frequent status update generation, which results in a better AoI performance than the SP-AoR protocol. We also investigate the average AoI of both proposed AoR protocols against the transmission success probability of the $S$-$D$ link (i.e., $P_1$) when the considered system adopts the generate-at-will model (i.e., $p=1$). As depicted in Fig. \ref{simulation_3}, we consider two cases with $P_2=P_3=0.3$ and $P_2=P_3=0.8$, respectively. Based on Remark \ref{remark1}, the average AoI of the SP-AoR protocol is only related to $P_1$ in the generate-at-will model. Thus, there is only one average AoI curve for the SP-AoR protocol in Fig. \ref{simulation_3}. It can be observed that in both cases, the RP-AoR curve has an intersection with the SP-AoR curve. Specifically, when $(P_2,P_3)=(0.3,0.3)$ and $(P_2,P_3)=(0.8,0.8)$, the intersections occur at $P_1=0.1701$ and $P_1=0.4624$, respectively, which are consistent with the results calculated by using the formula in Remark \ref{remark_2}. This indicates that if the considered system has a new status update at the beginning of each time slot, we can quickly determine which of the SP-AoR protocol and the RP-AoR protocol is better for reducing the average AoI of the considered system by simply comparing the values of $P_1$ and $f(P_2,P_3)$. \begin{figure} \centering \includegraphics[width=0.85\linewidth]{simulation_3} \caption{Average AoI of the SP-AoR protocol and the RP-AoR protocol versus the transmission success probability $P_1$ for different $(P_2, P_3)$ when the considered system adopts the generate-at-will model (i.e., $p=1$).} \label{simulation_3} \end{figure} \section{Conclusions} In this paper, we considered a cooperative IoT system, where the source timely reports randomly generated status updates to the destination with the help of a relay. Considering the limited capabilities of IoT devices, we devised two low-complexity AoR protocols, i.e., the SP-AoR protocol and the RP-AoR protocol, to reduce the AoI of the considered system. By analyzing the evolution of the instantaneous AoI, we derived the closed-form expressions of the average AoI for both proposed AoR protocols, which are functions of the generation probability of the status updates and the transmission success probability of each link. Based on the closed-form expressions, we further figured out the optimal generation probability of the status updates that minimizes the average AoI in both protocols. Simulation results validated our theoretical analysis, and demonstrated that the proposed protocols outperform each other under various system parameters. Note that based on the analytical results, we could quickly determine which protocol to apply for better AoI performance in the considered system. Furthermore, it was shown that the protocol with better performance can achieve near-optimal performance compared with the optimal scheduling policy solved by the MDP tool. \begin{appendices} \section{Proof of Theorem \ref{Theorem 2}} \label{prof3} Recall that $\bar{\Delta}_{SP}=\frac{[1-(1-p)(1-P_{3})]\cdot [1-(1-p)(1-P_{1})(1-P_{2})]}{p[pP_{1}+(1-p)P_{3}-(1-p)(1-P_{1})(1-P_{2})P_{3}]}$. To proceed, we derive the first-order derivative of $\bar\Delta_{SP}$ with respect to (w.r.t.) $p$. After some algebra manipulations, we have \begin{equation}\label{derisp} \frac{\partial \bar{\Delta}_{SP}}{\partial p}=\frac{\mu \cdot p^2+ \lambda \cdot p+\xi}{p^2\!\cdot\!\big[pP_{1}\!+\!(1\!-\!p)P_{3}\!-\!(1\!-\!p)(1\!-\!P_{1})(1\!-\!P_{2}P_{3})\big]^2}, \end{equation} where \begin{subequations} \begin{equation}\label{proof3xi} \resizebox{.99\hsize}{!}{$\begin{aligned} \mu\!= \!-&(P_{1}^2P_{2}^2P_{3}^2\!-\!2P_{1}^2P_{2}P_{3}^2\!+\!2P_{1}^2P_{2}P_{3}\!-\!P_{1}^2P_{2}\!+\!P_{1}^2P_{3}^2\! -\!2P_{1}^2P_{3}\!\\ &\,+\!P_{1}^2\! -\!2P_{1}P_{2}^2P_{3}^2\!+\!2P_{1}P_{2}P_{3}^2\!-\!P_{1}P_{2}P_{3}\!+\!P_{1}P_{2}\!+\!P_{2}^2P_{3}^2\!-\!P_{2}P_{3}), \end{aligned}$} \end{equation} \begin{equation}\label{proof3psi} \resizebox{.91\hsize}{!}{$\begin{aligned} \lambda\!=\, &2P_{1}^2P_{2}^2P_{3}^2\!-\!4P_{1}^2P_{2}P_{3}^2\!+\!2P_{1}^2P_{2}P_{3}\!+\!2P_{1}^2P_{3}^2\! -\!2P_{1}^2P_{3}\!\\ &\qquad\qquad\qquad-\!4P_{1}P_{2}^2P_{3}^2\!+\!4P_{1}P_{2}P_{3}^2\!-\!2P_{1}P_{2}P_{3}\!+\!2P_{2}^2P_{3}^2, \end{aligned}$} \end{equation} \begin{equation}\label{proof3omega} \resizebox{.99\hsize}{!}{$\begin{aligned} \xi\!=\!-(P_{1}^2P_{2}^2P_{3}^2\!-\!2P_{1}^2P_{2}P_{3}^2\!+\!P_{1}^2P_{3}^2 \!-\!2P_{1}P_{2}^2P_{3}^2\!+\!2P_{1}P_{2}P_{3}^2\!+\!P_{2}^2P_{3}^2), \end{aligned}$} \end{equation} \end{subequations} are defined for the notation simplicity. After a careful observation on the right hand side (RHS) of \eqref{derisp}, we can deduce that the sign of $\frac{\partial \bar{\Delta}_{SP}}{\partial p}$ is only determined by the numerator \begin{equation} \kappa(p) = \mu \!\cdot\! p^2+\lambda \!\cdot\! p+\xi, \end{equation} since the denominator is always large than zero. To determine the monotonicity of the function $\bar\Delta_{SP}$, we need to investigate the properties of the quadratic function $\kappa(p)$ on the feasible set of $p$ $\left(\mathrm{i.e.,}\ (0, 1]\right)$. Firstly, after some algebra manipulations, we note that \begin{subequations} \begin{equation} \xi=-P_{3}^2\Big[P_{1}^2(P_{2}-1)^2+P_{2}\big(P_{2}+2P_{1}(1-P_{2})\big)\Big], \end{equation} \begin{equation} \lambda^2-4\mu \xi=4P_{3}^2P_{2}(P_{3}-P_{1})(1-P_{1})(P_{1}+P_{2}-P_{1}P_{2})^2. \end{equation} \end{subequations} As $0<P_{1}<P_{2}<1$ and $0<P_{1}<P_{3}<1$, we have that $\xi<0$ and $\lambda^2-4\mu \xi>0$. This means that the curve of $\kappa(p)$ always intersects the Y-axis at the negative half of the Y-axis and it always has two roots on the X-axis, which can be given by \begin{subequations} \begin{equation} x_{1}=\frac{-\lambda -\sqrt{\lambda ^2-4\mu \xi}}{2\mu}, \end{equation} \begin{equation}\label{proof3x2} x_{2}=\frac{-\lambda +\sqrt{\lambda ^2-4\mu \xi}}{2\mu}, \end{equation} \end{subequations} where $x_{2}>x_{1}$. To further characterize the shapes of the function $\kappa(p)$, we now investigate $\mu$ and $\lambda$ for the following four possible cases: 1) When $\mu>0$ and $\lambda>0$, we always have $x_{1}<0$ and $x_{2}>0$. Since $p$ is in the range of $(0, 1]$, we have two sub-cases: (a) $x_{2}<1$ and (b) $x_{2}>1$. We draw the possible shapes of $\kappa(p)$ versus $p$ for the sub-case (a) and sub-case (b) in Fig. \ref{appendix1} (a) and Fig. \ref{appendix1} (b), respectively. From Fig. \ref{appendix1} (a), we can see that in the sub-case (a), $\kappa(p)<0$ holds for $p\in(0, x_{2}]$, and $\kappa(p)>0$ holds for $p\in(x_{2}, 1]$. This means that the function $\bar\Delta$ is decreasing for $p\in(0, x_{2}]$ and is increasing for $p\in(x_{2}, 1]$. As a result, the minimum value of $\bar\Delta$ is achieved at $p=x_{2}$. From Fig. \ref{appendix1} (b), we can see that in the sub-case (b), $\kappa(p)<0$ holds for $p\in(0, 1]$. Therefore, the function $\bar\Delta$ is always decreasing for $p\in(0, 1]$, which indicates that the value of $\bar\Delta$ is minimized at $p=1$. 2) When $\mu>0$ and $\lambda<0$, we always have $x_{1}<0$ and $x_{2}>0$. Since $p$ is in the range of $(0,1]$, we also have two sub-cases: (a) $x_{2}<1$ and (b) $x_{2}>1$. The possible shapes of $\kappa(p)$ versus $p$ for the sub-case (a) and sub-case (b) are depicted as Fig. \ref{appendix2} (a) and Fig. \ref{appendix2} (b), respectively. Similar to case 1), we can prove that the minimum value of $\bar\Delta$ is achieved by setting $p=x_{2}$ and $p=1$ for the case $x_{2}<1$ and $x_{2}>1$, respectively. 3) When $\mu<0$ and $\lambda<0$, we always have $x_{1}<x_{2}<0$. Therefore, there only exists one possible shape of $\kappa(p)$ versus $p$ in this case, which is depicted as Fig. \ref{appendix3}. From Fig. \ref{appendix3}, it is straightforward to see that $\kappa(0)<0$ holds for $p\in (0, 1]$. This means that the function $\bar\Delta$ is always decreasing for $p\in (0, 1]$ in this case. As a result, the minimum value of $\bar\Delta$ is achieved at $p=1$. 4) When $\mu<0$ and $\lambda>0$, we always have $x_{2}>x_{1}>0$. Therefore, the possible shapes of $\kappa(p)$ versus $p$ can be depicted as Fig. \ref{appendix4}. According to \eqref{proof3psi}, after some algebra manipulations, $\lambda$ can be rewritten as \begin{equation} \lambda\!=-2P_{3}(P_{1}\!+\!P_{2}\!-\!P_{1}P_{2})(P_{1}\!-\!P_{1}P_{3}\!-\!P_{2}P_{3}\!+\!P_{1}P_{2}P_{3}). \end{equation} As $\lambda>0$, $0<P_{1}<P_{2}<1$ and $0<P_{1}<P_{3}<1$, we thus have $P_{1}-P_{1}P_{3}-P_{2}P_{3}+P_{1}P_{2}P_{3}<0$, which can be rewritten as \begin{equation}\label{proof3P1} P_{1}<\frac{P_{2}P_{3}}{1-P_{3}+P_{2}P_{3}}. \end{equation} To further validate this case, we investigate the value of $-\mu$ under the constraint of \eqref{proof3P1}. We rewrite $-\mu$ as a quadratic function of $P_{1}$, which can be expressed as \begin{equation} -\mu(P_{1})=\psi P_{1}^2+\chi P_{1}+\omega, \end{equation} where \begin{subequations} \begin{equation} \psi = P_{2}^2P_{3}^2-2P_{2}P_{3}^2+2P_{2}P_{3}-P_{2}+P_{3}^2-2P_{3}+1, \end{equation} \begin{equation}\label{proof3miu} \chi=2P_{2}P_{3}^2(1-P_{2})+P_{2}(1-P_{3}), \end{equation} \begin{equation}\label{proof3unknown} \omega= P_{2}P_{3}(P_{2}P_{3}-1), \end{equation} \end{subequations} are defined for the simplicity of notations. As $0<P_{1}<P_{2}<1$ and $0<P_{1}<P_{3}<1$, according to \eqref{proof3miu} and \eqref{proof3unknown}, we have $\chi>0$ and $\omega<0$. In addition, if we set $P_{1}=1$, after some manipulations, we can attain that $-\mu({P_{1}})=(P_{3}-1)^2>0$. Similarly, if we substitute $P_{1}=\frac{P_{2}P_{3}}{1-P_{3}+P_{2}P_{3}}$ into the expression of $-\mu(P_{1})$, we can have $-\mu (P_{1})=\frac{P_{2}P_{3}(P_{2}-1)(P_{3}-1)^2}{(P_{2}P_{3}-P_{3}+1)^2}<0$. Based on the above analysis, we can draw the possible shapes of $-\mu(P_{1})$ versus $P_{1}$ for $\psi>0$ and $\psi<0$ in Fig. \ref{appendix5} (a) and Fig. \ref{appendix5} (b), respectively. Note that in these figures, we also show the possible positions of the point with X-coordinate being $\frac{P_{2}P_{3}}{1-P_{3}+P_{2}P_{3}}$. From Fig. \ref{appendix5} (a) and Fig. \ref{appendix5} (b), we can see that if $P_{1}<\frac{P_{2}P_{3}}{1-P_{3}+P_{2}P_{3}}$ and $0<P_{1}<1$, $-\mu<0$ always holds. This means that we always have $\mu>0$ if $\lambda>0$. This is contrary to the initial assumptions of this case (i.e., $\mu<0$ and $\lambda>0$). Therefore, the case 4) is not valid. In conclusion, we can find that in all of the possible case 1), case 2) and case 3), the minimum value of $\bar\Delta$ is achieved by setting $p=x_{2}$ and $p=1$ when $x_{2}<1$ and $x_{2}>1$, respectively. Therefore, based on \eqref{proof3xi}, \eqref{proof3psi}, \eqref{proof3omega} and \eqref{proof3x2}, after some algebra manipulations, the optimal $p$ that minimizes $\bar\Delta$ can be given by \eqref{psp}. This completes the proof. \begin{figure}[htbp] \centering \subfigure[When $x_{2}<1$]{\includegraphics[height=2.6cm]{appendix_1a}} \qquad \subfigure[When $x_{2}>1$]{\includegraphics[height=2.6cm]{appendix_1b}} \caption{Possible shapes for the function $\kappa(p)$ versus $p$ when $\mu>0$ and $\lambda>0$.} \label{appendix1} \end{figure} \begin{figure}[htbp] \centering \subfigure[When $x_{2}<1$]{\includegraphics[height=2.6cm]{appendix_2a}} \qquad \subfigure[When $x_{2}>1$]{\includegraphics[height=2.6cm]{appendix_2b}} \caption{Possible shapes for the function $\kappa(p)$ versus $p$ when $\mu>0$ and $\lambda<0$.} \label{appendix2} \end{figure} \begin{figure}[tbp] \centering{\includegraphics[height=2.8cm]{appendix_3}} \vspace{-0.7 em} \caption{Possible shapes for the function $\kappa(p)$ versus $p$ when $\mu<0$ and $\lambda<0$.} \label{appendix3} \end{figure} \begin{figure}[htbp] \centering \subfigure[When $x_{2}<1$]{\includegraphics[height=2.6cm]{appendix_4a}} \qquad \subfigure[When $x_{2}>1$]{\includegraphics[height=2.6cm]{appendix_4b}} \caption{Possible shapes for the function $\kappa(p)$ versus $p$ when $\mu<0$ and $\lambda>0$.} \label{appendix4} \end{figure} \begin{figure}[htbp] \centering \subfigure[When $\psi>0$]{\includegraphics[height=2.6cm]{appendix_5a}} \qquad \subfigure[When $\psi<0$]{\includegraphics[height=2.6cm]{appendix_5b}} \caption{Possible shapes for the function $-\mu(P_{1})$ versus $P_{1}$.} \label{appendix5} \end{figure} \end{appendices}
{'timestamp': '2021-01-05T02:13:57', 'yymm': '2101', 'arxiv_id': '2101.00382', 'language': 'en', 'url': 'https://arxiv.org/abs/2101.00382'}
arxiv
\section{Introduction} \label{sec:intro} The majority of NLP research addresses a \emph{single} text, typically at the sentence or document level. Yet, there are important applications which are concerned with aggregated information spread across multiple texts, such as cross-document coreference resolution~\cite{cybulska-vossen-2014-using}, classifying relations between document pairs~\cite{zhou-etal-2020-multilevel} and multi-hop question answering~\cite{yang-etal-2018-hotpotqa}. Existing language models (LMs)~\cite{devlin2019bert,liu2019roberta,JMLR:v21:20-074}, which are pretrained with variants of the masked language modeling (MLM) self-supervised objective, are known to provide powerful representations for internal text structure~\cite{clark-etal-2019-bert,rogers-etal-2020-primer}, which were shown to be beneficial also for various multi-document tasks~\cite{Yang-Siamese-2020,zhou-etal-2020-multilevel}. In this paper, we point out that beyond modeling internal text structure, multi-document tasks require also modeling cross-text relationships, particularly aligning or linking matching information elements across documents. For example, in Fig.~\ref{fig:comb_coref_examples}, one would expect a competent model to correctly capture that the two event mentions \textit{suing} and \textit{alleges}, from Documents 1 and 2, should be matched. Accordingly, capturing such cross-text relationships, in addition to representing internal text structure, can prove useful for downstream multi-text tasks, as we demonstrate empirically later. Following this intuition, we propose a new simple cross-document pretraining procedure, which is applied over sets of \emph{related} documents, in which informative cross-text relationships are abundant (e.g. like those in Fig.~\ref{fig:comb_coref_examples}). Under this setting, the model is encouraged to learn to consider and represent such relationships, since they provide useful signals when optimizing for the language modeling objective. For example, we may expect that it will be easier for a model to unmask the word \textit{alleges} in Document 2 if it would manage to effectively ``peek'' at Document 2, by matching the masked position and its context with the corresponding information in the other document. \input{figures/coref_examples} Naturally, considering cross-document context in pretraining, as well as in finetuning, requires a model that can process a fairly large amount of text. To that end, we leverage recent advances in developing efficient long-range transformers~\cite{beltagy2020longformer,zaheer2020big}, which utilize a global attention mode to build representations based on the entire input. Overcoming certain restrictions in prior utilization of global attention (see Section \ref{sec:background}), we introduce a dynamic attention pattern during pretraining, over all masked tokens, and later utilize it selectively in finetuning. Combining pretraining over related documents along with our global attention pattern yields a novel pretraining approach, that is geared to learn and implicitly encode informative cross-document relationships. As our experiments demonstrate, the resulting model, termed Cross-Document Language Model (CDLM), can be generically applied to downstream multi-document tasks, eliminating the need for task-specific architectures. We show empirically that our model improves consistently over previous approaches in several tasks, including cross-document coreference resolution, multi-hop question answering, and document matching tasks. Moreover, we provide controlled experiments to ablate the two contributions of pretraining over related documents as well as new dynamic global attention. Finally, we provide additional analyses that shed light on the advantageous behavior of our CDLM. Our contributions are summarized below: \begin{itemize}[noitemsep,topsep=0pt] \item A new pretraining approach for multi-document tasks utilizing: (1) sets of related documents instead of single documents; (2) a new dynamic global attention pattern. \item The resulting model advances the state-of-the-art for several multi-document tasks. \end{itemize} \section{Method} \subsection{Background: the Longformer Model} \label{sec:background} Recently, long-range LMs (e.g., Longformer~\cite{beltagy2020longformer}, BigBird~\cite{zaheer2020big}) have been proposed to extend the capabilities of earlier transformers \cite{vaswani2017attention} to process long sequences, using a sparse self-attention architecture. These models showed improved performance on both long-document and multi-document tasks~\cite{tay2021long}. In the case of multiple documents, instead of encoding documents separately, these models allow concatenating them into a long sequence of tokens and encoding them jointly. We base our model on Longformer, which sparsifies the full self-attention matrix in transformers by using a combination of a localized sliding window (called local attention), as well as a global attention pattern on a few specific input locations. Separate weights are used for global and local attention. During pretraining, Longformer assigns \emph{local attention} to all tokens in a window around each token and optimizes the Masked Language Modeling (MLM) objective. Before task-specific finetuning, the attention mode is predetermined for each input token, assigning global attention to a few targeted tokens, such as special tokens, that are targeted to encode global information. Thus, in the Longformer model, global attention weights are not pretrained. Instead, they are initialized to the local attention values, before finetuning on each downstream task. We conjecture that the global attention mechanism can be useful for learning meaningful representations for modeling cross-document (CD) relationships. Accordingly, we propose augmenting the pretraining phase to exploit the global attention mode, rather than using it only for task-specific finetuning, as described below. \subsection{Cross-Document Language Modeling} \label{sec:cdmlm} We propose a new pretraining approach consisting of two key ideas: (1) pretraining over sets of \emph{related} documents that contain overlapping information (2) pretraining with a dynamic global attention pattern over masked tokens, for referencing the entire cross-text context. \paragraph{Pretraining Over Related Documents} Documents that describe the same topic, e.g., different news articles discussing the same story, usually contain overlapping information. Accordingly, various CD tasks may leverage from an LM infrastructure that encodes information regarding alignment and mapping across multiple texts. For example, for the case of CD coreference resolution, consider the underlined predicate examples in Figure~\ref{fig:comb_coref_examples}. One would expect a model to correctly align the mentions denoted by \textit{suing} and \textit{alleges}, effectively recognizing their cross-document relation. Our approach to cross-document language modeling is based on pretraining the model on sets (clusters) of documents, all describing the same topic. Such document clusters are readily available in a variety of existing CD benchmarks, such as multi-document summarization (e.g., Multi-News~\cite{fabbri-etal-2019-multi}) and CD coreference resolution (e.g., ECB+~\cite{cybulska-vossen-2014-using}). Pretraining the model over a set of related documents encourages the model to learn cross-text mapping and alignment capabilities, which can be leveraged for improved unmasking, as exemplified in Sec.~\ref{sec:intro}. Indeed, we show that this strategy directs the model to utilize information across documents and helps in multiple downstream CD tasks. \begin{figure}[tb!!] \centering \includegraphics[width=1.\linewidth]{figures/cdmlm_fig} \caption{CDLM pretraining: The input consists of concatenated documents, separated by special document separator tokens. The masked (unmasked) token colored in yellow (blue) represents global (local) attention. The goal is to predict the masked token \textit{alleges}, based on the global context, i.e, the entire set of documents.} \label{fig:cdmlm} \vspace{-5mm} \end{figure} \paragraph{Pretraining With Global Attention} To support contextualizing information across multiple documents, we need to use efficient transformer models that scale linearly with input length. Thus, we base our cross-document language model (CDLM) on the Longformer model~\cite{beltagy2020longformer}, however, our setup is general and can be applied to other similar efficient Transformers. As described in Sec.~\ref{sec:background}, Longformer sparsifies the expensive attention operation for long inputs using a combination of local and global attention modes. As input to the model, we simply concatenate related documents using new special document separator tokens, {\tt $\langle$doc-s$\rangle$} and {\tt $\langle$/doc-s$\rangle$}, for marking document boundaries. We apply a similar masking procedure as in BERT: For each training example, we randomly choose a sample of tokens (15\%) to be masked;\footnote{For details of masking see BERT \cite{devlin-etal-2019-bert}.} however, our pretraining strategy tries to predict each masked token while considering the \emph{full} document set, by assigning them \emph{global attention}, utilizing the global attention weights (see Section~\ref{sec:background}). This allows the Longformer to contextualize information both across documents as well as over long-range dependencies within-document. The non-masked tokens use local attention, by utilizing the local attention weights, as usual. An illustration of the CD pretraining procedure is depicted in Fig.~\ref{fig:cdmlm}, where the masked token associated with \textit{alleges} (colored in yellow) globally attends to the whole sequence, and the rest of the non-masked tokens (colored in blue) attend to their local context. With regard to the example in Fig.~\ref{fig:comb_coref_examples}, this masking approach aims to implicitly compel the model to learn to correctly predict the word \textit{alleges} by looking at the second document, optimally at the phrase \textit{suing}, and thus capture the alignment between these two events and their contexts. \subsection{CDLM Implementation} \label{sec:res} In this section, we provide the experimental details used for pretraining our CDLM model. \paragraph{Corpus data} We use the preprocessed Multi-News dataset~\cite{fabbri-etal-2019-multi} as the source of related documents for pretraining. This dataset contains 44,972 training document clusters, originally intended for multi-document summarization. The number of source documents (that describe the same topic) per cluster varies from 2 to 10, as detailed in Appendix~\ref{subsec:multinews_data}. We consider each cluster of at least 3 documents for our cross-document pretraining procedure. We compiled our training corpus by concatenating related documents that were sampled randomly from each cluster, until reaching the Longformer's input sequence length limit of 4,096 tokens per sample. Note that this pretraining dataset is relatively small compared to conventional datasets used for pretraining. However, using it results in the powerful CDLM model. \paragraph{Training and hyperparameters} We pretrain the model according to our pretraining strategy, described in Section~\ref{sec:cdmlm}. We employ the Longformer-base model \cite{beltagy2020longformer} using the HuggingFace implementation \cite{wolf-etal-2020-transformers} and continue its pretraining, over our training data, for an additional 25k steps.\footnote{The training process for the base model takes 8 days on 8 RTX8000 GPUs. Training large models requires roughly 3x compute; therefore we do not focus on large models here and leave that for future work.} The new document separator tokens are added to the model vocabulary and randomly initialized before pretraining. We use the same setting and hyperparameters as in \citet{beltagy2020longformer}, and as elaborated in Appendix~\ref{sec:hyper_cdlm}. \subsection{Cross-Document Perplexity} \label{subsec:cdppl} First, we conduct a cross-document (CD) perplexity experiment, in a task-independent manner, to assess the contribution of the pretraining process. We used the Multi-News validation and test sets, each of them containing 5,622 document clusters, to construct the evaluation corpora. Then we followed the same protocol from the pretraining phase - 15\% of the input tokens are randomly masked, where the challenge is to predict the masked token given all documents in the input sequence. We matched the pretraining phase of each one of the ablation models: In \textsc{CDLM} and Rand \textsc{CDLM}, we assigned global attention for the masked tokens, and for Prefix \textsc{CDLM} the global attention is assigned to the 15\% first input tokens. Both Longformer and Local \textsc{CDLM} used local attention only. Perplexity is then measured by computing exponentiation of the loss. The results are depicted in Table~\ref{tab:ppl}. The advantage of \textsc{CDLM} over Rand \textsc{CDLM}, which was pretrained equivalently over an equivalent amount of (unrelated) CD data, confirms that CD pretraining, over \textit{related} documents, indeed helps for CD masked token prediction across such documents. Prefix \textsc{CDLM} introduces similar results since it was pretrained using a global attention pattern and the same corpora used by \textsc{CDLM}. The Local \textsc{CDLM} is expected to have difficulty to predict tokens across documents since it was pretrained without using global attention. Finally, the underlying Longformer model, which is reported as a reference point, is inferior to all the ablations since it was pretrained in a single document setting and without global attention or further pretraining on this domain. Unlike the two local-attentive models, \textsc{CDLM} is encouraged to look at the full sequence when predicting a masked token. Therefore, as in the pretraining phase, it exploits related information in other documents, and not just the local context of the masked token, hence \textsc{CDLM}, as well as Prefix \textsc{CDLM}, result with a substantial performance gain. \input{tables/ppl} \subsection{Cross-Document Coreference Resolution} \label{subsec:fdcdcoref} Cross-document (CD) coreference resolution deals with identifying and clustering together textual mentions across multiple documents that refer to the same concept (see Fig.~\ref{fig:comb_coref_examples}). The considered mentions can be either entity mentions, usually noun phrases, or event mentions, typically verbs or nominalizations that appear in the text. \paragraph{Benchmark.} We evaluated our CDLM by utilizing it over the ECB+ corpus~\cite{cybulska-vossen-2014-using}, the most commonly used dataset for CD coreference. ECB+ consists of within- and cross-document coreference annotations for entities and events (statistics are given in Appendix~\ref{subsec:ecb_data}). Following previous work, for comparison, we conduct our experiments on gold event and entity mentions. \input{tables/cd-coref_v2} We follow the standard coreference resolution evaluation metrics: \textit{MUC}~\cite{vilain1995model}, $\textit{B}^\textbf{3}$~\cite{bagga1998algorithms}, \textit{CEAFe}~\cite{luo2005coreference}, their average \textit{CoNLL F1}, and the more recent \textit{LEA} metric~\cite{moosavi-strube-2016-coreference}. \paragraph{Algorithm.} Recent approaches for CD coreference resolution train a pairwise scorer to learn the probability that two mentions are co-referring. At inference time, an agglomerative clustering based on the pairwise scores is applied, to form the coreference clusters. We made several modifications to the pairwise scorer. The current state-of-the-art models~\cite{zeng-etal-2020-event,yu2020paired} train the pairwise scorer by including only the local contexts (containing sentences) of the candidate mentions. They concatenate the two input sentences and feed them into a transformer-based LM. Then, part of the resulting tokens representations are aggregated into a single feature vector which is passed into an additional MLP-based scorer to produce the coreference probability estimate. To accommodate our proposed CDLM model, we modify this modeling by including the entire documents containing the two candidate mentions, instead of just their containing sentences, and assigning the global attention mode to the mentions' tokens and to the {\tt [CLS]} token. The full method and hyperparameters are elaborated in Appendix~\ref{subsec:ft_coref}. \paragraph{Baselines.} We consider state-of-the-art baselines that reported results over the ECB+ benchmark. The following baselines were used for both event and entity coreference resolution: \begin{itemize}[leftmargin=0pt,wide=0pt,label={--},topsep=0pt] \setlength\itemsep{-1pt} \item \citet{barhom-etal-2019-revisiting} is a model trained jointly for solving event and entity coreference as a single task. It utilizes semantic role information between the candidate mentions. \item \citet{Cattan2020StreamliningCC} is a model trained in an end-to-end manner (jointly learning mention detection and coreference following~\citet{lee-etal-2017-end}), employing the RoBERTa-large model to encode each document separately and to train a pair-wise scorer atop. \item \citet{allaway2021sequential} is a BERT-based model combining sequential prediction with incremental clustering. \end{itemize} \input{tables/coref-ablations} The following baselines were used for event coreference resolution. They all integrate external linguistic information as additional features. \begin{itemize}[leftmargin=0pt,wide=0pt,label={--},topsep=0pt] \setlength\itemsep{-1pt} \item \citet{meged-etal-2020-paraphrasing} is an extension of \citet{barhom-etal-2019-revisiting}, leveraging external knowledge acquired from a paraphrase resource~\cite{shwartz-etal-2017-acquiring}. \item \citet{zeng-etal-2020-event} is an end-to-end model, encoding the concatenated two sentences containing the two mentions by the BERT-large model. Similarly to our algorithm, they feed a MLP-based pairwise scorer with the concatenation of the {\tt [CLS]} representation and an attentive function of the candidate mentions representations. \item \citet{yu2020paired} is an end-to-end model similar to \citet{zeng-etal-2020-event}, but uses rather RoBERTa-large and does not consider the {\tt [CLS]} contextualized token representation for the pairwise classification. % \end{itemize} \paragraph{Results.} The results on event and entity CD coreference resolution are depicted in Table \ref{tab:subtopic_results_event}. Our \textsc{CDLM} outperforms all methods, including the recent sentence based models on event coreference. All the results are statistically significant using bootstrap and permutation tests with ${p<0.001}$~\cite{dror-etal-2018-hitchhikers}. \textsc{CDLM} largely surpasses state-of-the-art results on entity coreference, even though these models utilize external information and use large pretrained models, unlike our base model. In Table~\ref{tab:coref_ablations}, we provide the ablation study results. Using our model with sentences only, i.e., considering only the sentences where the candidate mentions appear (as the prior baselines did), exhibits lower performance, resembling the best performing baselines. Some crucial information about mentions can appear in a variety of locations in the document, and is not concentrated in one sentence. This characterizes long documents, where pieces of information are often spread out. Overall, the ablation study shows the advantage of using our pretraining method, over related documents and using a scattered global attention pattern, compared to the other examined settings. Recently, our CDLM-based coreference model was utilized to generate event clusters within an effective faceted-summarization system for multi-document exploration \cite{iFacetSum}. \subsection{Document matching} \label{subsec:aan} We evaluate our CDLM over document matching tasks, aiming to assess how well our model can capture interactions across multiple documents. We use the recent multi-document classification benchmark by \citet{zhou-etal-2020-multilevel} which includes two tasks of citation recommendation and plagiarism detection. The goal of both tasks is categorizing whether a particular relationship holds between two input documents. Citation recommendation deals with detecting whether one reference document should cite the other one, while the plagiarism detection task infers whether one document plagiarizes the other one. To compare with recent state-of-the-art models, we utilized the setup and data selection from~\citet{zhou-etal-2020-multilevel}, which provides three datasets for citation recommendation and one for plagiarism detection. \paragraph{Benchmarks.} For citation recommendation, the datasets include the ACL Anthology Network Corpus \citep[AAN;][]{radev2013acl}, the Semantic Scholar Open Corpus \citep[OC;][]{bhagavatula-etal-2018-content}, and the Semantic Scholar Open Research Corpus \citep[S2ORC;][]{lo-etal-2020-s2orc}. For plagiarism detection, the dataset is the Plagiarism Detection Challenge \citep[PAN;][]{potthast2013overview}. AAN is composed of computational linguistics papers which were published on the ACL Anthology from 2001 to 2014, OC is composed of computer science and neuroscience papers, S2ORC is composed of open access papers across broad domains of science, and PAN is composed of web documents that contain several kinds of plagiarism phenomena. For further dataset prepossessing details and statistics, see Appendix~\ref{subsec:cda_data}. \paragraph{Algorithm.} For our models, we added the {\tt [CLS]} token at the beginning of the input sequence, assigned it global attention, and concatenated the pair of texts, according to the finetuning setup discussed in Section~\ref{sec:cdmlm}. The hyperparameters are further detailed in Appendix~\ref{subsec:app_aan}. \paragraph{Baselines.} We consider the reported results of the following recent baselines: \begin{itemize}[leftmargin=0pt,wide=0pt,label={--},topsep=0pt] \setlength\itemsep{-1pt} \item \textbf{\textsc{HAN}} \cite{yang-etal-2016-hierarchical} proposed the Hierarchical Attention Networks (HANs). These models employ a bottom-up approach in which a document is represented as an aggregation of smaller components i.e., sentences, and words. They set competitive performance in different tasks involving long document encoding \cite{sun-etal-2018-stance}. \item \textbf{\textsc{SMASH}} \cite{jiang2019semantic} is an attentive hierarchical recurrent neural network (RNN) model, used for tasks related to long documents. \item \textbf{\textsc{SMITH}} \cite{Yang-Siamese-2020} is a BERT-based hierarchical model, similar HANs. \item \textbf{\textsc{CDA}} \cite{zhou-etal-2020-multilevel} is a cross-document attentive mechanism (CDA) built on top of HANs, based on BERT or GRU models (see Section~\ref{sec:related}). % \end{itemize} Both \textsc{SMASH} and \textsc{SMITH} reported results only over the AAN benchmark. In addition, they used a slightly different version of the AAN dataset,\textsuperscript{\ref{note1}} and included the full documents, unlike the dataset that \cite{zhou-etal-2020-multilevel} used, which we utilized as well, that considers only the documents' abstracts. \input{tables/aan} \paragraph{Results.} The results on the citation recommendation and plagiarism detection tasks are depicted in Table~\ref{tab:aan2}. We observe that even though \textsc{SMASH} and \textsc{SMITH} reported results using the full documents for the AAN task, our model outperforms them, using the partial version of the dataset, as in~\citet{zhou-etal-2020-multilevel}. Moreover, unlike our model, CDA is task-specific since it trains new cross-document weights for each task, yet it is still inferior to our model, evaluating on the three citation recommendation benchmarks. On the plagiarism detection benchmark, interestingly, our models does not perform better. Moreover, CDA impairs the performance of \textsc{BERT-HAN}, implying that dataset does not require detailed cross-document attention at all. In our experiments, finetuning \textsc{BERT-HAN+CDA} over the PAN dataset yielded poor results: $F_1$ score of 79.6, substantially lower compared to our models. The relatively small size of PAN may explain such degradations. \footnotetext{Following the most recent work of \citet{zhou-etal-2020-multilevel}, we evaluate our model on their version of the dataset. We also quote the results of \textsc{SMASH} and \textsc{SMITH} methods, even though they used a somewhat different version of this dataset, hence their results are not fully comparable to the results of our model and those of \textsc{CDA}.} \subsection{Multihop Question answering} \label{subsec:hpqa} In the task of multihop question answering, a model is queried to extract answer spans and evidence sentences, given a question and multiple paragraphs from various related and non-related documents. This task includes challenging questions, that answering them requires finding and reasoning over multiple supporting documents. \paragraph{Benchmark.} We used the HotpotQA-distractor dataset~\cite{yang-etal-2018-hotpotqa}. Each example in the dataset is comprised of a question and 10 different paragraphs from different documents, extracted from Wikipedia; two gold paragraphs include the relevant information for properly answering the question, mixed and shuffled with eight distractor paragraphs (for the full dataset statistics, see~\citet{yang-etal-2018-hotpotqa}). There are two goals for this task: extraction of the correct answer span, and detecting the supporting facts, i.e., evidence sentences. \paragraph{Algorithm.} We employ the exact same setup from~\cite{beltagy2020longformer}: We concatenate all the 10 paragraphs into one large sequence, separated by document separator tokens, and using special sentence tokens to separate sentences. The model is trained jointly in a multi-task manner, where classification heads specialize on each sub-task, including relevant paragraphs prediction, evidence sentences identification, extracting answer spans and inferring the question types (yes, no, or span). For details and hyperparameters, see Appendix~\ref{subsec:multihopqa} and ~\citet[Appendix D]{beltagy2020longformer}. \input{tables/hotpotqa-results} \paragraph{Results.} The results are depicted in Table~\ref{tab:hotpotqa}, where we included also the results for Transformer-XH~\cite{Zhao2020Transformer}, a transformer-based model that constructs global contextualized representations, Graph Recurrent Retriever~\cite{Asai2020Learning}, a recent strong graph-based passage retrieval method, RoBERTa~\cite{liu2019roberta}, which was modified by \citet{beltagy2020longformer} to operate on long sequences (dubbed RoBERTa-lf), and \textsc{BigBird}~\cite{zaheer2020big}, a long-range transformer model which was pretrained on a massive amount of text. \textsc{CDLM} outperforms all the ablated models as well as the comparably sized models from prior work (except for \textsc{BigBird}), especially in the supporting evidence detection sub-task. We note that the \textsc{BigBird} model was pretrained on much larger data, using more compute resources compared both to the Longformer model and to our models. We suspect that with more compute and data, it is possible to close the gap between CDLM and \textsc{BigBird} performance. We leave for future work evaluating a larger version of the \textsc{CDLM} model against large, state-of-the-art models. \subsection{Attention Analysis} \label{subsec:qualitative} It was recently shown that during the pretraining phase, LMs learn to encode various types of linguistic information, that can be identified via their attention patterns~\cite{wiegreffe-pinter-2019-attention,rogers2020primer}. In \citet{clark-etal-2019-bert}, the attention weights of BERT were proved as informative for probing the degree to which a particular token is ``important'', as well as its linguistic roles. For example, they showed that the averaged attention weights from the last layer of BERT are beneficial features for dependency parsing. We posit that our pretraining scheme, which combines global attention and a multi-document context, captures alignment and mapping information across documents. Hence, we hypothesize that the global attention mechanism favors cross-document (CD), long-range relations. To gain more insight, our goal is to investigate if our proposed pretraining method leads to relatively higher global attention weights between co-referring mentions compared to non-co-referring ones, even without any finetuning over CD coreference resolution. \paragraph{Benchmark.} We randomly sampled 1,000 positive and 1,000 negative coreference-pair examples from the ECB+ CD coreference resolution benchmark, for both events and entities. Each example consists of two concatenated documents and two coreference candidate mentions (see Section~\ref{subsec:fdcdcoref}). \paragraph{Analysis Method.} For each example, which contains two mention spans, we randomly pick one to be considered as the \emph{source span}, while the second one is the \emph{target span}. We denote the set of the tokens in the source and target spans as $S$ and $T$, respectively. Our goal is to quantify the degree of alignment between $S$ and $T$, using the attention pattern of the model. We first assign global attention to the tokens in the source span (in $S$). Next, we pass the full input through the model, compute the normalized attention weights for all the tokens in the input with respect to $S$, by aggregating the scores extracted from the last layer of the model. The score for an input token $i\notin S$, is given by \[ s(i|S) \propto \exp \left[\sum_{k=1}^n \sum_{j\in S} \left(\alpha_{i,j}^k+\alpha_{j,i}^k\right)\right], \] where ${\alpha_{i,j}^k}$ is the \emph{global} attention weight from token $i$ to token $j$ produced by head $k$, and $n$ is the total number of attention heads (the score is computed using only the last layer of the model). Note that we include both directions of attention. The target span score is then given by ${s(T|S)=\frac{1}{|T|}\sum_{j\in T}s(j|S)}$. Finally, we calculate the percentile rank (PR) of ${s(T|S)}$, compared to the rest of the token scores within the containing document of $T$, namely, ${\{s(i|S)|i\notin T\}}$. % For positive coreference examples, plausible results are expected to be associated with high attention weights between the source and the target spans, resulting with a high value of ${s(T|S)}$, and thus, yielding a higher PR. For negative examples, the target span is not expected to be promoted with respect to the rest of the tokens in the document. \input{figures/ecb_docs_tiny} \paragraph{Results.} First, we apply the procedure above over one selected example, depicted in Figure~\ref{fig:ecb_example}. We consider the two CD co-referring event mentions: \textit{name} and \textit{nominates} as the source and target spans, respectively. The target span received a PR of 69\% when evaluating the underlying Longformer. Notably, it received a high PR of 90\% when using our \textsc{CDLM}, demonstrating the advantage of our novel pretraining method. Next, we turn to a systematic experiment, elucidating the relative advantage of pretraining with global attention across related documents. In Table~\ref{tab:pr_ecb}, we depict the mean PR (MPR) computed over all the sampled examples, for all our pretrained models. We observe that none of the models fail\footnote{Typically, PR of $\sim$50\% corresponds to random ranking.} on the set of negatives, since the negative examples contain reasonable event or entity mentions, rather than random, non informative spans. For the positive examples, the gap of up to 10\% of MPR between the ``Local'' and ``Global'' models shows the advantage of adopting global attention during the pretraining phase. This indicates that the global attention mechanism implicitly helps to encode alignment information. \input{tables/pr_ecb} \section{Evaluations and Results} \label{sec:eval} This section presents experiments conducted to evaluate our \textsc{CDLM}, as well as the the ablations and baselines we used. For the intrinsic evaluation we measured the perplexity of the models. For extrinsic evaluations we considered event and entity cross-document coreference resolution, paper citation recommendation, document plagiarism detection, and multihop question answering. We also conducted an attention analysis, showing that our \textsc{CDLM} indeed captured cross-document and long-range relations during pretraining.\footnote{Since the underlying Longformer model is encoder-only, we evaluate on tasks that can be modeled using the encoder-only setting. We leave extensions to address seq2seq tasks like generation to future work.} \paragraph{Baseline LMs} Recall that CDLM employs multiple related documents during pretraining, and assigns global attention to masked tokens. To systematically study the importance of these two components, we consider the following LM baselines: \begin{itemize}[leftmargin=0pt,wide=0pt,label={--},topsep=0pt] \setlength\itemsep{-1pt} \item \textbf{Longformer}: the underlying Longformer model, without additional pretraining. \item \textbf{Local \textsc{CDLM}}: pretrained using the same corpus of CDLM with the Longformer's attention pattern (local attention only). This baseline is intended to separate the effect of simply continuing pretraining Longformer on our new pre-training data. \item \textbf{Rand \textsc{CDLM}}: Longformer with the additional CDLM pretraining, while using random, unrelated documents from various clusters. This baseline model allows assessing whether pretraining using related documents is beneficial. \item \textbf{Prefix \textsc{CDLM}}: pretrained similarly as CDLM but uses global attention for the first tokens in the input sequence, rather than the masked ones. This resembles the attention pattern of \textsc{BigBird} \cite{zaheer2020big}, adopted for our cross-document setup. We use this ablation for examining this alternative global attention pattern, from prior work. \end{itemize} The data and pretraining hyperparameters used for the ablations above are the same as the ones used for our \textsc{CDLM} pretraining, except for the underlying Longformer, which is not further pretrained, and the Rand \textsc{CDLM}, that is fed with different document clusters (drawn from the same corpus). During all the experiments, the global attention weights used by the underlying Longformer and by Local \textsc{CDLM} are initialized to the values of their pretrained local attention weights. All the models above further finetune their global attention weights, depending on the downstream task. When finetuning CDLM and the above models on downstream tasks involving multiple documents, we truncate the longer inputs to the Longformer's 4,096 token limit. \input{051_ppl} \input{052_cdcoref} \input{053_aan} \input{054_hpqa} \input{055_qualitative} \section{Related Work} \label{sec:related} Recently, long-context language models \cite{beltagy2020longformer,zaheer2020big} introduced the idea of processing multi-document tasks using a single long-context sequence encoder. However, pretraining objectives in these models consider only single documents. Here, we showed that additional gains can be obtained by MLM pretraining using multiple \textit{related} documents as well as a new dynamic global attention pattern. Processing and aggregating information from multiple documents has been also explored in the context of document retieval, aiming to extract information from a large set of documents~\cite{guu2020realm,lewis2020pre,patrick2020retrieval,karpukhin-etal-2020-dense}. These works focus on retrieving relevant information from often a large collection of documents, by utilizing short-context LMs, and then generate information of interest. CDLM instead provides an approach for improving the encoding and contextualizing information across multiple documents. As opposed to the mentioned works, our model utilizes long-context LM and can include broader contexts of more than a single document. The use of cross-document attention has been recently explored by the Cross-Document Attention (CDA) \cite{zhou-etal-2020-multilevel}. CDA specifically encodes two documents, using hierarchical attention networks, with the addition of cross attention between documents, and makes similarity decision between them. Similarly, the recent DCS model~\cite{ginzburg-etal-2021-self} suggested a cross-document finetuning scheme for unsupervised document-pair matching method (processing only two documents at once). Our CDLM, by contrast, is a general pretrained language model that can be applied to a variety of multi-document downstream tasks, without restrictions on the number of input documents, as long as they fit the input length of the Longformer. Finally, our pretraining scheme is conceptually related to cross-encoder models that leverage simultaneously multiple related information sources. For example, the Translation Language Model (TLM) \cite{conneau2019cross} encodes together sentences and their translation, while certain cross-modality encoders pretrain over images and texts in tandem (e.g., ViLBERT~\cite{lu2019vilbert}). \section{Conclusion} We presented a novel pretraining strategy and technique for cross-document language modeling, providing better encoding for cross-document (CD) downstream tasks. Our contributions include the idea of leveraging clusters of related documents for pretraining, via cross-document masking, along with a new long-range attention pattern, together driving the model to learn to encode CD relationships. This was achieved by extending the global attention mechanism of the Longformer model to apply already in pretraining, creating encodings that attend to long-range information across and within documents. Our experiments assess that our cross-document language model yields new state-of-the-art results over several CD benchmarks, while, in fact, employing substantially smaller models. Our analysis showed that CDLM implicitly learns to recover long-distance CD relations via the attention mechanism. We propose future research to extend this framework to train larger models, and to develop cross-document sequence-to-sequence models, which would support CD tasks that involve a generation phase. \section*{Acknowledgments} We thank Doug Downey and Luke Zettlemoyer for fruitful discussions and helpful feedback, and Yoav Goldberg for helping us connect with collaborators on this project. The work described herein was supported in part by grants from Intel Labs, the Israel Science Foundation grant 1951/17, the Israeli Ministry of Science and Technology, and the NSF Grant OIA-2033558. \section{Dataset Statistics and Details} In this section, we provide details regrading the pretraining corpus and benchmarks we used during our experiments. \subsection{Multi-News Corpus} \label{subsec:multinews_data} We used the preprocessed, not truncated version of Multi-News, which totals 322MB of uncompressed text.\footnote{We used the dataset available in \url{https://drive.google.com/open?id=1qZ3zJBv0zrUy4HVWxnx33IsrHGimXLPy}.} Each one of the preprocessed documents contains up to 500 tokens. The average and 90$^\text{th}$ percentile of input length is 2.5k and 3.8K tokens, respectively. In Table~\ref{tab:multi_stats} we list the number of related documents per cluster. This follows the original dataset construction suggested in~\citet{fabbri-etal-2019-multi}. \input{tables/multinews-stats} \subsection{ECB+ Dataset} \label{subsec:ecb_data} In Table~\ref{tab:ecb_stat}, we list the statistics about training, development, and test splits regarding the topics, documents, mentions and coreference clusters. We follow the data split used by previous works~\cite{cybulska2015bag, kenyon-dean-etal-2018-resolving,barhom-etal-2019-revisiting}: For training, we consider the topics: 1, 3, 4, 6-11, 13- 17, 19-20, 22, 24-33; For Validation, we consider the topics: 2, 5, 12, 18, 21, 23, 34, 35; For test, we consider the topics: 36-45. \input{tables/ecb-stats} \subsection{Paper Citation Recommendation \& Plagiarism Detection Datasets} \label{subsec:cda_data} In Table~\ref{tab:splits}, we list the statistics about training, development, and test splits for each benchmark separatly, and in Table~\ref{tab:counts}, we list the document and example counts for each benchmark. The statistics are taken from~\citet{zhou-etal-2020-multilevel}. \input{tables/cda-stats} The preprocessing of the datasets performed by~\citet{zhou-etal-2020-multilevel} includes the following steps: For AAN, only pairs of documents that include abstracts are considered, and only their abstracts are used. For OC, only one citation per paper is considered, and the dataset was downsampled significantly. For S2ORC, formed pairs of citing sections and the corresponding abstract in the cited paper are included, and the dataset was downsampled significantly. For PAN, pairs of relevant segments out of the entire document were extracted. For all the datasets, negative pairs were sampled randomly. Then, a standard preprocessing that includes filtering out characters that are not digits, letters, punctuation, or white space in the texts was performed. \begin{figure*}[tb] \centering \includegraphics[width=0.79\linewidth]{figures/cd-coref} \caption{CD-coreference resolution pairwise mention representation, using the new setup, for our \textsc{CDLM} models. $m_t^i$, $m_t^j$ and $s_t$ are the cross-document contextualized representation vectors for mentions $i$ and $j$, and of the {\tt [CLS]} token, respectively. ${m_t^i \circ m_t^j}$ is the element-wise product between $m_t^i$ and $m_t^j$. $m_t(i,j)$ is the final produced pairwise-mention representation. The tokens colored in yellow represent global attention, and tokens colored in blue represent local attention.} \label{fig:cdcoref} \end{figure*} \section{CDLM Pretraining Hyperparameters} \label{sec:hyper_cdlm} In this section, we detail the hyperparameters setting of the models we pretrained, including \textsc{CDLM} Prefix \textsc{CDLM}, Rand \textsc{CDLM}, and Local \textsc{CDLM}: The input sequences are of the length of 4,096, effective batch size of 64 (using gradient accumulation and batch size of 8), a maximum learning rate of 3e-5, and a linear warmup of 500 steps, followed by a power 3 polynomial decay. For speeding up the training and reducing memory consumption, we used the mixed-precision (16-bits) training mode. The pretraining took 8 days, using eight 48GB RTX8000 GPUs. The rest of the hyperparameters are the same as for RoBERTa~\cite{liu2019roberta}. Note that training CDLM using the large version of the Longformer model might require 2-3 times more memory and time. \section{Finetuning on Downstream Tasks} In this section, we elaborate further implementation details regarding the downstream tasks that we experimented, including the hyperparameter choices and the algorithms used. \subsection{Cross-Document Coreference Resolution} \label{subsec:ft_coref} The setup for our cross-document coreference resolution pairwise scoring is illustrated in Figure~\ref{fig:cdcoref}. We concatenate the relevant documents using the special document separator tokens, then encode them using our \textsc{CDLM} along with the {\tt [CLS]} token at the beginning of this sequence, as suggested in Section~\ref{sec:cdmlm}. For within-document coreference candidate examples, we use just the single containing document with one set of document separators, for the single input document. Inspired by \citet{yu2020paired}, we use candidate mention marking: we wrap the mentions with special tokens $\langle$\texttt{m}$\rangle$ and $\langle$\texttt{/m}$\rangle$ in order to direct the model to specifically pay attention to the candidates representations. Additionally, we assign global-attention to {\tt [CLS]}, {\tt $\langle$\texttt{m}$\rangle$}, $\langle$\texttt{/m}$\rangle$, and the mention tokens themselves, according to the finetuning strategy proposed in Section~\ref{sec:cdmlm}. Our final pairwise-mention representation is formed like in~\citet{zeng-etal-2020-event} and~\citet{yu2020paired}: We concatenate the cross-document contextualized representation vectors for the $t^{\text{th}}$ sample: \begin{equation*} \begin{split} {m_t(i,j)=\left[s_t,m_t^i,m_t^j,m_t^i\circ m_t^j \right]}, \end{split} \end{equation*} where $[\cdot]$ denotes the concatenation operator, $s_t$ is the cross-document contextualized representation vector of the {\tt [CLS]} token, and each of $m_t^i$ and $m_t^j$ is the sum of candidate tokens of the corresponding mentions ($i$ and $j$). Then, we train the pairwise scorer according to the suggested finetuning scheme. At test time, similar to most recent works, we apply agglomerative clustering to merge the most similar cluster pairs. Regarding the training data collection and hyperparameter setting, we adopt the same protocol as suggested in~\citet{Cattan2020StreamliningCC}:\footnote{We used the implementation taken from \url{https://github.com/ariecattan/cross_encoder}} Our training set is composed of positive instances which consist of all the pairs of mentions that belong to the same coreference cluster, while the negative examples are randomly sampled. The resulting feature vector is passed through a MLP pairwise scorer that is composed of one hidden layer of the size of 1024, followed by the Tanh activation. We finetune our models for 10 epochs, with an effective batch size of 128. We used eight 32GB V100-SMX2 GPUs for finetuning our models. The finetuning process took $\sim$28 and $\sim$45 hours per epoch, for event coreference and entity coreference, respectively. \subsection{Multi-Document Classification} \label{subsec:app_aan} We tune our models for 8 epochs, using a batch size of 32, and used the same hyperparameter setting from \citet[Section~5.2]{zhou-etal-2020-multilevel}.\footnote{we used the script \url{https://github.com/XuhuiZhou/CDA/blob/master/BERT-HAN/run_ex_sent.sh}} We used eight 32GB V100-SMX2 GPUs for finetuning our models. The finetuning process took $\sim$2,$\sim$5,$\sim$3, and $\sim$0.5 hours per epoch, for AAN, OC, S2ORC, and for PAN, respectively. We used the mixed-precision training mode, to reduce time and memory consumption. \subsection{Multihop Question Answering} \label{subsec:multihopqa} For preparing the data for training and evaluation, we follow our finetuning scheme: for each example, we concatenate the question and all the 10 paragraphs in one long context. We particularly use the following input format with special tokens and our document separators: ``\texttt{[CLS] [q] question [/q] $\langle$\texttt{doc-s}$\rangle$$\langle$t$\rangle$ $\texttt{title}_{\texttt{1}}$ $\langle$/t$\rangle$} \texttt{$\langle$s$\rangle$} $\texttt{sent}_{\texttt{1,1}}$ \texttt{$\langle$/s$\rangle$} \texttt{$\langle$s$\rangle$} $\texttt{sent}_{\texttt{1,2}}$ \texttt{$\langle$/s$\rangle$} $\langle$\texttt{/doc-s}$\rangle$ \texttt{...} \texttt{$\langle$t$\rangle$ $\langle$\texttt{doc-s}$\rangle$ $\texttt{title}_{\texttt{2}}$ $\langle$/t$\rangle$ } $\texttt{sent}_{\texttt{2,1}}$ \texttt{$\langle$/s$\rangle$} \texttt{$\langle$s$\rangle$} $\texttt{sent}_{\texttt{2,2}}$ \texttt{$\langle$/s$\rangle$} \texttt{$\langle$s$\rangle$} \texttt{...}'' where \texttt{[q]}, \texttt{[/q]}, $\langle$\texttt{t}$\rangle$, $\langle$\texttt{/t}$\rangle$, \texttt{$\langle$s$\rangle$}, \texttt{$\langle$/s$\rangle$}, \texttt{[p]} are special tokens representing, question start and end, paragraph title start and end, and sentence start and end, respectively. The new special tokens were added to the models vocabulary and randomly initialized before task finetuning. We use global attention to question tokens, paragraph title start tokens as well as sentence tokens. The model's structure is taken from ~\citet{beltagy2020longformer}. Similar to~\citet{beltagy2020longformer}, we finetune our models for 5 epochs, using a batch size of 32, learning rate of 1e-4, 100 warmup steps. Finetuning on our models took $\sim$6 hours per epoch, using four 48GB RTX8000 GPUs for finetuning our models.
{'timestamp': '2021-09-06T02:05:08', 'yymm': '2101', 'arxiv_id': '2101.00406', 'language': 'en', 'url': 'https://arxiv.org/abs/2101.00406'}
arxiv
\section*{Introduction} Persistent homology is a tool of Topological Data Analysis (TDA) whose applications range widely from biology to urban planning to neuroscience (see \cite{database} for an extended list of applications). Persistent homology summarises a dataset's information in the form of barcode \cite{barcode_carlssonetal, barcode_ghrist}. The efficient computation of such barcodes is one of the main algorithmic problems in TDA \cite{roadmap}. We provide an algorithm (Algorithm \ref{algorithm_row_pivot_red}) for the barcode decomposition based on row pivot pairing, which is the dual of the column pivot pairing presented in \cite{vines, edels_harer}. The algorithm reduces the boundary matrix of a given filtered simplicial complex proceeding by rows and performing row additions, allowing the full exploitation of the compress optimisation \cite{clearcompress}. A non-exhaustive list of algorithms to decompose persistence modules into interval modules includes the so-called standard algorithm \cite{edels_harer}, the chunk algorithm \cite{clearcompress}, the twist algorithm \cite{twist}, the pHrow algorithm \cite{dualities}, and Ripser \cite{ripser_paper}. The implementation of the first four can be found in \cite{PHAT} (cf. \cite{phat_paper}), and that of Ripser in \cite{ripser_software}. All of them take as input a filtered simplicial complex and employ column operations. Moreover, in a recent and independent work \cite{Edel-Olsb}, a dualisation of the standard algorithm is presented, using row operations. In addition to these algorithms, in \cite{abcw} it is shown that the barcode decomposition can also be achieved via the decomposition of filtered chain complexes, whose reduction is performed by row operations. However, the reduction in \cite{abcw} is different from the standard one, which is the focus of this work. Thus, we will not further study the algorithm presented in \cite{abcw}. As we mention, the idea of proceeding by row is not new. Here, we use the straightforward idea of row pivots to clarify the duality between clear and compress optimisations in the computation of persistent homology and cohomology. In \cite{ripser_paper, phat_paper, dualities}, it is shown that, for Vietoris-Rips complexes, the column reduction, coupled with the clear optimisation and applied to the coboundary matrix, provides a significant speed-up in the computation of the barcode. This improvement is not mirrored when the same reduction is coupled with the compress optimisation and applied to the boundary matrix \cite{ripser_paper, clearcompress, dualities}. Here, we show that the reason for this asymmetry is that the second procedure is not the true dual of the first one: to obtain the dual, and thus the same number of operations, it is necessary to reduce the boundary matrix via row operations instead of via column operations. \section{Preliminaries}\label{section_preliminaries} Throughout the work, the symbol $K=\{\sigma_1, \dots, \sigma_m\}$ denote a simplicial complex of dimension $d$, such that for each $i\leq m$, $K_i\coloneqq \{\sigma_1, \dots, \sigma_i\}$ is again a simplicial complex. The chain $\emptyset=K_0\subset K_1\subset\dots \subset K_m=K$, denoted by the symbol $FK$ throughout the work, is called a {\bf filtration} of $K$. Given a simplex $\sigma$ of dimension $h$, its {\bf boundary} is the set of the faces of $\sigma$ in dimension $h-1$. If $h=0$, the boundary is empty. Otherwise, it consists of exactly $h+1$ simplices. The {\bf boundary matrix} $\partial$ of $FK$, is a $(m\times m)$-matrix with coefficients in $\mathbb{F}_2$ where the $j$-th column represents the boundary of $\sigma_j$, i.e. $\partial[i,j]= 1$ if and only if $\sigma_i$ is in the boundary of $\sigma_j$. Note that, since $\sigma_i$ is in the complex before $\sigma_j$ is added, $\partial$ is an upper-triangular matrix. For $0\leq i \leq m$ and $0\leq p\leq d$, we denote the $p$-th homology of $K_i$ over the field $\mathbb{F}_{2}$ by $H_p(K_i)$. The inclusions $K_i\hookrightarrow K_j$, for all $i\leq j$, induce maps on the homology vector spaces $H_p(K_i)\to H_p(K_j)$ for all $0\leq p\leq d$. This collection of vector spaces and maps forms a diagram called a {\bf persistence module} (Fig.~1(a)) \cite{chazal-oudot}. \begin{figure}[H]\label{fig_pers_int_mod} \centering \begin{tikzcd}[row sep=0.1cm] (a) & 0 \ar[r] & V_{1} \ar[r] & V_{2} \ar[r] & \cdots \ar[r] & V_{m-1} \ar[r] & V_{m} \\ (b) & 0 \ar[r] & \mathbb{F}_2 \ar[r, "\mathbf{1}"] & \mathbb{F}_2 \ar[r, "\mathbf{1}"] & \cdots \ar[r, "\mathbf{1}"] & \mathbb{F}_2 \ar[r] & 0 \\ & \scriptstyle\cdots & \scriptstyle a & \scriptstyle a+1 & \scriptstyle \cdots & \scriptstyle b & \scriptstyle b+1 \end{tikzcd} \caption{(a) A persistence module; (b) An interval module with interval $[a,b]$.} \end{figure} Since we consider only simplicial complexes with finitely many simplices, the vectors spaces are finite-dimensional. In this case, a persistence module admits a nice decomposition into interval modules, which consist of copies of $\mathbb{F}_2$ connected by the identity morphism for the indices inside an interval, and zero otherwise (Fig.~1(b)) \cite{crawley-boevey}. The collection of intervals in the decomposition of a persistence module is called a {\bf barcode} \cite{barcode_carlssonetal, barcode_ghrist}, and it is an invariant of isomorphism type. In \cite[Sec.~VII]{edels_harer}, the standard algorithm to retrieve the barcode of a filtered simplicial complex is described. This algorithm retrieves the barcode by studying the lowest elements in the columns of the boundary matrix, whose indices form the so-called (column) pivots (see Definition~\ref{def_pivot_column}). Namely, the algorithm performs left-to-right column additions on columns with the same pivot until no two columns share the same pivot. \section{Row vs column pivot pairing}\label{section_eq_relations} The (column) pivot pairing in a reduced boundary matrix $\partial$ provides the lifespan intervals of the homological features of a persistence module \cite{edels_harer}. Usually, the reduction is performed using only one type of elementary column operation: adding a column to a later column. Here, we prove that also a reduction performed using only one type of elementary row operation, namely adding a row to a previous row, achieves the same pairing (cf.~\cite{Edel-Olsb}). The reason why other types of elementary row (column) operations are not allowed is that they do not preserve the order of the generators, and thus cannot maintain the pairing. \medskip Let $FK$ be a filtered simplicial complex, as described in \cref{section_preliminaries}, with boundary matrix $\partial$. For the $i$-th row of $\partial$, let $\leftp{i}$ denote the column index of the leftmost element of such row. If row $i$ is zero, set $\leftp{i}=0$. \begin{definition}\label{def_pivot_row} A matrix $R$ is called {\bf row reduced} if $\leftp{i}\neq \leftp{i'}$ for all non-zero rows $i\neq i'$. An index $j$ is called a {\bf row pivot} (of $R$) if there exists a row $i$ of $R$ such that $j=\leftp{i}$. \end{definition} We recall the some standard notions from \cite{edels_harer}. The symbol $\lowp{j}$ denotes the index row of the lowest element of column $j$. If column $j$ is trivial, then $\lowp{j}=0$. \begin{definition}\label{def_pivot_column} A matrix $C$ is called {\bf column reduced} if $\lowp{j}\neq \lowp{j'}$ for all non-zero columns $j\neq j'$. An index $i$ is called a {\bf column pivot} (of $C$) if there exists a column $j$ of $C$ such that $j=\lowp{i}$. \end{definition} Algorithm \ref{algorithm_row_pivot_red}, called {\bf row pivot reduction}, takes as input the boundary matrix $\partial$ of a filtered simplicial complex $FK$ and reduces it by row operations. This algorithm is one of the possible methods to achieve a row reduced matrix. Indeed, several different row reduced matrices can be obtained by the same boundary matrix $\partial$. This follows from the fact that, to the right of each row pivot, there can be several non-zero elements that do not affect the row pivots. Let $m$ be the number of rows of $\partial$. \begin{algorithm}[H]\label{algorithm_row_pivot_red} \caption{{\small Row pivot reduction}} \DontPrintSemicolon \KwIn{Boundary matrix $\partial$} \KwOut{Row reduced boundary matrix $\partial$} $R = \partial$ \\ \For{$i = m,\dots,1$}{ \If{$\leftp{i}\neq 0$}{ \While{there exists $i' > i$ with $\leftp{i'}=\leftp{i}\neq 0$}{ add row $i'$ to row $i$} } } \end{algorithm} In matrix notation, Algorithm \ref{algorithm_row_pivot_red} computes the reduced matrix as $R=W\cdot \partial$, where $W$ is an invertible upper-triangular matrix with $\mathbb{F}_2$-coefficients. \medskip For a matrix $D$, consider the following value: \[ r_{D}\left(i,j\right):= \rnk D_{i}^{j} - \rnk D_{i+1}^{j} + \rnk D_{i+1}^{j-1} - \rnk D_{i}^{j-1} \] where $D_{i}^{j}$ is the lower left submatrix of $D$, given by all the rows of $D$ with index $h\geq i$ and all the columns with index $l \leq j$. The Pairing Lemma \cite{edels_harer} states that, for a column reduced matrix $C$ of a boundary matrix $\partial$, $i=\lowp{j}$ in $C$ if and only if $r_{\partial}\left(i,j\right)=1$. An analogous result holds for row reduced matrices (cf.~\cite[Lem 2.2]{Edel-Olsb}): \begin{lemma}[Row pairing lemma]\label{equivalence_pivot} Let $\partial$ be a boundary matrix and $R$ a row reduced matrix of $\partial$. Then $j=\leftp{i}$ in $R$ if and only if $r_{\partial}\left(i,j\right)=1$. \end{lemma} The proof is precisely the same as the Pairing Lemma \cite{edels_harer} since the used technique relies on the lower-left submatrices. Moreover, from the Pairing Lemma \cite{edels_harer} and the above Lemma \ref{equivalence_pivot}, $j=\leftp{i}$ in a row reduced matrix $R$ of $\partial$ if and only if $i=low\left(j\right)$ in a column reduced matrix $C$ of $\partial$. In particular, if $j=\leftp{i}$ or $i=\lowp{j}$, the indices $\left(i, j\right)$ form a {\bf persistence pair}. \begin{remark} Since the coboundary matrix is the anti-transpose of the boundary one (i.e. an element in position $(i,j)$ is sent to position $(m+1-j,m+1-i)$), Algorithm \ref{algorithm_row_pivot_red} performs the standard column reduction on the coboundary matrix. Indeed, for a reduced matrix $R$, $j=\leftp{i}$ if and only if $i=\lowp{j}$ in its anti-transpose $R^{-T}$. Thus, Lemma \ref{equivalence_pivot} provides an alternative proof of the correctness of the standard persistence algorithm in cohomology, result originally showed in \cite{dualities}. \end{remark} The running time of Algorithm \ref{algorithm_row_pivot_red} is at most cubic in the number of simplices, as it is for the standard persistence algorithm. We now refine this estimate a little. \begin{point}\label{point_computational_costs} {\em Computational costs of the reduction.} In \cite{edels_harer}, it is shown that the running time of the inner (i.e. while) loop in the standard persistence algorithm for the column $j$, representing a $h$-simplex $\sigma_{j}$ and whose column pivot is in row $i$, is $(h+1)(j-i)^2$. If $\sigma_{j}$ is positive, i.e. at the end of the reduction column $j$ is trivial, then the cost is higher: $(h+1)(j-1)^2$. When reducing the coboundary matrix via column operations, as in \cite{ripser_paper, dualities}, the running time becomes $c(j-i)^2$, where $c$ is the number of cofaces of the simplex $\sigma_{j}$, and the cost of reducing a positive column is $c(j-1)^2$. When reducing the boundary matrix via row operations, as in Algorithm \ref{algorithm_row_pivot_red}, the running time of the inner loop in Algorithm \ref{algorithm_row_pivot_red} for the row $i$, representing a simplex $\sigma_{i}$ and whose row pivot is in column $j$, is $c(j-i)^2$. Note that, if $\sigma_{i}$ is negative, i.e. row $i$ becomes zero at the end of the reduction, then the cost is $c(m-j)^2$, where $m$ is the number of rows. Thus, using row operations, the negative rows are the more expensive to reduce, dually to what happens when reducing by columns. \end{point} \section{Clear and compress}\label{section_clear_compress} We now recall two standard runtime optimisations from \cite{clearcompress, twist}, and show their duality using row and column reductions. Similar observations can be found in \cite{abcw}. \medskip A simplex in the filtered simplicial complex $FK$ is called {\bf positive} if it causes the birth of a homological class, and {\bf negative} if it causes the death of a homological class. By extension, columns and rows in $\partial$ are called positive (resp. negative) if the corresponding simplices are positive (negative). \begin{point}\label{point_clearing} {\em Clear.} The {\bf clear} optimisation is based on the fact that if a row of index $j$ is positive, the $j$-th column of $\partial$ cannot be negative. As was already observed in \cite{clearcompress, twist}, this optimisation is particularly effective when performed on the boundary matrices in decreasing degrees, or, as shown in \cite{phat_paper}, when applied to the coboundary matrices in increasing degrees. Since the clear avoids reducing columns that are already known not to contain pivots, it is quite helpful in the persistent algorithms up-to-date. However, it is not so useful when reducing by rows, since it shrinks by one the length of each row, but does not avoid any reduction. \end{point} \begin{point}\label{point_compress} {\em Compress.} The {\bf compress} optimisation hinges on the fact that if a column of index $i$ is negative, the $i$-th row of $\partial$ cannot be positive. From \cref{section_eq_relations}, it follows the real advantages of the compress optimisation are obtained when the matrix reduction is performed using row operations. Indeed, in this case, it avoids a costly loop whose results is already known, while, in accordance with previous results \cite{phat_paper}, it is quite inefficient when applied using column operations because it only shortens the columns by one element. Performed using the row reduction, the compress is particularly effective when applied to the boundary matrices in increasing degrees. \end{point} Finally, for what we showed, in the computation of the barcode of a filtered simplicial complex the number of rows that need to be reduced in the boundary matrix using the compress optimisation is the same as the number of columns that have to be processed in the coboundary matrix when exploiting the clear optimisation. In the case of acyclic complexes, as done in \cite{ripser_paper, abcw}, we can be more precise and show that this number is \begin{equation*} \displaystyle\sum_{h=0}^{d+1}\binom{v-1}{h} \end{equation*} where $d$ is the maximal dimension of the acyclic filtered simplicial complex and $v$ the number of vertices. It follows that any algorithm that reduces the coboundary matrix using column operations and the clear can be described as reducing the boundary matrix using row operations and the compress. \paragraph*{Acknowledgments.} The author was supported by FAR2019-UniMORE and by the Austrian Science Fund (FWF) grant number P 29984-N35. The author thanks Claudia Landi, Michael Kerber, Wojciech Chach{\'o}lski, and H\aa vard B. Bjerkevik for useful discussions and feedback. \footnotesize
{'timestamp': '2021-03-12T02:23:19', 'yymm': '2101', 'arxiv_id': '2101.00451', 'language': 'en', 'url': 'https://arxiv.org/abs/2101.00451'}
arxiv
\section{Introduction}\label{sec:introduction}} \IEEEPARstart{D}{}epth estimation is often the starting point for solving higher level computer vision tasks such as tracking, localization, navigation and more. Although a variety of active sensors are available for this purpose, image-based techniques are often preferred thanks to the increasing availability of standard cameras on most consumer devices. Among them, binocular stereo \cite{scharstein2002taxonomy} is one of the most popular and studied in the literature. Given two synchronized images acquired by a calibrated stereo rig, depth can be estimated by means of triangulation after finding the displacement between matching pixels on the two images, \emph{i.e.}{} the \textit{disparity}. This search is limited to a 1D search range in case of rectified images. Specifically, by selecting one of the two images as \textit{reference}, for each pixel we look for the corresponding one on the other view, namely \textit{target}, among a number of candidates on the same, horizontal scanline. Over the past few decades, a great variety of algorithms have been proposed, broadly classified into local or global methods according to the deployed steps formalized in \cite{scharstein2002taxonomy}, that are i) matching cost computation, ii) cost aggregation, iii) disparity optimization and selection, and iv) refinement. Common to all algorithms is the definition of a \textit{cost volume}, collecting for each pixel in the reference image matching costs for corresponding candidates on the target image. Among all, solutions based on the Semi-Global Matching pipeline (SGM \cite{hirschmuller2005accurate}) resulted in the years the most popular thanks to the good trade-off between accuracy and computational complexity. Similar to other computer vision tasks, deep learning has hit stereo matching as well \cite{poggi2020synergies}, at first replacing single steps in the pipeline such as matching cost computation with convolutional neural networks (CNNs) \cite{zbontar2016stereo}, rapidly converging towards end-to-end deep networks \cite{Mayer_2016_CVPR} embodying the entire pipeline. Nowadays, the state-of-the-art is represented by these latter approaches \cite{Zhang2019GANet}, although several limitations still preclude their seamless deployment in real world applications \cite{Tonioni_2019_CVPR,Tonioni_2019_learn2adapt,tonioni2019unsupervised}. In parallel with this rapid evolution, estimating the \textit{confidence} of estimated disparity maps, as shown in Figure \ref{fig:overview}, has grown in popularity. At first used for selecting most reliable estimates or filtering out outliers, more techniques leveraging confidence measures have been studied and developed. Specifically, most methods aim at improving pre-existing stereo algorithms \cite{spyropoulos2014learning,spyropoulos2016correctness}, with particular focus on SGM variants \cite{park2015leveraging,park2018learning,seki2016patch,poggi2016learning,poggi2020learning}. Other notable applications consist into fusion with Time-Of-Flight sensors \cite{marin2016reliable,poggi2020confidence}, as well as domain adapation of deep stereo networks \cite{Tonioni_2017_ICCV,tonioni2019unsupervised}. Starting from the first review in the field \cite{hu2012quantitative}, several strategies to estimate a confidence measure have been proposed in the literature, either hand-made or learned from data by means of machine learning \cite{poggi2017quantitative}. More recent works belonging to this latter category \cite{tosi2018beyond,gul2019pixel,mehltretter2019cnn,Kim_2019_CVPR} rapidly established as state-of-the-art. In this paper, we provide a comprehensive review and evaluation of confidence measures, covering more than 10 years of studies in this field. This extensive survey extends our previous work \cite{poggi2017quantitative}, representing the most recent evaluation available in literature, with the following novelties: \begin{figure*}[t] \centering \renewcommand{\tabcolsep}{1pt} \begin{tabular}{ccc} \includegraphics[width=0.28\textwidth]{images/qualitative/census-CBCA/2012/000011_10.png} & \includegraphics[width=0.28\textwidth]{images/qualitative/mccnn-SGM/2012/disparity.png} & \includegraphics[width=0.28\textwidth]{images/qualitative/mccnn-SGM/2012/k12-laf.png} \\ \end{tabular} \caption{\textbf{Confidence estimation example.} From left to right, reference image, disparity map and estimated confidence map (pixels from black to white encode confidence from lower to higher).} \label{fig:overview} \end{figure*} \begin{itemize} \item We include the latest advances in the field of confidence estimation, either hand-made \cite{veld2018novel} or based on deep learning \cite{tosi2018beyond,gul2019pixel,mehltretter2019cnn,Kim_2019_CVPR} \item We evaluate each confidence measure on a total of 4 realistic datasets, respectively KITTI 2012 \cite{Geiger_CVPR_2012} and 2015 \cite{Menze2015CVPR}, Middlebury 2014 \cite{scharstein2014high} and ETH3D \cite{schops2017multi}, together with the SceneFlow Driving synthetic dataset \cite{Mayer_2016_CVPR}. Indeed, for the first time, we assess the ability of learning-based measures to tackle domain shift issues, training in one domain (\emph{e.g.}, on a synthetic dataset) and testing in different ones (\emph{e.g.}, real). \item For the first time in literature, we evaluate all the considered measures when applied to state-of-the-art 3D end-to-end stereo network, \emph{i.e.}{} GANet \cite{Zhang2019GANet}. \end{itemize} The rest of the manuscript is organized as follows: Section \ref{sec:related} briefly resumes the progressive development in the field of confidence estimation and its applications, Section \ref{sec:hand} introduces the taxonomy of hand-crafted confidence measures, while Section \ref{sec:learning} lists and classifies learning based approaches. Then, Section \ref{sec:results} collects the outcome of our extensive experiments, summarized in Section \ref{sec:discussion} before drawing conclusions in Section \ref{sec:conclusions}. \section{Related Work} \label{sec:related} In last decades, there have been extensive works in stereo confidence measures, mainly based on handcrafted confidence measures~\cite{Egnal2002,Egnal2004,Mordohai2009}. Hu and Mordohai~\cite{hu2012quantitative} performed a taxonomy and evaluation of stereo confidence measures, considering 17 confidence measures and two local algorithms on the two datasets available at that time. Since then novel confidence measures were proposed~\cite{breiman2001random,haeusler2013ensemble,spyropoulos2014learning,spyropoulos2016correctness,park2015leveraging,park2018learning} and more importantly this field was affected by methodologies inspired by the machine learning. To account for the fact that there is no single confidence feature yielding stably optimal performance for all datasets and stereo matching algorithms, methods aiming to benefit from the combination of multiple confidence measures have been proposed~\cite{haeusler2013ensemble,spyropoulos2014learning} with a random forest. Following this strategy, the reliability of confidence measures was further improved by considering more effective features~\cite{park2015leveraging,park2018learning}, an efficient O(1) computation~\cite{poggi2016learning}, and hierarchical aggregation at a superpixel-level~\cite{kim2017feature}. Recent approaches have tried to measure the confidence through deep CNNs~\cite{poggi2016bmvc,seki2016patch,Fu_2017_RFMI,fu2018learning,tosi2018beyond,Shaked_2017_CVPR,kim2019unified,Kim_2019_CVPR,Kim2020adversarial,gul2019pixel,mehltretter2019cnn}. Formally, CNN-based methods first extract the confidence features directly from input cues, i.e. reference image, cost volume, and disparity maps, and then predict the confidence with a classifier. Various methods have been proposed that use the single- or bi-modal input, i.e. left disparity~\cite{poggi2016bmvc}, both left and right disparity~\cite{seki2016patch}, a matching cost~\cite{Shaked_2017_CVPR}, matching cost and disparity~\cite{kim2019unified}, and disparity and color image~\cite{Fu_2017_RFMI,tosi2018beyond}. More recently, Kim et al.~\cite{Kim_2019_CVPR} present a deep network that estimates the confidence by making full use of tri-modal input, including matching cost, disparity, and reference image with a novel fusion technique. Concerning unsupervised training of confidence measures, Mostegel et al.~\cite{MOSTEGEL_CVPR_2016} proposed to determine training labels made of a set of correct disparity assignment and a set of wrong ones, exploiting, respectively, consistencies and contradictions between multiple depth maps. Differently, Tosi et al.~\cite{Tosi_2017_BMVC} leveraged on a pool of confidence measures for the same purpose. This field has also seen the deployment of confidence measures plugged into stereo vision pipelines to improve the overall accuracy as proposed in~\cite{poggi2017quantitative,marin2016reliable,Poggi_ICIAP_2017}. Most previous approaches aimed at improving the accuracy of SGM~\cite{Hirschmuller2008} algorithm exploiting as a cue an estimated match reliability. In addition, confidence measures have been effectively deployed for sensor fusion combining depth maps from multiple sensors~\cite{marin2016reliable} and for embedded stereo systems~\cite{Poggi_ICIAP_2017}. \begin{figure}[t] \centering \begin{tabular}{c} \includegraphics[trim=0.1cm 13cm 21.5cm 0.2cm,clip,width=0.48\textwidth]{images/pami-confidence.pdf} \\ \end{tabular} \caption{ \textbf{Example of cost curves} for a pixel $p$: on x axis, disparity hypotheses $i$, on y axis, matching cost $c_i$. We show an ambiguous curve in black, for which ${d_1}$ and ${d_2}$ (respectively equal to 46 and 48) compete for the role of minimum and other local minima exist (at disparities 22 and 60, the former corresponding to ${d_{2m}}$). We also show an ideal cost curve in blue with a clear winner. Best viewed in color.} \label{fig:costs} \end{figure} \section{Hand-crafted confidence measures} \label{sec:hand} Common to the variety of confidence measures proposed in the literature is using the cost volume as the source of information. However, most measures only process a portion of the cues available from it, ranging from properties of the per-pixel full cost curve down to simply leveraging the output disparity map only. In compliance with previous works \cite{hu2012quantitative,poggi2017quantitative,park2018learning}, we define a taxonomy with the aim of grouping confidence measures into categories according to the input cues extracted from the cost volume. We first define the naming convention used in the rest of this section. Given two rectified images $l$ and $r$ and assuming the former as reference, for each pixel $p$ at coordinates $(x,y)$ a cost curve $c(p)$ is computed. We define the following terms \begin{itemize} \item $l(p),r(p)$: pixel intensity in image $l,r$ \item $c_i(p)$: matching cost for disparity hypothesis $i \in D$ \item $d_1(p)$: winning disparity hypothesis \item $d_2$(p): disparity hypothesis of the second minimum \item $d_{2m}(p)$: disparity hypothesis of the second \textit{smallest} local minimum. Any $c_i$ is a local minimum if $c_i<c_{i\pm1}$, yet $d_{2m}(p)$ may not be defined \item $c_{d_1}(p)$: minimum cost in the curve \item $c_{d_2}(p)$: second minimum in the cost curve \item $c_{d_{2m}}(p)$: second local minimum in the cost curve \item $p^r$: pixel on $r$ at coordinates $x-d_1(p)$ \item $\mu$: mean over a local window, \emph{e.g.}{} $\mu(l(p))$ represents the mean intensity over a window in image $l$. \end{itemize} When omitted, costs and disparities always refer to $l$ as the reference image. Otherwise, we label them as $c^r$ and $d^r$ when assuming $r$ as reference. Fig. \ref{fig:costs} depicts an example of a cost curve, highlighting the positions of specific costs defined earlier. In particular, we show an \textit{ambiguous} curve (black) where several scores compete for the minimum, increasing the likelihood of selecting a wrong disparity with respect to the case of having an \textit{ideal} curve (blue). We are now going to define, in Sec. from \ref{sec:local} to \ref{sec:sgm}, different families of measures according to the input cues they process. To each category, we assign a color that will be recalled when discussing the results of our evaluation. \subsection{\colorbox{localcolor}{Minimum cost and local properties}}\label{sec:local} We group here methods considering only local information in the cost curve, mostly encoded by $c_{d_1}$, $c_{d_2}$, and $c_{d_{2m}}$, from pixel $p$ and eventually its neighbors. Most measures use $c_{d_{2m}}$, that may not be defined as in the case, for instance, of an ideal cost curve. Indeed, variants of these measures, called \textit{naive}, use $c_{d_2}$ that is always defined. \textbf{Matching Score Measure} (MSM) \cite{Egnal2004}, expressed by the negative minimum cost itself (the lower, the higher confidence) \begin{equation}\label{msm} \text{MSM}(p) = -c_{d_1}(p) \end{equation} \textbf{Maximum Margin} (MM) \cite{poggi2017quantitative}, has the difference between the second smallest local minimum and the minimum cost \begin{equation}\label{mm} \text{MM}(p) = c_{d_{2m}}(p) - c_{d_1}(p) \end{equation} \textbf{Maximum Margin Naive} (MMN) \cite{hu2012quantitative}, has the difference between the second minimum and the minimum cost \begin{equation}\label{mmn} \text{MMN}(p) = c_{d_2}(p) - c_{d_1}(p) \end{equation} \textbf{Non-Linear Margin} (NLM) \cite{Haeusler2012evaluation}, has exponential of the MM \begin{equation}\label{nlm} \text{NLM}(p) = e^{\frac{c_{d_{2m}}(p) - c_{d_1}(p)}{2\sigma^2}} \end{equation} \textbf{Non-Linear Margin Naive} (NLMN) \cite{poggi2017quantitative}, has exponential of the MMN \begin{equation}\label{nlmn} \text{NLMN}(p) = e^{\frac{_{d_2}(p) - c_{d_1}(p)}{2\sigma^2}} \end{equation} \textbf{Curvature} (CUR) \cite{Egnal2004}, as the local shape of the cost curve in correspondence of the minimum cost \begin{equation}\label{cur} \text{CUR}(p) = -2c_{d_1}(p) + c_{d_1-1}(p) + c_{d_1+1}(p) \end{equation} \textbf{Local Curve} (LC) \cite{Wedel2009detection}, as the slope of the cost curve between the minimum cost and the higher of its neighbors \begin{equation}\label{lc} \text{LC}(p) = \frac{\max{[c_{d_1-1}(p),c_{d_1+1}(p)]} -c_{d_1}(p)}{\gamma} \end{equation} \textbf{Peak Ratio} (PKR) \cite{Egnal2004}, as the ratio between the second local minima and the minimum cost \begin{equation}\label{pkr} \text{PKR}(p) = \frac{c_{d_{2m}}(p)}{c_{d_1}(p)} \end{equation} \textbf{Peak Ratio Naive} (PKRN) \cite{hu2012quantitative}, as the ratio between the second minima and the minimum cost \begin{equation}\label{pkrn} \text{PKRN}(p) = \frac{c_{d_2}(p)}{c_{d_1}(p)} \end{equation} \textbf{Disparity Ambiguity Measure} (DAM) \cite{haeusler2013ensemble}, as the distance between two disparity hypotheses expressed by the minimum cost and the second minima \begin{equation}\label{dam} \text{DAM}(p) = |d_1(p) - d_2(p)| \end{equation} \textbf{Average Peak Ratio} (APKR) \cite{kim2014stereo}, as the average of ratios between costs for pixels $q$ in window, respectively in the same position of the second smallest local minimum and the minimum cost in $p$ \begin{equation}\label{apkr} \text{APKR}(p) = \sum_{q \in N(p)} \frac{c_{d_{2m}(p)}(q)}{c_{d_1(p)}(q)} \end{equation} \textbf{Average Peak Ratio Naive} (APKRN) \cite{poggi2017quantitative}, naive variant of the previous measure replacing second smallest local minimum with second minimum \begin{equation}\label{apkrn} \text{APKRN}(p) = \sum_{q \in N(p)} \frac{c_{d_2(p)}(q)}{c_{d_1(p)}(q)} \end{equation} \textbf{Weighted Peak Ratio} (WPKR) \cite{kim2016weighted}, as the average of ratios as defined for APKR. Each ratio is multiplied by a binary weight $\alpha(p,q)=1$ if the difference between pixel intensities $l(p)$ and $r(q)$ is lower than a threshold $w$ \begin{equation}\label{wpkr} \text{WPKR}(p) = \sum_{q \in N(p)} \alpha(p,q) \cdot \frac{c_{d_{2m}(p)}(q)}{c_{d_1(p)}(q)} \end{equation} \textbf{Weighted Peak Ratio Naive} (WPKRN) \cite{poggi2017quantitative}, naive variant of the previous measure replacing second smallest local minimum with second minimum \begin{equation}\label{wpkrn} \text{WPKRN}(p) = \sum_{q \in N(p)} \alpha(p,q) \cdot \frac{c_{d_2(p)}(q)}{c_{d_1(p)}(q)} \end{equation} \textbf{Semi-Global Energy} (SGE) \cite{haeusler2013ensemble}, inspired by the the Semi-Global Matching algorithm and computing confidence by summing penalties P1, P2 to the minimum cost as \begin{equation}\label{sge} \begin{split} \text{SGE} = \sum_{s \in \mathcal{S}} \sum_{q \in s(p)} c_{d_1}(q) &+ P1\cdot t[d_1(q)-d_1(q')= 1] \\ &+ P2\cdot t[d_1(q)-d_1(q') > 1] \end{split} \end{equation} with $s$ being a scanline ray from a set of rays $\mathcal{S}$ emerging from $p$, $s(p)$ a set of pixels along the ray in a local window $N(p)$ and $q'$ the successor of $q$ along the ray. The binary operator $t[\cdot]$ is 1 when the expression holds and 0 otherwise. Thus, P1 and P2 penalize respectively small and larger disparity margins between neighboring pixels along $s$. \subsection{\colorbox{fullcolor}{The entire cost curve}} We group here methods considering the entire cost curve, from pixel $p$ and eventually its neighbors \textbf{Perturbation measure} (PER) \cite{haeusler2013ensemble}, capturing the deviation of the cost curve to an ideal one as shown in Fig. \ref{fig:costs} \begin{equation}\label{per} \text{PER}(p) = \sum_{i \neq d_1} e^{-\frac{[c_{d_1}(p) - c_i(p)]^2}{s^2}} \end{equation} \textbf{Maximum Likelihood Measure} (MLM) \cite{Matthies1192stereo}, as a probability density function for the predicted disparity given the matching costs, by assuming that the cost function follows a normal distribution and that the disparity prior is uniform \cite{hu2012quantitative} \begin{equation}\label{mlm} \text{MLM}(p) = \frac{e^{-\frac{c_{d_1}(p)}{2\sigma}}}{\sum_{i \in D} e^{-\frac{c_{i}(p)}{2\sigma}}} \end{equation} \textbf{Attainable Likelihood Measure} (ALM) \cite{Matthies1192stereo}, modeling the cost function in $p$ using a Gaussian distribution centered at $c_{d_1}(p)$, thus making the numerator equal to 1 \begin{equation}\label{alm} \text{ALM}(p) = \frac{1}{\sum_{i \in D} e^{-\frac{c_{i}(p)}{2\sigma}}} \end{equation} \textbf{Number of Inflections} (NOI) \cite{hu2012quantitative}, as the number of local minima in the cost curve \begin{equation}\label{noi} \text{NOI}(p) = \# \bigcup_{i \in D} c_{i}(p) < c_{i\pm1}(p) \end{equation} with $\#$ denoting the cardinality of the set. \textbf{Local Minima in Neighborhood} (LMN) \cite{kim2014stereo}, as the number of pixels $q$ in a local window $N(p)$ for which costs $c_{d_1(p)}(q)$ are local minima \begin{equation}\label{lmn} \text{LMN}(p) = \# \bigcup_{q \in N(p)} c_{d_1(p)}(q) < c_{d_1(p)\pm1}(q) \end{equation} \textbf{Winner Margin} (WMN) \cite{Scharstein1996stereo}, as the difference between the second local minima and the minimum cost, normalized over the entire cost curve \begin{equation}\label{wmn} \text{WMN}(p) = \frac{c_{d_{2m}}(p) - c_{d_1}(p)}{\sum_{i \in D} c_i} \end{equation} \textbf{Winner Margin Naive} (WMNN) \cite{hu2012quantitative}, as the difference between the second minima and the minimum cost, normalized over the entire cost curve \begin{equation}\label{wmnn} \text{WMNN}(p) = \frac{c_{d_2}(p) - c_{d_1}(p)}{\sum_{i \in D} c_i} \end{equation} \textbf{Negative Entropy Measure} (NEM) \cite{Scharstein1996stereo}, relates the degree of uncertainty to the negative entropy of the minimum matching cost \begin{equation}\label{nem} \text{NEM}(p) = \sum \frac{e^{-c_{d_1}}}{\sum_{i \in D} e^{-c_i}} \cdot \log{\frac{e^{-c_{d_1}}}{\sum_{i \in D} e^{-c_i}}} \end{equation} \textbf{Pixel-Wise Cost Function Analysis} (PWCFA) \cite{veld2018novel}, aimed at detecting multiple local minima close to c$_{d_1}$ \begin{equation}\label{pwcfa} \text{PWCFA}(p) = \frac{1}{\sum_{i \in D} \frac{\max( \min( |i-d_1|-1, \frac{d_{max}-d_{min}}{3}), 0)^2}{\max(c_i-c_{d_1}- \frac{\sum_{i \in D} c_i}{3(d_{max}-d_{min})} ,1)}} \end{equation} In our experiments, being costs normalized in $[0,1]$, we replace $\frac{d_{max}-d_{min}}{3}$ with $\frac{1}{3}$. \subsection{\colorbox{lrcolor}{Left-right consistency}} This category evaluates the consistency between corresponding pixels across left and right views according to symmetric (on both left and right views) or asymmetric cues (based on left view only). \textbf{Left-Right Consistency} (LRC) \cite{Egnal2002}, measures the difference between disparity $d_1$ estimated for $p$ on the left map and disparity $d^r_1$ on the right map for $p^r$. The lower the difference, the higher the confidence \begin{equation}\label{lrc} \text{LRC}(p) = - |d_1(p) - d^r_1(p^r)| \end{equation} \textbf{Left-Right Difference} (LRD) \cite{hu2012quantitative}, encodes the margin between the first and second minima on the left disparity map, divided by the difference between minimum costs of corresponding pixels $p,p^r$, respectively on left and right disparity maps \begin{equation}\label{lrd} \text{LRD}(p) = \frac{c_{d_2}(p)-c_{d_1}(p)}{|c_{d_1}(p) - c_{d^r_1}(p^r)|} \end{equation} \textbf{Zero-Mean Sum of Absolute Differences} (ZSAD) \cite{haeusler2013ensemble}, as the zero-mean difference in intensities between local windows centered in $p$ and $p^r$ \begin{equation}\label{zsad} \text{ZSAD}(p) = \sum_{q \in N(p)} | l(q) - \mu l(p) - r(q^r) + \mu r(p^r) | \end{equation} \textbf{Asymmetric Consistency Check} (ACC) \cite{Min2010asymmetric}, checking if any neighbor of $p$, on the same horizontal scanline, collides with it, \emph{i.e.}{} if it matches with the same pixel on the right image. In such a case, low confidence is assigned if $d_1(p)$ is not the maximum hypothesis among colliding hypothesis $d_1(q)$ or if $c_{d_1}(p)$ is not the minimum among costs $c_{d_1}(q)$ \begin{equation}\label{acc} \text{ACC}(p) = \begin{cases} 0 & \text{if } p^r \in \bigcup_{q \in Q} q^r \text{ and} \\ & [d_1(p) \neq \max{q \in Q} d_1(q) \text{ or }\\ & c_1(p) \neq \min{q \in Q} c_1(q)] \\ 1 & \text{otherwise } \\ \end{cases} \end{equation} with $Q$ being the set of pixels $q$ having $x$ coordinate varying between $-d_1(p)$ and $(d_{max}-d_1(p))$ around $p$. \textbf{Uniqueness Constraint} (UC) \cite{UC}, a binary confidence assigning 0 to all colliding pixels, except the one with minimum cost \begin{equation}\label{uc} \text{UC}(p) = \begin{cases} 0 & \text{if } p^r \in \bigcup_{q \in Q} q^r \text{ and} \\ & c_1(p) \neq \min{q \in Q} c_1(q)] \\ 1 & \text{otherwise } \\ \end{cases} \end{equation} \textbf{Uniqueness Constraint Cost} (UCC) \cite{poggi2017quantitative}, assigning 0 to all colliding pixels, except the one with minimum cost for which the cost itself is assumed as confidence (the lower, the more confident) \begin{equation}\label{ucc} \text{UCC}(p) = \begin{cases} 0 & \text{if } p^r \in \bigcup_{q \in Q} q^r \text{ and} \\ & c_1(p) \neq \min{q \in Q} c_1(q)] \\ -c_{d_1} & \text{otherwise } \\ \end{cases} \end{equation} \textbf{Uniqueness Constraint Occurrence} (UCO) \cite{poggi2017quantitative}, as the number of pixels $q$ colliding with $p$ (the lower, the more confident) \begin{equation}\label{uco} \text{UCO}(p) = - \# \bigcup_{q \in Q} p^r = q^r \end{equation} \subsection{\colorbox{dispcolor}{Disparity map analysis}} Confidence measures belonging to this group are obtained by extracting features from the reference disparity map, with no additional cues from the cost volume. \textbf{Distance to Discontinuities} (DTD) \cite{spyropoulos2014learning}, as the minimum distance to a depth discontinuity, which often represents a challenge for correct matching \begin{equation}\label{dtd} \text{DTD}(p) = \min_{q \in \hat{d}} |p-q| \end{equation} with $\hat{d}$ being obtained by applying an edge detector to the disparity map \textbf{Disparity Map Variance} (DMV) \cite{haeusler2013ensemble}, defined as the norm of the gradient computed over the disparity map \begin{equation}\label{dmv} \text{DMV}(p) = ||\nabla d_1(p)|| \end{equation} \textbf{Variance of disparity} (VAR) \cite{park2015leveraging}, as the statistical variance on a neighborhood $N(p)$. The higher is the variance, the noisier the disparity map is \begin{equation}\label{var} \text{VAR}(p) = -\frac{1}{\#N(p)} \sum_{q \in N(p)} [d_1(q) - \mu(d_1(p)) ]^2 \end{equation} \textbf{Disparity skewness} (SKEW) \cite{park2018learning}, as the asymmetry on the statistical distribution on a neighborhood $N(p)$. High skewness can identify noisy regions in the disparity map \begin{equation}\label{skew} \text{SKEW}(p) = -\frac{1}{\#N(p)} \sum_{q \in N(p)} [d_1(q) - \mu(d_1(p)) ]^3 \end{equation} \textbf{Median Disparity Deviation} (MDD) \cite{spyropoulos2014learning}, as the distance from the median disparity (MED) computed over $N(p)$ (the lower, the more confident) \begin{equation}\label{mdd} \text{MDD}(p) = -|d_1(p) - \text{MED}(d_1(p))| \end{equation} \textbf{Mean Disparity Deviation} (MND) \cite{park2018learning}, as the distance from the mean disparity computed over $N(p)$ (the lower, the more confident) \begin{equation}\label{mnd} \text{MND}(p) = -|d_1(p) - \mu(d_1(p))| \end{equation} \textbf{Disparity Agreement} (DA) \cite{poggi2016learning}, as the number of pixels sharing the same disparity estimate in a local neighborhood (the higher, the more confident) \begin{equation}\label{da} \text{DA}(p) = H[d_1(p)](p) \end{equation} with H being the histogram of disparity distribution defined over N(p) \begin{equation} H[i](p) = \# \bigcup_{q \in N(p)} d_1(q) = i \end{equation} \textbf{Disparity Scattering} (DS) \cite{poggi2016learning}, encoding the amount of different disparity hypothesis in a local neighborhood (the lower, the more confident) \begin{equation}\label{ds} \text{DS}(p) = - \log \frac{\sum_{i \in D} t[H[i](p) > 0] }{\#N(p)} \end{equation} with $t[..]$ being 1 when the expression holds and 0 otherwise. \subsection{\colorbox{imagecolor}{Reference image analysis}} Confidence measures belonging to this category use as input domain only the reference image or some priors \textbf{Distance from Border} (DB) \cite{spyropoulos2014learning}, encoding the distance from the closest image border, where information is lower \begin{equation}\label{db} \text{DB}(p) = \min (x,y,W-x,H-y) \end{equation} with $W,H$ respectively image width and height. \textbf{Distance from Left Border} (DLB) \cite{park2015leveraging}, as the distance from the left border with $d_{max}$ as upper bound, encoding a portion of the reference image $l$ with no matches on $r$ \begin{equation}\label{dlb} \text{DLB}(p) = \min (x,d_{max}) \end{equation} \textbf{Horizontal Gradient Magnitude} (HGM) \cite{haeusler2013ensemble}, as the horizontal gradient over image intensity. Higher gradients should encode regions rich of texture and easier to be matched \begin{equation}\label{hgm} \text{HGM}(p) = |\nabla_x l(p)| \end{equation} \textbf{Distance to image edge} (DTE) \cite{park2015leveraging}, as the minimum distance to an image edge, which often represents a challenge for correct matching \begin{equation}\label{dte} \text{DTE}(p) = \min_{q \in \hat{l}} |p-q| \end{equation} with $\hat{l}$ being obtained by applying an edge detector to reference image $l$. \textbf{Intensity Variance} (IVAR) \cite{park2018learning}, as the statistical variance of pixel intensity on a neighborhood $N(p)$. The higher variance should encode regions rich of texture and easier to be matched \begin{equation}\label{ivar} \text{IVAR}(p) = \frac{1}{\#N(p)} \sum_{q \in N(p)} [l(q) - \mu l(p) ]^2 \end{equation} \subsection{\colorbox{distcolor}{Self-matching}} The idea behind these confidence measures is to exploit the notion of distinctiveness of the examined point within its neighborhoods along the horizontal scanline of the same image. To study such a cue, the self-matching between two instances of the same image is performed, \emph{e.g.}{} a cost curve $c^{ll}(p)$ is obtained by running the stereo algorithm on two $l$ images, assuming $D^{ll}=[-d_{max},d_{max}]$ centered on $p$ and symmetric as in \cite{hu2012quantitative}. \textbf{Distinctiveness} (DTS) \cite{Manduchi1999Distinctiveness}, as the minimum among all costs over $D^{ll}$ range. It encodes the presence of pixels that are very similar to $p$ on the same horizontal scanline \begin{equation}\label{dts} \text{DTS}^l(p) = \min_{i \in D^{ll}} c^{ll}_{i}(p) \end{equation} \textbf{Distinctive Similarity Measure} (DSM) \cite{Yoon2008Distinctive}, combining distinctiveness over $l$ and $r$ and considering the similarity between two potentially corresponding pixels \begin{equation}\label{dsm} \text{DSM}(p) = \frac{\text{DTS}^l(p) \cdot \text{DTS}^r(p^r)}{c_{d_1}(p)^2} \end{equation} \textbf{Self-Aware Matching Measure} (SAMM) \cite{Mordohai2009}, as the correlation coefficient between cost curves $c(p)$ and $c^{ll}(p)$ \begin{equation}\label{samm} \text{SAMM}(p) = \frac{\sum_{i \in D} [c_{i-d_1}(p) - \mu( c(p))]\cdot [c^{ll}_{i}(p) - \mu( c^{ll}(p))]} {\sigma(p)\cdot\sigma^{ll}(p)} \end{equation} with $\sigma$ and $\sigma^{ll}$ being respectively the variance of costs $c(p)$ and $c^{ll}(p)$. \subsection{\colorbox{sgmcolor}{Semi-Global Matching measures}}\label{sec:sgm} This family of measures is tailored to the SGM algorithm, considering specific cues available through this pipeline. \textbf{Sum of Consistent Scanlines} (SCS) \cite{esgm}, as the number of scanline optimizations out of $s$ sharing the same disparity outcome $d^s_1(p)$ of the full SGM algorithm \begin{equation}\label{scs} \text{SCS}(p) = \# \cup_s d^s_1(p) = d_1(p) \end{equation} \textbf{Local-global relationship} (PS) \cite{marin2016reliable}, it studies the relationship between matching costs before and after the semi-global cost aggregation \begin{equation}\label{ps} \begin{split} \text{PS}(p) = \frac{c_{d_2}^*(p) - c_{d_1}^*(p)}{c_{d_1}^*(p)}\cdot&(1-\frac{\min|d_2^*(p)-d_1^*(p)|,\gamma}{\gamma})\cdot \\ &(1-\frac{\min|d_1^*(p)-d_1(p)|,\gamma}{\gamma}) \end{split} \end{equation} \section{Learned confidence measures} \label{sec:learning} The most recent trend in stereo confidence estimation concerns the possibility of \textit{learning} this task directly from data, as in the case of most computer vision problems. We can broadly classify these approaches into two main families: machine learning frameworks and deep learning frameworks. In both, we can distinguish between approaches processing or not the cost volume. \subsection{Machine learning approaches} Methods belonging to this category use classifiers, more specifically random forests \cite{breiman2001random}, fed with a subset of the confidence measures reviewed so far to infer a new confidence value. Among these frameworks, we distinguish three main subcategories, respectively processing the cost volume, the disparity map or being specifically designed for SGM algorithm. In the remainder, we report the composition of the per-pixel features vectors adopted by each proposal, omitting $p$ in the notation for the sake of space. \subsubsection{\colorbox{forestvol}{Cost-volume forests}} \hspace{0.3cm} \textbf{Ensemble Learning (23 features)} (ENS23) \cite{haeusler2013ensemble}, the first attempt to infer a confidence estimate by means of machine learning. It combines several hand-crafted measures and features extracted by running the stereo algorithm at multiple resolutions. The main configuration consists into the following features $\mathcal{F}(\text{ENS}_{23})$ = $(\text{PKR}^{f,h,q},\text{NEM}^{f,h,q},\text{PER}^{f,h,q},\text{LRC}^f,\text{HGM}^{f,h,q}, \\ \text{DMV}^{f,h,q},\text{DAM}^{f,h,q},\text{ZSAD}^{f,h,q},\text{SGE}^f)$, with $^{f,h,q}$ apexes referring to results obtained by running stereo algorithms on $l,r$ at full, half and quarter resolution respectively. \textbf{Ground Control Points} (GCP) \cite{spyropoulos2014learning,spyropoulos2016correctness}, it proposes a compact feature vector computed at single scale \\ $\mathcal{F}(\text{GCP})$ = (\text{MSM}, \text{DB}, \text{MMN}, \text{ALM}, \text{LRC}, \text{LRD}, \text{DTD}, \text{MDD}) with MDD being obtained over a $5\times5$ window $N(p)$. \textbf{Leveraging stereo confidence} (LEV) \cite{park2015leveraging,park2018learning}, it introduces features computed on multiple windows $N(p)$ of increasing size. Two versions with respectively 22 and 50 features have been proposed: $\mathcal{F}(\text{LEV}_{22})$ = (\text{PKR}, \text{PKRN}, \text{MSM}, \text{MM}, \text{WMN}, \text{MLM}, \text{PER}, \text{NEM}, \text{LRD}, \text{LC}, \text{VAR}$^{1,\dots,4}$, \text{DTD}, \text{MDD}$^{1,\dots,4}$, \text{LRC}, \text{HGM}, \text{DLB}) and $\mathcal{F}(\text{LEV}_{50})$ = (\text{MSM}, \text{PKR}, \text{PKRN}, \text{MM}, \text{MMN}, \text{WMN}, \text{WMNN}, \text{MLM}, \text{PER}, \text{NEM}, \text{LRD}, \text{LC}, \text{ALM} \text{DTD}, \text{DTE}, \text{LRC}, \text{HGM}, \text{DLB}, \text{DB}, \text{NOI}, \text{VAR}$^{1,3,4,6,9,14}$, \text{MDD}$^{1,3,4,6,9,14}$, \text{MND}$^{1,3,4,6,9,14}$, \text{SKEW}$^{1,3,4,6,9,14}$, \text{IVAR}$^{1,3,4,6,9,14})$. Features with apex $^i$ are computed on $(3 + 2i)\times(3 + 2i)$ windows, \emph{e.g.}{} MDD$^1$ is computed over a $5\times5$. We replace image gradients with HGM, achieving slightly better results. The authors also propose a method to select the most important features and reduce the vector dimensionality. In our evaluation, we consider the complete vectors, being them the best performing. \textbf{Feature Augmentation} (FA)~\cite{kim2017feature}. Unlike previous methods that predict the confidence based on per-pixel features, FA~\cite{kim2017feature} imposes a spatial consistency on the confidence estimation by introducing a robust set of features extracted from super-pixels, $\mathcal{F}(\text{FA1})$ = (\text{LRC}, \text{DB}, \text{LRD}, \text{MDD}$^{1,2,3}$, \text{MLM}, \text{MSM}) and $\mathcal{F}(\text{FA2})$ = (\text{LRD}, \text{PKRN}, \text{MDD}$^{1,2,3,4}$, \text{MLM}, \text{NEM}), which are concatenated with per-pixel features and enhanced through adaptive filtering. \subsubsection{\colorbox{forestdisp}{Disparity forests}} \hspace{0.3cm} \textbf{Ensemble Learning (7 features)} (ENS7) \cite{haeusler2013ensemble}, a variant of ENS23 extracting seven features from the disparity map and the reference image, resulting in $\mathcal{F}(\text{ENS}_7)$ = (\text{LRC}$^f$,\text{HGM}$^{f,h,q}$,\text{DMV}$^{f,h,q}$). \textbf{O(1) Features} (O1) \cite{poggi2016learning,poggi2020learning}, these methods aim at learning to infer a confidence score only from features that can be computed in constant time from the reference disparity map domain, thus not requiring the cost volume. Two version with respectively 20 \cite{poggi2016learning} and 47 \cite{poggi2020learning} features have been proposed: $\mathcal{F}(\text{O1})$ = (\text{DA}$^{1,\dots,4}$, \text{DS}$^{1,\dots,4}$, \text{MED}$^{1,\dots,4}$, \text{MDD}$^{1,\dots,4}$, \text{VAR}$^{1,\dots,4}$) and $\mathcal{F}(\text{O2})$ = (\text{DA}$^{1,\dots,9}$, \text{DS}$^{1,\dots,9}$, \text{MED}$^{1,\dots,9}$, \text{MDD}$^{1,\dots,9}$, \text{VAR}$^{1,\dots,9}$, \text{DLB}, \text{UC}) \subsubsection{\colorbox{sgmcolor}{SGM-specific forest}} \hspace{0.3cm} \textbf{SGMForest} (SGMF) \cite{schonberger2018SGMForest}, suited for the SGM algorithm, it consider the disparities $d^s_1$ selected by each single scanline $s \in \mathcal{S}$ and their cost $c^z_{d^s_1}$ for each scanline $z \in \mathcal{S}$ \begin{equation} \text{SGMF} = (\bigcup_{s \in \mathcal{S}}d^{s}_1, \bigcup_{(s,z) \in \mathcal{S}\times\mathcal{S} } c^z_{d^s_1}) \end{equation} Originally proposed to improve SGM by selecting the most reliable scanline for each pixel, we recast it to infer a confidence value for the SGM algorithm. \subsection{Deep learning approaches} This latter family groups methods leveraging on CNNs to infer confidence maps. Conversely from previous machine learning approaches, these techniques directly process the input cues, \emph{i.e.}{} reference image, cost volume and disparity maps, without explicit features extraction. In this case we define two subcategories, respectively processing the disparity map as main cue or the cost volume as well. \subsubsection{\colorbox{deepdisp}{Disparity CNNs}} \hspace{0.3cm} \textbf{Confidence CNN} (CCNN) \cite{poggi2016bmvc}, a patch-based CNN processing $9\times9$ patches from the reference disparity map only. A full confidence map can be processed in a single forward pass by means of a fully-convolutional design. \textbf{Patch Based Confidence Prediction} (PBCP) \cite{seki2016patch}, a patch-based network jointly processing $15\times15$ patches from both reference and target disparity map. This latter is warped according to the former. Two versions exist, trading-off accuracy for speed: one for which pixels in the patches are normalized according to the central pixel disparity (\textit{disposable}), for which each patch needs to be process independently, and one for which normalization is turned off (\textit{reusable}), allowing for a single inference on the full-resolution disparity map. \textbf{Early Fusion Network} (EFN) \cite{Fu_2017_RFMI}, extending CCNN by processing the input reference image together with the disparity map. In this variant, $9\times9$ image and disparity patches are concatenated and fed to a single features extractor. \textbf{Late Fusion Network} (LFN) \cite{Fu_2017_RFMI}, combining image and disparity as EFN does, but processing the two $9\times9$ patches by means of two distinct features extractor, then concatenating the resulting features before confidence estimation. \textbf{Multi Modal CNN} (MMC) \cite{fu2018learning}, extending the late fusion model proposed in \cite{Fu_2017_RFMI}. In particular, $15\times15$ patches from the two modalities are processed by two different encoders for disparity and RGB, the latter using dilated convolutions to enlarge the receptive field. \textbf{Global Confidence Network} (ConfNet) \cite{tosi2018beyond}, deploying an U-Net like architecture with larger receptive field in order to include larger content from both the image and disparity map. This network decimates the input resolution by means of max-pool operations, then restoring it by means of transposed convolutions in the decoding part. \textbf{Local-Global Confidence Network} (LGC) \cite{tosi2018beyond}, combines patch-based methodologies \cite{poggi2016bmvc} with ConfNet allowing to reason for both local and global cues at once, combining the fine-grained features extracted by the former with the large image context of the latter. \subsubsection{\colorbox{deepvol}{Cost-volume CNNs}} \hspace{0.3cm} \textbf{Reflective Confidence Network} (RCN)~\cite{Shaked_2017_CVPR} proposes to jointly estimate a confidence measure together with cost optimization at the end of the stereo matching pipeline. By deploying a two-layer fully connected network processing the matching costs, a confidence map is predicted together with the final disparity map. \textbf{Matching Probability Network} (MPN)~\cite{Kim_2017_ICIP} processes the matching cost volume together with the disparity map, through a novel network consisting of cost feature extraction, disparity feature extraction, and fusion modules. To deal with a varying size of cost volume according to stereo pairs, a top-$K$ matching probability volume layer is also proposed in the cost feature extraction module. \textbf{Unified Confidence Network} (UCN)~\cite{kim2019unified}. Similar to RCN~\cite{Shaked_2017_CVPR}, it is also based on the observation that jointly learning cost optimization and confidence estimation is effective at improving the accuracy of the final disparity map of a stereo matching pipeline. UCN~\cite{kim2019unified} proposes a unified network architecture for cost optimization and confidence estimation. An encoder-decoder module refines the matching costs with a larger receptive field in order to obtain a more accurate disparity map. Then a subnetwork processes it together with top-$K$ refined costs to output a confidence map. \textbf{Locally Adaptive Fusion Network} (LAF)~\cite{Kim_2019_CVPR} estimates a confidence map of an initial disparity by making full use of tri-modal input, including cost, disparity, and color image. A key element is to learn locally-varying attention and scale maps to fuse the tri-modal confidence features. In addition, the confidence map is recursively refined to enforce a spatial context and local consistency. \textbf{Adversarial Confidence Network} (ACN)~\cite{Kim2020adversarial}. Similar to RC~\cite{Shaked_2017_CVPR} and UN~\cite{kim2019unified}, it jointly estimates disparity and confidence from stereo image pairs. Especially, ACN~\cite{Kim2020adversarial} accomplishes this via a minmax optimization to learn the generative cost aggregation networks and discriminative confidence estimation networks in an adversarial manner. To fully exploit complementary information of cost, disparity, and color image, a dynamic fusion module is also proposed. \textbf{Pixel-Wise Confidence RNN} (CRNN)~\cite{gul2019pixel} is the first attempt to use a recurrent neural network architecture to compute confidences. To maintain a low complexity, the confidence for a given pixel is purely computed from its associated costs without considering any additional neighbouring pixels. \textbf{Cost Volume Analysis Network} (CVA)~\cite{mehltretter2019cnn}. In order to combine the advantages of deep learning and cost volume features, it directly learns features for estimating confidence from the volumetric data. Specifically, CVA~\cite{mehltretter2019cnn} first fuses a cost volume into a single cost curve using 3D convolutions, and the curve is then processed along the disparity axis by other 3D convolutions with varying depth. \subsection{Others} For completeness, we report techniques aimed at improving the effectiveness of pre-computed confidence maps, although not directly evaluating them in this paper. \textbf{Learning Local Consistency} (++) \cite{poggi2017learning}. This framework learns a more reliable measure exploiting local consistency within neighboring points by processing a pre-computed confidence map by means of a patch-based CNN. \textbf{Even More Confident} (EMC) \cite{poggi2017even}. In this framework, random forest based measures are improved by replacing the ensemble classifier with a patch-based CNN. \begin{table*}[t] \centering \scalebox{0.6}{ \renewcommand{\tabcolsep}{2pt} \begin{tabularx}{2\textwidth}{ccc} \begin{tabular}{.l;l;l.} \toprule Measure & Acronym & Definition\\ \midrule \rowcolor{localcolor} Average Peak Ratio \cite{kim2014stereo}& APKR & Eq. \ref{apkr}\\ Average Peak Ratio Naive \cite{poggi2017quantitative} & APKRN & Eq. \ref{apkrn}\\ Curvature \cite{Egnal2004} & CUR & Eq. \ref{cur} \\ Disparity Ambiguity Measure \cite{haeusler2013ensemble} & DAM & Eq. \ref{dam} \\ Local Curve \cite{Wedel2009detection} & LC & Eq. \ref{lc}\\ Maximum Margin \cite{poggi2017quantitative} & MM & Eq. \ref{mm}\\ Maximum Margin Naive \cite{hu2012quantitative} & MMN & Eq. \ref{mmn}\\ Matching Score Measure \cite{Egnal2004} & MSM & Eq. \ref{msm}\\ Non-Linear Margin \cite{Haeusler2012evaluation} & NLM & Eq. \ref{nlm}\\ Non-Linear Margin Naive \cite{poggi2017quantitative} & NLMN & Eq. \ref{nlmn}\\ Peak Ratio \cite{Egnal2004} & PKR & Eq. \ref{pkr}\\ Peak Ratio Naive \cite{hu2012quantitative} & PKRN & Eq. \ref{pkrn}\\ Semi-Global Enery \cite{haeusler2013ensemble} & SGE & Eq. \ref{sge}\\ Weighted Peak Ratio \cite{kim2016weighted} & WPKR & Eq. \ref{wpkr}\\ Weighted Peak Ratio Naive \cite{poggi2017quantitative} & WPKRN & Eq. \ref{wpkrn}\\ \rowcolor{fullcolor} Attainable Likelihood Measure \cite{Matthies1192stereo} & ALM & Eq. \ref{alm}\\ Local Minima in Neightrhood \cite{kim2014stereo} & LMN & Eq. \ref{lmn}\\ Maximum Likelihood Measure \cite{Matthies1192stereo} & MLM & Eq. \ref{mlm}\\ Negative Entropy Measure \cite{Scharstein1996stereo} & NEM & Eq. \ref{nem}\\ Number of Inflections \cite{hu2012quantitative} & NOI & Eq. \ref{noi}\\ Perturbation measure \cite{haeusler2013ensemble}& PER & Eq. \ref{per}\\ Pixel-Wise Cost Function Analysis \cite{veld2018novel} & PWCFA & Eq. \ref{pwcfa}\\ Winner Margin \cite{Scharstein1996stereo} & WMN & Eq. \ref{wmn}\\ Winner Margin Naive \cite{hu2012quantitative} & WMNN & Eq. \ref{wmnn}\\ \rowcolor{sgmcolor} Local-global relationship \cite{marin2016reliable} & PS & Eq. \ref{ps}\\ \midrule \end{tabular} & \begin{tabular}{.l;l;l.} \toprule Measure & Acronym & Definition\\ \midrule \rowcolor{dispcolor} Disparity Agreement \cite{poggi2016learning} & DA & Eq. \ref{da}\\ Disparity Scattering \cite{poggi2016learning} & DS & Eq. \ref{ds}\\ Disparity Map Variance \cite{haeusler2013ensemble} & DMV & Eq. \ref{dmv}\\ Distance To Discontinuities \cite{spyropoulos2014learning} & DTD & Eq. \ref{dtd}\\ Median Disparity Deviation \cite{spyropoulos2014learning} & MDD & Eq. \ref{mdd}\\ Mean Disparity Deviation \cite{park2018learning} & MND & Eq. \ref{mnd}\\ Disparity skewness \cite{park2018learning} & SKEW & Eq. \ref{skew}\\ Disparity Variance \cite{park2015leveraging} & VAR & Eq. \ref{var}\\ \rowcolor{lrcolor} Asymmetric Consistency Check \cite{Min2010asymmetric} & ACC & Eq. \ref{acc}\\ Left-Right Consistency \cite{Egnal2002} & LRC & Eq. \ref{lrc}\\ Left-Right Difference \cite{hu2012quantitative} & LRD & Eq. \ref{lrd}\\ Uniqueness Constraint \cite{UC} & UC & Eq. \ref{uc}\\ Uniqueness Constraint (Cost) \cite{poggi2017quantitative} & UCC & Eq. \ref{ucc}\\ Uniqueness Constraint (Occurrence) \cite{poggi2017quantitative} & UCO & Eq. \ref{uco}\\ Zero-Mean Sum of Absolute Differences \cite{haeusler2013ensemble} & ZSAD & Eq. \ref{zsad}\\ \rowcolor{distcolor} Distinctiveness \cite{Manduchi1999Distinctiveness} & DTS & Eq. \ref{dts}\\ Distinctive Similarity Measure \cite{Yoon2008Distinctive} & DSM & Eq. \ref{dsm} \\ Self-Aware Matching Measure \cite{Mordohai2009} & SAMM & Eq. \ref{samm}\\ \rowcolor{imagecolor} Distance from Border \cite{spyropoulos2014learning} & DB & Eq. \ref{db} \\ Distance from Left Border \cite{park2015leveraging} & DLB & Eq. \ref{dlb}\\ Distance to image Edge \cite{park2015leveraging} & DTE & Eq. \ref{dte}\\ Horizontal Gradient Magnitude \cite{haeusler2013ensemble} & HGM & Eq. \ref{hgm}\\ Intensity Variance \cite{park2018learning} & IVAR & Eq. \ref{ivar} \\ & & \\ \rowcolor{sgmcolor} Sum of Consistent Scanlines \cite{esgm} & SCS & Eq. \ref{scs}\\ \midrule \end{tabular} & \begin{tabular}{.l;l;l;l;l;l;l.} \toprule Measure & Acronym & Forest & CNN & Image & Volume & Disparity\\ \midrule \rowcolor{forestvol} Ensemble Learning (23 features) \cite{haeusler2013ensemble} & ENS$_{23}$ & \cmark & & \cmark & \cmark & \cmark\\ Ground Control Points \cite{spyropoulos2014learning} & GCP & \cmark & & \cmark & \cmark & \cmark\\ Leveraging stereo confidence (22 features) \cite{park2015leveraging} & LEV$_{22}$ & \cmark & & \cmark & \cmark & \cmark\\ Leveraging stereo confidence (50 features) \cite{park2018learning} & LEV$_{50}$ & \cmark & & \cmark & \cmark & \cmark\\ Feature augmentation \cite{kim2017feature} & FA & \cmark & & \cmark & \cmark & \cmark \\ \rowcolor{forestdisp} Ensemble Learning (7 features) \cite{haeusler2013ensemble} & ENS$_{7}$ & \cmark & & \cmark & & \cmark\\ O(1) (20 features) \cite{poggi2016learning} & O1 & \cmark & & & & \cmark\\ O(1) (47 features) \cite{poggi2020learning} & O2 & \cmark & & \cmark & & \cmark\\ \rowcolor{deepdisp} Confidence CNN \cite{poggi2016bmvc} & CCNN & & \cmark & & & \cmark\\ Patch-based confidence prediction (reusable) \cite{seki2016patch} & PBCP$_{r}$ & & \cmark & & & \cmark \\ Patch-based confidence prediction (disposable) \cite{seki2016patch} & PBCP$_{d}$ & & \cmark & & & \cmark \\ Early Fusion Network \cite{Fu_2017_RFMI} & EFN & & \cmark & \cmark & & \cmark \\ Late Fusion Network \cite{Fu_2017_RFMI} & LFN & & \cmark & \cmark & & \cmark \\ Multi Modal CNN \cite{fu2018learning} & MMC & & \cmark & \cmark & & \cmark \\ Global Confidence Network \cite{tosi2018beyond} & ConfNet & & \cmark & \cmark & & \cmark \\ Local-Global Network \cite{tosi2018beyond} & LGC & & \cmark & \cmark & & \cmark \\ \rowcolor{deepvol} Reflective Confidence Network \cite{Shaked_2017_CVPR} & RCN & & \cmark & & \cmark & \\ Matching Probability Network \cite{Kim_2017_ICIP} & MPN & & \cmark & & \cmark & \cmark \\ Unified Confidence Network \cite{kim2019unified} & UCN & & \cmark & & \cmark & \cmark\\ Locally Adaptive Fusion Network \cite{Kim_2019_CVPR} & LAF & & \cmark & \cmark & \cmark & \cmark\\ Adversarial Confidence Network \cite{Kim2020adversarial} & ACN & & \cmark & \cmark & \cmark & \cmark\\ Pixel-Wise Confidence RNN \cite{gul2019pixel} & CRNN & & \cmark & & \cmark & \\ Cost Volume Analysis Network \cite{mehltretter2019cnn} & CVA & & \cmark & & \cmark & \\ & & \multicolumn{5}{c.}{}\\ \rowcolor{sgmcolor} SGMForest \cite{schonberger2018SGMForest} & SGMF & \cmark & & & \cmark & \\ \midrule \end{tabular} \\ \end{tabularx} } \caption{ \textbf{Taxonomy of confidence measures.} Different colors encode different categories. For each measure, we report its full name, reference paper and acronym. For hand-crafted measures, We point to their definition. For learned measures, we highlight the type of classifier and its input cues.} \label{tab:acronyms} \end{table*} \section{Experimental results} \label{sec:results} In this section, we introduce the reader to our experimental evaluation by describing each dataset and stereo algorithm involved, as well as the evaluation metrics. \subsection{Evaluated measures} We collect the names, acronyms and definition of each of the measures classified in our taxonomy and involved in our evaluation in Table \ref{tab:acronyms}. Measures belonging to the same category are grouped in blocks colored according to the category and listed in alphabetical order. For hand-crafted measures, we point to equations detailing their definition. For learned measures (right-most in the table), we highlight the classifier they use and the input cues they process. The same table structure will be used when evaluating the measures on the different datasets and stereo algorithms. \subsection{Datasets} We describe in detail the datasets on which our evaluation is carried out. Since ground truth disparity is required to assess the performance of confidence estimation, we refer to the training sets made available by each dataset. \textbf{SceneFlow Driving.} The Freiburg SceneFlow dataset \cite{Mayer_2016_CVPR} is a large collection of synthetic images, made of about 39K stereo pairs with ground truth disparity maps. We run experiments on this dataset, aiming in particular at studying the impact of domain shifts on the confidence estimation task for the first time in literature. Purposely, we sample a training set made of 22 stereo pairs from the \textit{backwards} sequences Driving split, since learned-based approaches require very few images for training \cite{poggi2016bmvc,seki2016patch}. We also collect a testing set made of 22 images from \textit{forward} sequences, thus non-overlapping with those from which the training images are sampled. \textbf{KITTI\ 2012.} An outdoor dataset, acquired from static scenes in a driving environment. It is composed of 194 grayscale stereo pairs, recently made available in color format as well. Sparse ground truth disparity was obtained from LIDAR measurements, post-processed by registering a set of consecutive frames (5 before and 5 after) with ICP, then re-projecting accumulated point clouds onto the image and finally manually filtering all ambiguous depth values. We manually split them into 20 training images and keep the remaining 174 for testing following \cite{poggi2017quantitative}, in order to allow for training learned measures on real data as well. \textbf{KITTI\ 2015.} Improved with respect to KITTI\ 2012 and thought for scene flow evaluation, this dataset frames dynamic scenes in driving environments. It is composed of 200 color stereo pairs for which sparse ground truth disparity was obtained with a similar procedure, except for moving objects that were replaced by 3D CAD models (\emph{e.g.}, in the case of cars) fitted into accumulated point clouds and re-projected onto the image and manually filtered. \textbf{Middlebury 2014.} An indoor dataset, made of 15 stereo pairs reaching up to 6 megapixels resolution. Dense ground truth maps are obtained by means of an active stereo pipeline \cite{scharstein2014high}. It represents an open challenge for most stereo algorithms, either hand-crafted or based on deep learning. In our experiments, we process quarter resolution images as in previous works \cite{poggi2017quantitative}. \textbf{ETH3D.} One of the most recent among real-world datasets, made of 27 low-resolution grayscale stereo pairs. To obtain ground truth disparities, the authors recorded the scene geometry with a Faro Focus X 330 laser scanner, taking one or more 360$^\circ$ scans with up to 28 million points each. We evaluate confidence measures on this dataset for the first time in literature. \subsection{Evaluation metrics} We measure the effectiveness of each confidence measure at detecting correct matches, as introduced in \cite{hu2012quantitative}. To this aim, we sort pixels in a disparity map following decreasing order of confidence and gradually compute the error rate (D1) on sparse maps obtained by iterative sampling (\emph{e.g.}, 5\% of pixels each time) from the dense map. D1 is computed as the percentage of pixels having absolute error larger than $\tau$. Plotting the error rates results in a ROC curve, whose AUC quantitatively assesses the confidence effectiveness (the lower, the better). Optimal AUC is obtained if the confidence measure is capable of sampling all correct matches first and is equal to: \begin{equation} \text{AUC}_\text{opt} = \int_{1-\varepsilon}^1 \frac{x - (1-\varepsilon)}{x} dx = \varepsilon + (1-\varepsilon)\ln{(1-\varepsilon)} \end{equation} with $\varepsilon$ being the D1 computed over the disparity map. To have a view over an entire dataset, we compute macro-average AUC scores over the total number of images. To ease readability, we report each AUC score, together with optimal AUCs, multiplied by a factor $\times10^2$. In all the experiments, we set $\tau$ to 3 for Driving, KITTI\ 2012 and KITTI\ 2015 datasets, to 1 for Middlebury 2014\ and ETH3D. According to \cite{hu2012quantitative}, we may also define the AUC for the random chance (i.e., assuming no knowledge about pixels confidence). This is equal to the D1 itself, since no correct matches can be selected in absence of confidence information. Every time the AUC achieved by a confidence measure is lower than the D1, it means it is somehow useful for selection with respect to the random choice. For each stereo algorithm, we will report AUC for the five considered datasets. We will also report the ranking (R.) for each confidence measure according to its average performance over them. Concerning measures computed over a local window, we report in the table the top performing configuration, while we show the behavior of each of them by varying the window size in form of plots. Concerning learned measures, we report results in two main configuration: 1) when trained on the Driving train split and 2) when trained on the 20 KITTI 2012 stereo pairs, on left and right columns in a single table. In the former case, we rank measures both according to their performance on synthetic data (R.) and their cross-domain ranking (CR.) on real data averaging over the four real datasets. In the latter case, we rank measures according to performance on the real domain (R.). \subsection{Stereo Algorithms} We measure the effectiveness of each confidence measure when dealing with the output of four different stereo algorithms, ranging from noisier to more robust, as well as on a deep stereo network. The four hand-crafted pipelines are obtained selecting among two matching costs and two aggregation strategies, described in detail in the remainder. \subsubsection{Matching cost functions} The very first step in a stereo pipeline consists into computing per-pixel matching costs. To this aim, we selected two popular choices, AD-CENSUS and MCCNN-fst. \textbf{AD-CENSUS.} A robust matching function based on the census transform \cite{Zabih_1994_ECCV}. For both left and right images, pixels intensities are replaced by 81 bits strings, computed by cropping a $9\times9$ image patch centered around a given pixel and comparing the intensity values of each neighbor in the patch to the intensity value of the pixel in the center. Then, the absolute distance between pixels is computed in form of the Hamming distance between bits strings. \textbf{MCCNN-fst.} In this case, matching costs are inferred by a deep neural network \cite{zbontar2016stereo} trained to compare image patches and estimate a similarity score between the two. We use the MCCNN-fst variant, because it is much faster, although almost equivalent to the accurate one MCCNN-acrt. We use weights made available by the authors and respectively trained on KITTI\ 2012, KITTI\ 2015 and Middlebury 2014\ for the corresponding datasets. We used weights trained on Middlebury 2014\ to run experiments on ETH3D\ as well, while we trained from scratch a model on the Driving train split for experiments on the same dataset test split. \subsubsection{Aggregation strategies} Given an initial cost volume, the aggregation step aims at reducing noise and ambiguity in the cost curves. According to the strategy deployed, stereo algorithms are usually classified into local and global \cite{scharstein2002taxonomy}. We select two main approaches representative of the two worlds, Cross-based Cost Aggregation (CBCA) and SGM. For both, the source code and parameters as defined in \cite{zbontar2016stereo} are used in our experiments. \textbf{CBCA.} An adaptive, local aggregation strategy. Given a pixel, it builds a support window over a cross \cite{zhang2009cross} including neighbors for which both spatial distance and intensity difference are lower than two respective thresholds. Supports regions $U_l,U_r$ are computed over $I_l, I_r$ and combined as \begin{equation} U_d(p) = \{q | q \in U_l(p), (q - d) \in U_r(p - d)\} \end{equation} Then, initial costs $C_0(p,d)$ sharing the same disparity hypothesis $d$ are summed over the support region $U_d(p)$ to obtain aggregated costs $C_\text{CBCA}(p,d)$. \textbf{SGM.} A semi-global aggregation strategy \cite{hirschmuller2005accurate} combining multiple scanline optimizations. For each, smoothness is enforced by means of two penalties P1 and P2, starting from locally aggregated costs by means of CBCA, as follows: \begin{equation}\label{eq:sgm} \begin{split} C_s(p,d) = &C_\text{CBCA}(p,d) + \min_{o>1}[C_\text{CBCA}(q,d), \\ &C_\text{CBCA}(q,d\pm1)+P1, C_\text{CBCA}(q,d\pm o)+P2] -\\ &\min_{k<d_{max}}(C(q,k)) \\ \end{split} \end{equation} The outcome $C_s$ over each scanline $s$ is then summed to obtain the final cost volume $C_\text{SGM}$. Four paths are considered, along horizontal and vertical directions. \subsubsection{End-to-end stereo} Confidence measures have always been studied in synergy with hand-crafted stereo algorithms, but nowadays end-to-end deep networks represent the preferred choice to infer dense disparity maps. Thus, for the first time in literature, we deeply investigate about confidence estimation in the case of deep stereo networks. \textbf{GANet} \cite{Zhang2019GANet}. A state-of-the-art 3D architecture whose output is a feature volume $\mathcal{C}$ of size $D\times H\times W$ similar to the cost volume processed by hand-crafted stereo algorithms, from which disparity is selected by means of soft-argmax \begin{equation} d = \sum_{i \in D} i \cdot \mathcal{C}_i(p) \end{equation} Accordingly, $\mathcal{C}$ encodes matching probabilities. In our experiments, we convert $\mathcal{C}$ into matching costs by multiplying for $-1$ and compute disparity by replacing the soft-argmax operation with a traditional WTA selection during disparity inference at testing time. This way, all confidence measures can be applied seamlessly as done with hand-crafted algorithms, being disparity selected from the minimum cost. Table \ref{tab:softmax_vs_wta} shows how the WTA selection impacts on disparity accuracy compared to soft-argmax. In general, WTA selection seems better when assuming higher threshold $\tau$, such as on Driving, KITTI 2012 and KITTI 2015. On the other hand, the subpixel accuracy enabled by the soft-argmax strategy allows to improve the error rate when considering $\tau=1$, as in Middlebury and ETH3D dataset. \begin{table}[] \centering \renewcommand{\tabcolsep}{2pt} \begin{tabular}{c|ccccc} \toprule & Driving & KITTI 2012 & KITTI 2015 & Middlebury & ETH \\ & (bad3) & (bad3) & (bad3) & (bad1) & (bad1) \\ \midrule soft-argmax & 17.65\% & 9.51\% & 10.77\% & \textbf{26.89\%} & \textbf{8.73\%} \\ WTA & \textbf{16.66\%} & \textbf{8.47\%} & \textbf{10.02\%} & 28.61\% & 10.80\% \\ \toprule \end{tabular} \caption{\textbf{GANet disparity map accuracy}, with different selection strategies.} \label{tab:softmax_vs_wta} \end{table} For our experiments, we use the weights made available by the authors trained on SceneFlow to avoid over-fitting to any real dataset and simulate deployment in-the-wild. \subsection{Hyper-parameters, training setup, implementation.} In this section, we resume implementations details and parameters tuning for both hand-crafted and learned confidence methods, referring to existing works the sake of space. Concerning hand-crafted measures, all hyper-parameters have been set following our previous work \cite{poggi2017quantitative}\footnote{\url{http://vision.deis.unibo.it/~mpoggi/code/ICCV2017.zip}}. To study the impact of the local windows over confidence measures exploiting local content, we considered the following window sizes, already used in previous works \cite{park2015leveraging,park2018learning,poggi2016learning,poggi2020learning}: $5\times5$, $7\times7$, $9\times9$, $11\times11$, $13\times13$, $15\times15$, $17\times17$, $19\times19$, $21\times21$ and $31\times31$. Concerning learning-based measures, we follow the authors training settings, using the original source code when available\footnote{\url{https://github.com/fabiotosi92/LGC-Tensorflow}}\footnote{\url{https://github.com/seungryong/LAF}}. For methods for which the source code has not been released, we ran experiments using our own code, implementing each approach following the authors' advice at the best of our knowledge. \subsection{CBCA Algorithms} We start by evaluating the performance on local stereo algorithms leveraging CBCA cost optimization. Although they rarely are the final source of disparity maps, several works \cite{park2015leveraging,park2018learning,poggi2016learning,poggi2020learning,seki2016patch} proposed improved SGM variants exploiting the confidence estimated over intermediate results, often coming from CBCA methods. This makes the evaluation of confidence in this setting valuable as well. In the remainder, all results will be collected in tables, where each entry is colored differently to recall the aforementioned classes of measures. \subsubsection{CENSUS-CBCA} In this section, we discuss the outcome of our experiments carried out with Census-CBCA algorithm. \textbf{Hand-crafted measures.} Table \ref{tab:census_cbca_hand} shows the performance achieved by the hand-crafted measures, \emph{i.e.} not involving machine learning at all. Among them, the top-3 measures are DA$_{31}$, VAR$_{9}$ and APKR$_{7}$, that are computed over a local window. This suggests that the local context, either from the disparity domain or the cost volume, can be a powerful cue to estimate the per-pixel confidence. The first measures using single pixel information are LRD and PKR. The top-9 measures, except LRD, belong to the \colorbox{localcolor}{local properties} or \colorbox{dispcolor}{disparity domain} families, with WMN and WMNN ranking 11 and 12 and being the first measures using the \colorbox{fullcolor}{entire cost curve}. Confidence estimated from \colorbox{lrcolor}{left-right consistency}, after finding LRD at rank 5, only appears at rank 25 with UCC, performing better than LRC on the noisy outputs of Census-CBCA. \colorbox{distcolor}{Self-matching} measures show up at 26 and 28 positions with SAMM and DSM, while \colorbox{imagecolor}{image properties} produce, not surprisingly, poor results. \begin{table}[t] \centering \scalebox{0.68}{ \renewcommand{\tabcolsep}{2pt} \begin{tabularx}{\textwidth}{cc} \begin{tabular}{.l;c|c|c|c|c;c.} \toprule & Driv. & 2012 & 2015 & Midd. & ETH & R.\\ \midrule \rowcolor{localcolor} APKR$_{7}$ & 20.64 & 9.32 & 7.78 & 12.54 & 8.33 & 3\\ APKRN$_{5}$ & 25.95 & 11.15 & 9.79 & 11.91 & 8.74 & 14\\ CUR & 33.33 & 19.94 & 14.71 & 14.51 & 10.72 & 33\\ DAM & 30.56 & 17.81 & 15.97 & 22.07 & 16.13 & 36\\ LC & 31.45 & 18.63 & 14.29 & 14.24 & 10.66 & 32\\ MM & 21.50 & 10.46 & 8.83 & 12.14 & 8.57 & 7\\ MMN & 28.51 & 13.15 & 11.68 & 12.31 & 9.47 & 20\\ MSM & 22.28 & 17.12 & 15.06 & 17.61 & 15.30 & 30\\ NLM & 21.50 & 10.46 & 8.83 & 12.15 & 8.57 & 8\\ NLMN & 28.51 & 13.16 & 11.68 & 12.31 & 9.47 & 21\\ PKR & 20.85 & 10.55 & 8.90 & 12.40 & 8.64 & 6\\ PKRN & 25.66 & 11.83 & 10.32 & 11.42 & 8.84 & 15\\ SGE & 22.06 & 16.98 & 14.97 & 17.81 & 15.41 & 29\\ WPKR$_{5}$ & 21.96 & 10.16 & 8.63 & 12.49 & 8.51 & 9\\ WPKRN$_{5}$ & 26.95 & 12.93 & 11.63 & 12.58 & 9.18 & 18\\ \rowcolor{fullcolor} ALM & 20.76 & 14.77 & 13.03 & 16.20 & 12.79 & 24\\ LMN & 39.19 & 26.79 & 19.57 & 22.43 & 15.85 & 39\\ MLM & 20.23 & 13.31 & 11.58 & 14.67 & 11.70 & 17\\ NEM & 30.99 & 24.75 & 21.30 & 29.93 & 20.55 & 44\\ NOI & 33.15 & 25.56 & 21.36 & 28.15 & 18.74 & 42\\ PER & 20.70 & 14.59 & 12.84 & 15.98 & 12.65 & 23\\ PWCFA & 20.72 & 12.91 & 11.63 & 14.01 & 11.21 & 16\\ WMN & 20.94 & 11.25 & 9.45 & 12.63 & 9.07 & 11\\ WMNN & 24.64 & 11.73 & 10.15 & 11.33 & 9.11 & 12\\ \midrule \rowcolor{white} Opt. & 12.00 & 4.72 & 3.40 & 5.31 & 4.07 & -\\ D1(\%) & 43.58 & 27.19 & 22.28 & 28.70 & 21.27 & -\\ \midrule \end{tabular} & \begin{tabular}{.l;c|c|c|c|c;c.} \toprule & Driv. & 2012 & 2015 & Midd. & ETH & R. \\ \midrule \rowcolor{dispcolor} DA$_{31}$ & 23.12 & \underline{7.95} & 6.45 & 12.92 & \underline{6.07} & 1\\ DMV & 25.91 & 11.46 & 9.26 & 18.45 & 14.40 & 27 \\ DS$_{17}$ & 21.85 & 9.27 & 7.62 & 12.27 & 8.05 & 4\\ DTD & 22.18 & 11.87 & 11.93 & 17.75 & 11.50 & 22\\ MDD$_{21}$ & 22.79 & 7.88 & \underline{6.01} & 17.95 & 12.54 & 13\\ MND$_{19}$ & 20.93 & 9.93 & 7.98 & 14.05 & 9.57 & 10\\ SKEW$_{7}$ & 22.25 & 11.27 & 9.47 & 17.57 & 13.22 & 19\\ VAR$_{9}$ & \underline{20.16} & 9.88 & 8.03 & \underline{11.99} & 8.36 & 2\\ \rowcolor{lrcolor} ACC & 32.75 & 17.35 & 13.70 & 19.16 & 14.53 & 35\\ LRC & 31.13 & 14.20 & 11.35 & 18.91 & 13.45 & 31\\ LRD & 23.54 & 9.65 & 8.05 & 10.70 & 8.16 & 5\\ UC & 31.49 & 16.52 & 13.11 & 19.29 & 14.81 & 34\\ UCC & 21.58 & 14.01 & 12.49 & 16.27 & 13.40 & 25\\ UCO & 36.19 & 18.54 & 14.85 & 22.60 & 15.18 & 37\\ ZSAD & 29.63 & 23.52 & 18.70 & 21.07 & 16.86 & 38\\ \rowcolor{distcolor} DTS & 50.75 & 30.49 & 22.71 & 23.65 & 21.32 & 46\\ DSM & 25.03 & 15.06 & 12.33 & 16.00 & 13.44 & 28\\ SAMM & 21.52 & 11.95 & 9.65 & 22.09 & 13.72 & 26\\ \rowcolor{imagecolor} DB & 37.90 & 22.96 & 19.69 & 26.13 & 17.38 & 40\\ DLB & 39.70 & 22.26 & 20.01 & 25.26 & 18.57 & 41\\ DTE & 42.64 & 20.24 & 17.64 & 27.94 & 18.82 & 43\\ HGM & 42.11 & 23.40 & 19.21 & 27.72 & 19.38 & 45\\ IVAR$_{5}$ & 43.57 & 34.29 & 41.03 & 30.11 & 22.76 & 47\\ & & & & & & \\ \midrule \rowcolor{white} Opt. & 12.00 & 4.72 & 3.40 & 5.31 & 4.07 & -\\ D1(\%) & 43.58 & 27.19 & 22.28 & 28.70 & 21.27 & -\\ \midrule \end{tabular} \end{tabularx} } \caption{\textbf{Results with Census-CBCA algorithm}, hand-crafted measures.} \label{tab:census_cbca_hand} \end{table} \begin{figure}[t] \centering \begin{tabular}{c} \includegraphics[width=0.38\textwidth]{images/plots/census1.pdf} \\ \includegraphics[width=0.38\textwidth]{images/plots/census2.pdf} \\ \includegraphics[width=0.38\textwidth]{images/plots/census3.pdf} \\ \end{tabular} \caption{\textbf{Impact of N(p) size}, Census-CBCA algorithm.} \label{fig:census_cbca_radius} \end{figure} \begin{table}[t] \centering \scalebox{0.68}{ \renewcommand{\tabcolsep}{2pt} \begin{tabularx}{\textwidth}{cc} \begin{tabular}{.l;c;c|c;c|c;c;c.} \multicolumn{8}{c}{Train set: Driving} \\ \toprule & Driv. & 2012 & 2015 & Midd. & ETH & R. & CR.\\ \midrule \rowcolor{forestvol} ENS$_{23}$ & 17.08 & 8.49 & 7.44 & 13.29 & 9.36 & 19 & 16\\ GCP & 16.10 & 7.16 & 5.93 & 11.84 & 8.33 & 16 & 5\\ LEV$_{22}$ & 15.32 & 6.56 & 5.43 & 12.01 & 9.39 & 11 & 7\\ LEV$_{50}$ & 14.59 & 6.25 & 5.26 & 12.37 & 7.80 & 2 & 3\\ FA & 15.07 & 7.45 & 6.05 & 13.99 & 11.40 & 8 & 18\\ \rowcolor{forestdisp} ENS$_{7}$ & 19.11 & 8.86 & 7.85 & 15.72 & 11.72 & 21 & 21\\ O1 & 15.41 & 7.41 & 6.03 & 14.68 & 9.49 & 12 & 14\\ O2 & 14.77 & 6.73 & 5.60 & 13.17 & 7.83 & 6 & 6\\ \rowcolor{deepdisp} CCNN & 15.30 & 6.64 & 5.46 & 16.37 & 8.98 & 10 & 13\\ PBCP$_{r}$ & 16.07 & 6.74 & 5.44 & 14.61 & 8.56 & 15 & 11\\ PBCP$_{d}$ & 15.90 & 6.22 & 5.22 & 14.24 & 11.94 & 13 & 15\\ EFN & 16.73 & 7.65 & 6.80 & 18.02 & 11.54 & 18 & 20\\ LFN & 15.15 & 7.77 & 6.32 & 15.65 & 10.30 & 9 & 19\\ MMC & 14.65 & 7.22 & 5.78 & 14.79 & 9.37 & 3 & 12\\ ConfNet & 15.97 & 6.56 & 5.60 & 13.30 & 8.00 & 14 & 9\\ LGC & 14.74 & \underline{6.06} & \underline{4.94} & 14.01 & 9.18 & 4 & 10\\ \rowcolor{deepvol} RCN & 23.46 & 16.97 & 14.10 & 21.73 & 15.99 & 23 & 22\\ MPN & 16.22 & 6.53 & 5.22 & \underline{11.19} & \underline{7.08} & 17 & 1\\ UCN & 14.97 & 6.33 & 5.05 & 12.48 & 7.28 & 7 & 2\\ LAF & \underline{13.76} & 6.87 & 5.35 & 12.06 & 9.12 & 1 & 8\\ ACN & 14.76 & 6.97 & 5.49 & 12.00 & 7.57 & 5 & 4\\ CRNN & 22.27 & 16.87 & 13.91 & 21.99 & 16.86 & 22 & 23\\ CVA & 17.38 & 9.47 & 7.52 & 12.82 & 8.87 & 20 & 17\\ \midrule \rowcolor{white} Opt. & 12.00 & 4.72 & 3.40 & 5.31 & 4.07 & - & -\\ D1(\%) & 43.58 & 27.19 & 22.28 & 28.70 & 21.27 & - & -\\ \midrule \end{tabular} & \begin{tabular}{.l;c|c;c|c;c.} \multicolumn{6}{c}{Train set: KITTI 2012} \\ \toprule & 2012 & 2015 & Midd. & ETH & R.\\ \midrule \rowcolor{forestvol} ENS$_{23}$ & 6.62 & 5.60 & 11.15 & 8.20 & 15\\ GCP & 6.37 & 5.29 & 11.18 & 8.54 & 14\\ LEV$_{22}$ & 5.75 & 4.56 & 11.47 & 8.33 & 6\\ LEV$_{50}$ & 5.67 & 4.49 & 11.88 & 8.70 & 11\\ FA & 6.01 & 4.71 & 13.34 & 12.68 & 19\\ \rowcolor{forestdisp} ENS$_{7}$ & 7.53 & 6.28 & 14.59 & 10.92 & 20\\ O1 & 6.15 & 4.77 & 11.45 & 9.73 & 16\\ O2 & 5.81 & 4.53 & 11.06 & 9.28 & 10\\ \rowcolor{deepdisp} CCNN & 5.76 & 4.40 & 11.24 & 9.09 & 9\\ PBCP$_{r}$ & 6.01 & 4.89 & 10.20 & 9.19 & 7\\ PBCP$_{d}$ & 5.54 & 4.44 & 15.01 & 14.43 & 21\\ EFN & 6.16 & 4.74 & 13.64 & 9.84 & 17\\ LFN & 5.80 & 4.43 & 11.81 & 9.02 & 13\\ MMC & 5.71 & 4.36 & 11.26 & 8.98 & 8\\ ConfNet & 6.11 & 4.85 & 11.85 & 8.24 & 12\\ LGC & 5.59 & 4.25 & 9.93 & 7.58 & 4\\ \rowcolor{deepvol} RCN & 14.79 & 13.29 & 17.59 & 13.21 & 23\\ MPN & 5.58 & 4.31 & 9.00 & \underline{6.23} & 1\\ UCN & 5.52 & 4.28 & 9.17 & 6.55 & 3\\ LAF & \underline{5.33} & \underline{4.20} & 10.30 & 9.50 & 5\\ ACN & 5.69 & 4.35 & \underline{8.86} & 6.49 & 2\\ CRNN & 11.81 & 10.48 & 15.52 & 11.62 & 22\\ CVA & 8.12 & 6.39 & 11.04 & 9.63 & 18\\ \midrule \rowcolor{white} Opt. & 4.72 & 3.40 & 5.31 & 4.07 & -\\ D1(\%) & 27.19 & 22.28 & 28.70 & 21.27 & -\\ \midrule \end{tabular} \end{tabularx} } \caption{\textbf{Results with Census-CBCA algorithm}, learned measures.} \label{tab:census_cbca_learning} \end{table} \begin{figure*}[t] \scriptsize \centering \renewcommand{\tabcolsep}{1pt} \rotatebox{90}{KITTI} \rotatebox{90}{2015} \subfigure{ \includegraphics[width=0.11\textwidth, frame]{images/qualitative/census-CBCA/2015/000197_10.png}} \subfigure{ \includegraphics[width=0.11\textwidth, frame]{images/qualitative/census-CBCA/2015/disparity.png}} \subfigure{ \includegraphics[width=0.11\textwidth, frame]{images/qualitative/census-CBCA/2015/apkr_7.png}} \subfigure{ \includegraphics[width=0.11\textwidth, frame]{images/qualitative/census-CBCA/2015/wmn.png}} \subfigure{ \includegraphics[width=0.11\textwidth, frame]{images/qualitative/census-CBCA/2015/da_31.png}} \subfigure{ \includegraphics[width=0.11\textwidth, frame]{images/qualitative/census-CBCA/2015/uc_cost.png}} \subfigure{ \includegraphics[width=0.11\textwidth, frame]{images/qualitative/census-CBCA/2015/samm.png}} \subfigure{ \includegraphics[width=0.11\textwidth, frame]{images/qualitative/census-CBCA/2015/k12-laf.png} } \\ \rotatebox{90}{Middlebury} \subfigure{ \includegraphics[width=0.11\textwidth, frame]{images/qualitative/census-CBCA/MiddEval3/Playtable.png}} \subfigure{ \includegraphics[width=0.11\textwidth, frame]{images/qualitative/census-CBCA/MiddEval3/disparity.png}} \subfigure{ \includegraphics[width=0.11\textwidth, frame]{images/qualitative/census-CBCA/MiddEval3/apkr_7.png}} \subfigure{ \includegraphics[width=0.11\textwidth, frame]{images/qualitative/census-CBCA/MiddEval3/wmn.png}} \subfigure{ \includegraphics[width=0.11\textwidth, frame]{images/qualitative/census-CBCA/MiddEval3/da_31.png}} \subfigure{ \includegraphics[width=0.11\textwidth, frame]{images/qualitative/census-CBCA/MiddEval3/uc_cost.png}} \subfigure{ \includegraphics[width=0.11\textwidth, frame]{images/qualitative/census-CBCA/MiddEval3/samm.png}} \subfigure{ \includegraphics[width=0.11\textwidth, frame]{images/qualitative/census-CBCA/MiddEval3/k12-laf.png} } \\ \caption{\textbf{Qualitative results concerning Census-CBCA algorithm.} Results on KITTI 2015 and Middlebury showing a variety of confidence measures. From top left to bottom right: reference image, disparity map and confidence maps by APKR$_7$, WMN, DA$_{31}$, UCC, SAMM and LAF.} \label{fig:qualitative_census_cbca} \end{figure*} \textbf{Impact of the windows size.} Figure \ref{fig:census_cbca_radius} plots the AUC achieved by varying the radius of $N(p)$ for measures computed over a local neighborhood. Interestingly, we can notice how different measures behave differently, highlighting that not always the larger local context leads to the better performance. Indeed, this is true only for DA, achieving its best performance with $31\times31$ windows. In general, measures computed from the \colorbox{dispcolor}{disparity domain} such as DS, MDD and MND get the best results with medium/large windows size, respectively 17, 19 and 21 size. Finally, measures APKR, APKRN, WPKR, WPKRN based on \colorbox{localcolor}{local properties} tend to perform better with smaller kernels of size 5 or 7. Similarly, IVAR performs better with a small window, \emph{i.e.} $5\times5$. \textbf{Learned measures, synthetic data training.} Table \ref{tab:census_cbca_learning}, on the left, collects results for learned measures when trained on synthetic images from the Driving train split. Concerning results on the synthetic test split, LAF performs the best, followed by LEV$_{50}$. This highlights that, either using \colorbox{forestvol}{cost-volume forests} or \colorbox{deepvol}{cost-volume CNNs}, the information in the cost volume can be useful if properly leveraged, in particular with adequate receptive fields. Nevertheless, MMC and LGCNet show that \colorbox{deepdisp}{disparity CNNs} can be very close to the top-2 methods using the cost volume. Finally, comparing tables \ref{tab:census_cbca_hand} and \ref{tab:census_cbca_learning} we can notice that, excluding RF and CRNN, learned measures always outperform hand-crafted ones on the synthetic test split. Concerning generalization to real data, comparing the two tables again, we point out that most learned measures outperform the top-performing hand-crafted measure (DA$_{31}$) on KITTI 2012 and 2015, except ENS$_{23}$. This evidence suggests that learning confidence estimation suffers from the domain shift from synthetic to real much less than other tasks such as, for instance, learning stereo matching \cite{Tonioni_2017_ICCV,Tonioni_2019_CVPR,Tonioni_2019_learn2adapt,tonioni2019unsupervised}. A possible reason we ascribe it to is the much more structured appearance observed in the disparity domain, the primary cue processed for this task, where smooth surfaces are very likely to be met, and sharp edges occur near depth discontinuities either in real or simulated environments, conversely to raw image appearance that differs a lot from synthetic to real scenes, for instance, because of lightning conditions and noise. Thus, detecting outliers in such a well-defined domain is a simpler task than facing stereo matching from raw images. Despite this fact, many learned measures (\emph{e.g.} FA) poorly perform on Middlebury and ETH, being often outperformed by the best hand-crafted ones, such as DA and VAR. This behavior is probably due to the different geometry of indoor vs outdoor scenes, confirming our previous findings in \cite{poggi2017quantitative}. Other methods performing very well on synthetic images and affected by domain shift issues are LAF and LGC. One might argue that methods trained by assuming $\tau=3$ are penalized when the dataset threshold is lower, i.e. $\tau=1$. However, by setting $\tau=3$ for Middlebury and ETH3D, the relative order is, in most cases, unaltered. In contrast, some methods keep their good ranking unaltered (\emph{e.g.} LEV$_{50}$, O2) or even significantly improve it, such as GCP and ConfNet. Moreover, MPN surprisingly jumps to rank 1, exposing excellent generalization properties. \textbf{Learned measures, real data training.} Table \ref{tab:census_cbca_learning}, on the right, collects results for measures trained on KITTI 2012 20 training images. By comparing the numbers on the left and right side of the table, on KITTI 2012 and 2015, we can notice how, not surprisingly, training on real images allows for better accuracy on these datasets. However, the tiny improvements (we recall that reported AUC are multiplied by $10^2$) confirm a marginal impact of domain-shift on the confidence estimation task. A similar behavior, except for PBCP$_{d}$, can be noticed on Middlebury while on ETH3D, many learned measures trained on KITTI 2012 (\emph{e.g.} LEV$_{50}$, O2, PBCPs, LAF and CVA) achieve worse performance. We ascribe this behavior to the same reason outlined previously. Overall, the top-performing learned measures training on KITTI 2012 turn out \colorbox{deepvol}{cost-volume CNNs} and LGC belonging to \colorbox{deepdisp}{disparity CNNs} category. Finally, we observe that top-performing hand-crafted measures are competitive and, sometimes, better than learned ones training on KITTI 2012. \textbf{Qualitative results.} We report in Fig. \ref{fig:qualitative_census_cbca} disparity maps from KITTI 2015 and Middlebury. The figure also shows, on different columns, confidence maps for five hand-crafted measures to highlight their behaviors and the outcome of a learned confidence measure trained on KITTI 2012 splits to highlight the effects of the domain shift. We can notice how most traditional measures tend to assign low confidence, probably because of the noisy cost volumes and disparities produced by Census-CBCA. More advanced measures like SAMM or learned as LAF, when assigning low confidence, can better focus on the real outliers. \textbf{Summary.} When dealing with noisy algorithms such as Census-CBCA, hand-crafted measures computed on a local window result very effective, even without processing the cost volume. This is also confirmed for learned measures, where a large receptive field exploited by networks and forests always improves the results. The disparity map alone allows for the best results in the case of hand-crafted measures and for competitive effectiveness in the case of learned methods. \begin{table}[t] \centering \scalebox{0.68}{ \renewcommand{\tabcolsep}{2pt} \begin{tabularx}{\textwidth}{cc} \begin{tabular}{.l;c|c|c|c|c;c.} \toprule & Driv. & 2012 & 2015 & Midd. & ETH & R.\\ \midrule \rowcolor{localcolor} APKR$_{19}$ & 16.18 & 4.91 & 4.88 & \underline{8.63} & 13.94 & 1\\ APKRN$_{5}$ & 24.07 & 8.47 & 8.42 & 10.97 & 17.11 & 27\\ CUR & 30.86 & 13.17 & 12.10 & 14.14 & 23.14 & 34\\ DAM & 29.83 & 12.95 & 12.66 & 19.69 & 24.98 & 37\\ LC & 29.93 & 12.80 & 11.94 & 13.60 & 23.01 & 33\\ MM & 17.34 & 6.23 & 6.17 & 10.21 & 17.73 & 13\\ MMN & 28.68 & 10.54 & 10.42 & 13.05 & 19.68 & 29\\ MSM & 18.38 & 9.70 & 8.84 & 10.40 & 21.37 & 25\\ NLM & 17.34 & 6.63 & 6.17 & 10.21 & 17.73 & 14\\ NLMN & 28.68 & 10.54 & 10.42 & 13.05 & 19.68 & 30\\ PKR & 16.48 & 6.55 & 6.25 & 9.53 & 18.09 & 12\\ PKRN & 22.75 & 8.24 & 8.16 & 11.06 & 17.98 & 23\\ SGE & 17.80 & 9.36 & 8.48 & 10.18 & 20.93 & 22\\ WPKR$_{11}$ & 16.47 & 5.44 & 5.47 & 8.71 & 15.34 & 4\\ WPKRN$_{5}$ & 24.34 & 9.42 & 9.56 & 11.17 & 17.53 & 28\\ \rowcolor{fullcolor} ALM & 15.82 & 6.26 & 6.47 & 9.37 & 17.71 & 11\\ LMN & 27.37 & 9.59 & 8.41 & 15.68 & 21.99 & 31\\ MLM & 15.55 & 5.56 & 5.77 & 9.23 & 16.71 & 6\\ NEM & 27.22 & 19.36 & 17.06 & 26.06 & 33.36 & 42\\ NOI & 31.06 & 22.20 & 18.94 & 27.40 & 32.63 & 46\\ PER & 15.78 & 6.13 & 6.34 & 9.35 & 17.54 & 8\\ PWCFA & 16.63 & 5.60 & 6.09 & 9.78 & 17.42 & 10\\ WMN & 16.84 & 7.19 & 6.90 & 9.31 & 18.67 & 15\\ WMNN & 20.23 & 7.63 & 7.52 & 10.40 & 17.67 & 18\\ \midrule \rowcolor{white} Opt. & 9.63 & 2.29 & 2.16 & 5.63 & 10.31 & -\\ D1(\%) & 39.00 & 18.71 & 16.93 & 29.80 & 34.28 & -\\ \midrule \end{tabular} & \begin{tabular}{.l;c|c|c|c|c;c.} \toprule & Driv. & 2012 & 2015 & Midd. & ETH & R.\\ \midrule \rowcolor{dispcolor} DA$_{31}$ & 17.45 & 5.38 & 5.16 & 8.81 & \underline{12.70} & 2\\ DMV & 18.44 & 6.16 & 6.01 & 11.29 & 17.68 & 16\\ DS$_{9}$ & 16.15 & 5.07 & 4.71 & 8.95 & 15.24 & 3\\ DTD & 17.69 & 6.78 & 6.82 & 13.43 & 20.99 & 20\\ MDD$_{21}$ & 16.85 & \underline{4.58} & \underline{4.42} & 11.62 & 15.38 & 7\\ MND$_{9}$ & 16.43 & 5.32 & 5.12 & 10.85 & 17.53 & 9\\ SKEW$_{5}$ & 17.33 & 6.24 & 6.23 & 12.21 & 18.81 & 17\\ VAR$_{5}$ & \underline{15.64} & 5.33 & 5.02 & 9.57 & 16.52 & 5\\ \rowcolor{lrcolor} ACC & 28.95 & 12.50 & 11.29 & 19.32 & 26.47 & 36\\ LRC & 26.66 & 10.27 & 9.24 & 18.76 & 23.90 & 32\\ LRD & 20.86 & 8.02 & 7.66 & 10.68 & 18.45 & 19\\ UC & 28.33 & 12.26 & 11.06 & 19.21 & 26.36 & 35\\ UCC & 18.84 & 8.74 & 8.08 & 10.73 & 19.70 & 21\\ UCO & 32.70 & 13.59 & 11.59 & 22.73 & 27.16 & 38\\ ZSAD & 25.55 & 19.49 & 16.77 & 22.51 & 28.79 & 39\\ \rowcolor{distcolor} DTS & 34.11 & 22.87 & 20.95 & 38.30 & 37.16 & 47\\ DSM & 18.39 & 9.73 & 8.85 & 10.54 & 21.49 & 26\\ SAMM & 15.91 & 6.07 & 5.47 & 19.33 & 21.70 & 24\\ \rowcolor{imagecolor} DB & 34.69 & 16.71 & 15.52 & 27.59 & 29.84 & 43\\ DLB & 34.39 & 14.78 & 14.52 & 26.39 & 31.21 & 41\\ DTE & 40.06 & 14.49 & 13.75 & 28.73 & 27.64 & 44\\ HGM & 38.23 & 16.31 & 14.78 & 28.17 & 30.05 & 45\\ IVAR$_{5}$ & 40.21 & 12.71 & 12.75 & 27.11 & 25.54 & 40\\ & & & & & & \\ \midrule \rowcolor{white} Opt. & 9.63 & 2.24 & 2.16 & 5.63 & 10.31 & -\\ D1(\%) & 39.00 & 18.88 & 16.93 & 29.80 & 34.28 & -\\ \midrule \end{tabular} \end{tabularx} } \caption{\textbf{Results with MCCNN-CBCA algorithm}, hand-crafted measures.} \label{tab:mccnn_cbca_hand} \end{table} \begin{figure}[t] \centering \begin{tabular}{c} \includegraphics[width=0.38\textwidth]{images/plots/mccnn1.pdf} \\ \includegraphics[width=0.38\textwidth]{images/plots/mccnn2.pdf} \\ \includegraphics[width=0.38\textwidth]{images/plots/mccnn3.pdf} \\ \end{tabular} \caption{\textbf{Impact of N(p) size}, MCCNN-CBCA algorithm.} \label{fig:mccnn_cbca_radius} \end{figure} \begin{table}[t] \centering \scalebox{0.68}{ \renewcommand{\tabcolsep}{2pt} \begin{tabularx}{\textwidth}{cc} \begin{tabular}{.l;c;c|c;c|c;c;c.} \multicolumn{8}{c}{Train set: Driving} \\ \toprule & Driv. & 2012 & 2015 & Midd. & ETH & R. & CR. \\ \midrule \rowcolor{forestvol} ENS$_{23}$ & 13.67 & 4.30 & 4.75 & 10.36 & 16.21 & 20 & 20\\ GCP & 12.65 & 3.64 & 3.78 & 10.27 & 17.34 & 18 & 18\\ LEV$_{22}$ & 12.16 & 3.11 & 3.43 & 9.26 & 14.72 & 13 & 7\\ LEV$_{50}$ & 11.70 & \underline{3.04} & 3.37 & 10.13 & 14.10 & 5 & 9\\ FA & 11.38 & 3.66 & 3.66 & 9.32 & 13.79 & 2 & 5\\ \rowcolor{forestdisp} ENS$_{7}$ & 14.88 & 5.05 & 5.46 & 11.03 & 16.67 & 21 & 21\\ O1 & 12.19 & 3.88 & 4.16 & 9.73 & 13.39 & 14 & 12\\ O2 & 11.82 & 3.77 & 4.02 & 9.79 & 13.00 & 7 & 8\\ \rowcolor{deepdisp} CCNN & 12.15 & 3.45 & 3.78 & 10.10 & 13.13 & 12 & 6\\ PBCP$_{r}$ & 12.51 & 3.21 & \underline{3.35} & 9.28 & 13.68 & 17 & 3\\ PBCP$_{d}$ & 11.95 & 3.96 & 4.49 & 9.73 & 14.57 & 10 & 15\\ EFN & 12.48 & 4.31 & 4.84 & 10.58 & 14.65 & 15 & 17\\ LFN & 11.79 & 4.36 & 4.53 & 9.76 & 14.18 & 6 & 16\\ MMC & 11.40 & 4.14 & 4.21 & 9.41 & 13.74 & 3 & 14\\ ConfNet & 12.48 & 3.56 & 3.77 & 9.17 & 13.59 & 16 & 4\\ LGC & 11.66 & 3.12 & 3.52 & 8.84 & 13.31 & 4 & 2\\ \rowcolor{deepvol} RCN & 18.94 & 6.89 & 6.77 & 24.35 & 28.77 & 23 & 23\\ MPN & 11.99 & 3.80 & 4.13 & 9.96 & 13.51 & 11 & 13\\ UCN & 11.86 & 3.34 & 3.69 & 10.10 & 13.99 & 8 & 12\\ LAF & \underline{11.00} & 3.79 & 4.00 & 9.24 & 14.08 & 1 & 11\\ ACN & 11.88 & 3.45 & 3.60 & \underline{8.59} & \underline{12.81} & 9 & 1\\ CRNN & 16.01 & 5.89 & 5.67 & 21.69 & 26.06 & 22 & 22\\ CVA & 12.67 & 4.24 & 4.52 & 11.48 & 15.09 & 19 & 19\\ \midrule \rowcolor{white} Opt. & 9.63 & 2.35 & 2.16 & 5.63 & 10.31 & - & -\\ D1(\%) & 39.00 & 18.88 & 16.93 & 29.80 & 34.28 & - & -\\ \midrule \end{tabular} & \begin{tabular}{.l;c|c;c|c;c.} \multicolumn{6}{c}{Train set: KITTI 2012} \\ \toprule & 2012 & 2015 & Midd. & ETH & R.\\ \midrule \rowcolor{forestvol} ENS$_{23}$ & 3.53 & 3.76 & 9.58 & 14.48 & 17\\ GCP & 3.44 & 3.44 & 9.86 & 15.69 & 19\\ LEV$_{22}$ & 3.05 & 3.05 & 8.48 & 13.74 & 10\\ LEV$_{50}$ & 2.89 & 2.97 & 8.45 & 13.45 & 5\\ FA & 3.00 & 3.02 & 8.33 & 14.00 & 11\\ \rowcolor{forestdisp} ENS$_{7}$ & 3.94 & 4.33 & 10.95 & 16.37 & 21\\ O1 & 2.96 & 2.93 & 8.25 & 15.18 & 14\\ O2 & 2.79 & 2.87 & 8.09 & 14.92 & 13\\ \rowcolor{deepdisp} CCNN & 2.84 & 2.91 & 8.23 & 14.23 & 9\\ PBCP$_{r}$ & 3.27 & 3.48 & 7.86 & 14.98 & 15\\ PBCP$_{d}$ & 2.95 & 3.06 & 11.26 & 17.10 & 20\\ EFN & 3.22 & 3.15 & 9.44 & 13.98 & 16\\ LFN & 3.04 & 3.00 & 8.45 & 14.15 & 12\\ MMC & 2.95 & 2.94 & 8.15 & 13.78 & 6\\ ConfNet & 3.22 & 3.32 & 8.31 & 13.34 & 8\\ LGC & 2.96 & \underline{2.77} & 8.09 & 14.37 & 7\\ \rowcolor{deepvol} RCN & 5.53 & 5.35 & 17.75 & 24.99 & 23\\ MPN & 3.03 & 3.09 & 8.26 & 13.02 & 4\\ UCN & 2.85 & 2.90 & 8.07 & \underline{13.01} & 1\\ LAF & \underline{2.81} & 2.90 & \underline{8.03} & 13.17 & 2\\ ACN & 2.94 & 3.03 & 8.24 & 13.09 & 3\\ CRNN & 5.08 & 4.87 & 17.75 & 25.02 & 22\\ CVA & 3.31 & 3.38 & 9.34 & 15.78 & 18\\ \midrule \rowcolor{white} Opt. & 2.35 & 2.16 & 5.63 & 10.31 & -\\ D1(\%) & 18.88 & 16.93 & 29.80 & 34.28 & -\\ \midrule \end{tabular} \end{tabularx} } \caption{\textbf{Results with MCCNN-CBCA algorithm}, learned measures.} \label{tab:mccnn_cbca_learning} \end{table} \subsubsection{MCCNN-CBCA} \textbf{Hand-crafted measures.} Table \ref{tab:mccnn_cbca_hand} reports the performance achieved by hand-crafted measures highlighting how, with MCCNN-CBCA, the top-performing measure is APKR$_{17}$. Similar to Census-CBCA experiments measures processing the \colorbox{dispcolor}{disparity map} perform very well, with DA$_{31}$ and DS$_9$ in the top-3 with others three out of six positionings in the top-10. Confidence measures processing \colorbox{localcolor}{local properties}, in particular WPKR$_{11}$ in addition to APKR$_{17}$, or the \colorbox{fullcolor}{entire cost curve} as MLM, PER and PWCFA perform very well. In contrast, the best methods exploiting \colorbox{lrcolor}{left-right consistency} features rank 19 and 21 with LRD and UCC, respectively. Among \colorbox{distcolor}{self-matching} measures, SAMM achieves better results and ranks 24, while estimating confidence only from \colorbox{imagecolor}{image properties} confirms ineffective as always. \textbf{Impact of the windows size.} Figure \ref{fig:mccnn_cbca_radius} plots the AUC achieved by varying the radius of $N(p)$ for measures computed over a local neighborhood. DA confirms to perform better on large $31\times31$ windows, while the other \colorbox{dispcolor}{disparity map} features show mixed behaviors, with VAR and SKEW preferring a small window of size 5, MND and DS of size 9 and MDD of 21. Methods based on \colorbox{localcolor}{Local properties} perform differently, with APKR achieving the top-1 position with a kernel of size 19 and WPKR ranking 4th with a window of size 11. \textit{Naive} variants, as well as IVAR, worsen with kernels larger than 5. \begin{figure*}[t] \scriptsize \centering \renewcommand{\tabcolsep}{1pt} \rotatebox{90}{KITTI} \rotatebox{90}{2015} \subfigure{ \includegraphics[width=0.11\textwidth, frame]{images/qualitative/census-CBCA/2015/000197_10.png}} \subfigure{ \includegraphics[width=0.11\textwidth, frame]{images/qualitative/mccnn-CBCA/2015/disparity.png}} \subfigure{ \includegraphics[width=0.11\textwidth, frame]{images/qualitative/mccnn-CBCA/2015/apkr_7.png}} \subfigure{ \includegraphics[width=0.11\textwidth, frame]{images/qualitative/mccnn-CBCA/2015/wmn.png}} \subfigure{ \includegraphics[width=0.11\textwidth, frame]{images/qualitative/mccnn-CBCA/2015/da_31.png}} \subfigure{ \includegraphics[width=0.11\textwidth, frame]{images/qualitative/mccnn-CBCA/2015/uc_cost.png}} \subfigure{ \includegraphics[width=0.11\textwidth, frame]{images/qualitative/mccnn-CBCA/2015/samm.png}} \subfigure{ \includegraphics[width=0.11\textwidth, frame]{images/qualitative/mccnn-CBCA/2015/k12-laf.png} } \\ \rotatebox{90}{Middlebury} \subfigure{ \includegraphics[width=0.11\textwidth, frame]{images/qualitative/census-CBCA/MiddEval3/Playtable.png}} \subfigure{ \includegraphics[width=0.11\textwidth, frame]{images/qualitative/mccnn-CBCA/MiddEval3/disparity.png}} \subfigure{ \includegraphics[width=0.11\textwidth, frame]{images/qualitative/mccnn-CBCA/MiddEval3/apkr_7.png}} \subfigure{ \includegraphics[width=0.11\textwidth, frame]{images/qualitative/mccnn-CBCA/MiddEval3/wmn.png}} \subfigure{ \includegraphics[width=0.11\textwidth, frame]{images/qualitative/mccnn-CBCA/MiddEval3/da_31.png}} \subfigure{ \includegraphics[width=0.11\textwidth, frame]{images/qualitative/mccnn-CBCA/MiddEval3/uc_cost.png}} \subfigure{ \includegraphics[width=0.11\textwidth, frame]{images/qualitative/mccnn-CBCA/MiddEval3/samm.png}} \subfigure{ \includegraphics[width=0.11\textwidth, frame]{images/qualitative/mccnn-CBCA/MiddEval3/k12-laf.png} } \\ \caption{\textbf{Qualitative results concerning MCCNN-CBCA algorithm.} Results on KITTI 2015 and Middlebury showing a variety of confidence measures. From top left to bottom right: reference image, disparity map and confidence maps by APKR$_7$, WMN, DA$_{31}$, UCC, SAMM and LAF.} \label{fig:qualitative_mccnn_cbca} \end{figure*} \textbf{Learned measures, synthetic data training.} Table \ref{tab:mccnn_cbca_learning}, on left, collects results for learned measures when trained on synthetic images from the Driving train split. When testing on synthetic data, LAF outperforms all the competitors as observed on Census-CBCA experiments, this time followed by FA. MMC and LGC follow, confirming that for noisy CBCA algorithms, \colorbox{deepdisp}{disparity CNNs} are competitive with both \colorbox{forestvol}{cost-volume forests} and \colorbox{deepvol}{cost-volume CNNs}. This fact is confirmed by O1 and O2, being both outperformed with minor margins, respectively by LEV and LEV$_{50}$. Again, larger receptive fields seem beneficial when the cost volume is not processed. Concerning generalization to real data, as for Census-CBCA, we observe that most learned measures outperform the top-performing hand-crafted one APKR$_{17}$ on KITTI 2012 and 2015, confirming that the domain shift from synthetic to real is much less evident when dealing with CBCA algorithms. Nonetheless, the performance on Middlebury and ETH3D are still comparable with hand-crafted methods. Overall, ACN surprisingly jumps to rank 1, while LAF drops to rank 11, while LGC and O2 and show a more stable behavior and keep their position almost unaltered, with the former achieving rank 2. Looking at patch-based methods, the comparison between PBCP$_{r}$, CCNN and PBCP$_{d}$ confirms the previous findings, with the latter performing better on images similar to the training set but dropping when evaluating across domains. PBCP$_{r}$ variant is, on the contrary, much more robust to domain shifts and reaches rank 3 in this case. Since RGB data can be significantly affected by the domain shift, most measures processing the reference image witness a massive drop in accuracy when crossing domains. Nonetheless, a notable exception is ConfNet, a component of LGC, which seems particularly good at generalization, as observed in the previous experiments. \textbf{Learned measures, real data training.} Table \ref{tab:mccnn_cbca_learning}, on the right, gathers results for learned measures when trained on KITTI 2012 20 training images. \colorbox{deepvol}{Cost-volume CNNs} cover the top-4 positions in the leaderboard, followed by LEV$_{50}$. Then MMC, LGC, ConfNet and CCNN that are \colorbox{deepdisp}{disparity CNNs}. Finally, \colorbox{forestvol}{cost-volume forests} such as FA and LEV outperform, on average, O1 and O2, while being less effective on specific datasets such as in the case of KITTI 2015 and Middlebury. Concerning patch-based methods, this time CCNN outperforms both PBCP variants, with PBCP$_{r}$ better at generalizing compared to PBCP$_{d}$ as observed so far. On the other hand, MMC outperforms CCNN thanks to the much larger receptive field. Moreover, MMC also surpasses networks, such as ConfNet and LGC, with comparable receptive fields. \textbf{Qualitative results.} To conclude this section, Fig. \ref{fig:qualitative_mccnn_cbca} shows some disparity maps from KITTI 2015 and Middlebury together with confidence maps. In particular, it highlights how hand-crafted measures belonging to different categories behave very differently and, in the rightmost column, the effects introduced by the domain shift on a learned measure. Compared to what seen with Census-CBCA, the traditional measures assign high confidence more often, probably because of the more robust cost volumes and disparities produced by replacing the census transform with MCCNN-fst. However, from confidence maps by LAF it is still easier to discriminate good matches from outliers. \textbf{Summary.} By replacing the matching costs computed by the census transform with those computed by MCCNN-fst, the behavior of most confidence measures remains unaltered, both for hand-crafted measures, among which several measures processing the disparity map only still result the most effective among the hand-crafted ones, or are competitive in the case of learned measures. \subsection{SGM Algorithms} We now assess confidence estimation performance with stereo methods leveraging SGM for cost volume optimization, one of the most versatile and popular solutions for its good trade-off between accuracy and computational complexity. Differently from the local algorithms tested so far, SGM disparity maps are much more accurate due to the \textit{global} nature of the optimization carried out, making the outlier detection task significantly more challenging. \subsubsection{CENSUS-SGM} In this section, we discuss the outcome of our experiments carried out with the Census-SGM algorithm. \textbf{Hand-crafted measures.} Table \ref{tab:census_sgm_hand} shows the performance achieved by hand-crafted measures. The top-performing measure is VAR$_{19}$ while, interestingly, the remaining ones processing the \colorbox{dispcolor}{disparity map} perform poorly this time because of the much smoother outputs by Census-SGM. Measures processing \colorbox{localcolor}{local properties} or the \colorbox{fullcolor}{entire cost curve} perform better in general, with MM, NLM and some of those based on peak ratio (\emph{e.g.} APKR$_{5}$ and PKR) achieving excellent results. Confidence estimated from \colorbox{lrcolor}{left-right consistency}, UCC and LRD in particular, turns out better than measures computed from the left disparity map only. Among \colorbox{distcolor}{self-matching} measures, DSM achieves the best accuracy despite far from top-performing ones, while estimating confidence only from \colorbox{imagecolor}{image properties} confirms ineffective once again. \colorbox{sgmcolor}{SGM-specific measures} tailored for SGM such as PS and SCS show an average performance, placing at the middle of the leaderboard. \textbf{Impact of the windows size.} Figure \ref{fig:census_sgm_radius} plots the AUC achieved by varying the radius of $N(p)$ for measures computed over a local neighborhood. Despite the very different outcome of the stereo algorithm deployed in this experiment, we can observe behaviors similar to the Census-CBCA case. For instance, DA and DS perform better on $31\times31$ windows, MDD and MND get the best results with a size of 21 while those based on \colorbox{localcolor}{local properties} perform better with kernels of size 5. IVAR yields the best performance with the smallest 5$\times$5 kernel. \textbf{Learned measures, synthetic data training.} Table \ref{tab:census_sgm_learning}, on the left, collects results for learned measures when trained on synthetic images from the Driving train split. Concerning results on the synthetic test split, \colorbox{deepvol}{cost-volume CNNs} achieve the top-4 positions with LAF leading, followed by methods acting in the disparity domain MMC, LGC and O2. This outcome is not surprising since for disparity maps with a much lower error rate, as in the case of Census-SGM, the cost volume becomes a much more meaningful cue to detect outliers. Both \colorbox{deepdisp}{disparity CNNs} and \colorbox{forestdisp}{disparity forests} can compete only when using a very large receptive field. Compared to general-purpose methods, most of them outperform \colorbox{sgmcolor}{SGMF} specifically tailored for SGM whose ranking is 16. Analyzing the capability of generalizing to real data, very rarely learned measures perform better than the top-1 hand-crafted measure VAR on KITTI datasets. This evidence suggests that the domain shift impacts more when dealing with more accurate stereo algorithms producing smoother disparity maps. Moreover, the effect is even more evident on Middlebury and ETH3D. Despite this outcome, interestingly, LAF keeps rank 1, showing to be the most stable solution in these experiments with LEV$_{50}$, CVA and ConfNet following. MPN and O2 substantially keep their position moving from synthetic to real data showing a much higher generalization capability than most other methods. SGMF achieves average generalization performance yet improving its ranking from 16 to 10. Looking at patch-based methods, PBCP$_{r}$ again better generalizes than CCNN and PBCP$_{d}$, although the latter is better on the same training domain. As for Census-CBCA, measures processing the reference image witness drop in ranking when crossing the domains since the RGB data is directly exposed to image content variation. However, such a drop is moderate for LGC and a notable exception is ConfNet that jumps from rank 12 to 4. \begin{table}[t] \centering \scalebox{0.68}{ \renewcommand{\tabcolsep}{2pt} \begin{tabularx}{\textwidth}{cc} \begin{tabular}{.l;c|c|c|c|c;c.} \toprule & Driv. & 2012 & 2015 & Midd. & ETH & R.\\ \midrule \rowcolor{localcolor} APKR$_{5}$ & 14.34 & 2.64 & 2.81 & 11.06 & 5.48 & 4\\ APKRN$_{5}$ & 21.95 & 4.13 & 4.01 & 12.04 & 5.95 & 21\\ CUR & 23.97 & 5.51 & 4.77 & 13.05 & 6.79 & 29\\ DAM & 29.20 & 8.67 & 8.21 & 22.67 & 13.28 & 43\\ LC & 22.08 & 5.47 & 4.91 & 12.96 & 6.95 & 28\\ MM & 14.47 & 2.82 & 2.83 & \underline{10.68} & 5.39 & 2\\ MMN & 25.95 & 5.36 & 5.05 & 13.40 & 6.94 & 30\\ MSM & 14.52 & 3.55 & 3.46 & 13.04 & 7.82 & 14\\ NLM & 14.47 & 2.82 & 2.83 & 10.68 & 5.39 & 3\\ NLMN & 25.95 & 5.36 & 5.05 & 13.40 & 6.94 & 31\\ PKR & 13.85 & 2.81 & 2.92 & 11.15 & 5.60 & 5\\ PKRN & 20.62 & 4.03 & 3.88 & 11.74 & 6.01 & 20\\ SGE & 14.22 & 3.38 & 3.30 & 13.11 & 7.83 & 12\\ WPKR$_{5}$ & 14.60 & 2.70 & 2.86 & 11.03 & 5.49 & 7\\ WPKRN$_{5}$ & 21.98 & 4.64 & 4.50 & 12.52 & 6.21 & 25\\ \rowcolor{fullcolor} ALM & 13.57 & 2.97 & 2.89 & 12.05 & 6.52 & 10\\ LMN & 30.86 & 7.43 & 5.90 & 20.92 & 11.24 & 40\\ MLM & 13.49 & 2.74 & 2.70 & 11.29 & 6.13 & 6\\ NEM & 24.76 & 10.33 & 9.04 & 28.90 & 14.59 & 44\\ NOI & 30.49 & 14.77 & 12.09 & 29.36 & 15.00 & 48\\ PER & \underline{13.55} & 2.91 & 2.82 & 11.83 & 6.42 & 9\\ PWCFA & 14.94 & 3.29 & 3.22 & 12.03 & 6.48 & 11\\ WMN & 13.79 & 2.89 & 3.04 & 11.50 & 5.95 & 8\\ WMNN & 18.78 & 3.61 & 3.47 & 11.44 & 5.95 & 16\\ \rowcolor{sgmcolor} PS & 21.50 & 5.37 & 4.79 & 11.98 & 7.24 & 27\\ \midrule \rowcolor{white} Opt. & 6.85 & 0.79 & 0.74 & 4.57 & 2.14 & -\\ D1(\%) & 33.25 & 10.33 & 9.00 & 26.68 & 15.74 & -\\ \midrule \end{tabular} & \begin{tabular}{.l;c|c|c|c|c;c.} \toprule & Driv. & 2012 & 2015 & Midd. & ETH & R.\\ \midrule \rowcolor{dispcolor} DA$_{31}$ & 23.53 & 3.92 & 4.23 & 14.51 & \underline{4.39} & 26\\ DMV & 24.59 & 4.77 & 4.67 & 18.77 & 11.10 & 34\\ DS$_{31}$ & 18.41 & 3.05 & 3.47 & 12.80 & 5.38 & 15\\ DTD & 14.89 & 3.61 & 3.80 & 17.67 & 8.68 & 22\\ MDD$_{21}$ & 21.24 & 3.70 & 3.64 & 18.97 & 10.35 & 32\\ MND$_{21}$ & 16.34 & 2.99 & 3.00 & 14.23 & 7.27 & 18\\ SKEW$_{21}$ & 15.92 & 4.03 & 4.12 & 15.91 & 9.21 & 24\\ VAR$_{19}$ & 13.75 & \underline{1.97} & \underline{1.92} & 12.02 & 5.37 & 1\\ \rowcolor{lrcolor} ACC & 24.05 & 6.08 & 5.59 & 18.43 & 11.09 & 35\\ LRC & 25.30 & 6.16 & 5.57 & 19.65 & 11.38 & 37\\ LRD & 20.12 & 3.08 & 3.22 & 11.28 & 5.88 & 17\\ UC & 24.23 & 6.28 & 5.83 & 18.79 & 11.37 & 36\\ UCC & 14.76 & 3.48 & 3.48 & 13.04 & 7.41 & 13\\ UCO & 26.94 & 7.44 & 6.41 & 19.95 & 11.88 & 39\\ ZSAD & 21.59 & 9.49 & 8.14 & 19.86 & 12.59 & 38\\ \rowcolor{distcolor} DTS & 37.20 & 22.53 & 6.39 & 21.17 & 15.03 & 49\\ DSM & 16.43 & 4.50 & 2.78 & 13.66 & 7.80 & 19\\ SAMM & 14.31 & 11.89 & 3.71 & 19.17 & 8.97 & 33\\ \rowcolor{imagecolor} DB & 27.68 & 8.45 & 8.75 & 23.84 & 11.87 & 42\\ DLB & 29.02 & 6.79 & 6.93 & 23.26 & 13.01 & 41\\ DTE & 33.69 & 9.36 & 8.92 & 26.45 & 13.55 & 47\\ HGM & 32.49 & 9.27 & 8.19 & 25.86 & 13.99 & 46\\ IVAR$_{5}$ & 34.08 & 8.64 & 8.51 & 25.41 & 12.47 & 45\\ & & & & & & \\ \rowcolor{sgmcolor} SCS & 22.13 & 3.55 & 3.79 & 13.08 & 6.54 & 23\\ \midrule \rowcolor{white} Opt. & 6.85 & 0.79 & 0.74 & 4.57 & 2.14 & -\\ D1(\%) & 33.25 & 10.33 & 9.00 & 26.68 & 15.74 & -\\ \midrule \end{tabular} \end{tabularx} } \caption{\textbf{Results with Census-SGM algorithm}, hand-crafted measures.} \label{tab:census_sgm_hand} \end{table} \begin{figure}[t] \centering \begin{tabular}{c} \includegraphics[width=0.38\textwidth]{images/plots/census-sgm1.pdf} \\ \includegraphics[width=0.38\textwidth]{images/plots/census-sgm2.pdf} \\ \includegraphics[width=0.38\textwidth]{images/plots/census-sgm3.pdf} \\ \end{tabular} \caption{\textbf{Impact of N(p) size}, Census-SGM algorithm.} \label{fig:census_sgm_radius} \end{figure} \begin{table}[t] \centering \scalebox{0.68}{ \renewcommand{\tabcolsep}{2pt} \begin{tabularx}{\textwidth}{cc} \begin{tabular}{.l;c;c|c;c|c;c;c.} \multicolumn{8}{c}{Train set: Driving} \\ \toprule & Driv. & 2012 & 2015 & Midd. & ETH & R. & CR.\\ \midrule \rowcolor{forestvol} ENS$_{23}$ & 11.16 & 2.87 & 3.21 & 15.63 & 9.06 & 17 & 17\\ GCP & 11.42 & 2.35 & 2.52 & 16.52 & 8.95 & 19 & 16\\ LEV$_{22}$ & 10.68 & \underline{1.84} & \underline{1.99} & 16.48 & 11.33 & 13 & 20\\ LEV$_{50}$ & 10.12 & 2.04 & 2.08 & 12.90 & 6.96 & 9 & 2\\ FA & 10.83 & 3.63 & 3.51 & 14.28 & 9.41 & 14 & 18\\ \rowcolor{forestdisp} ENS$_{7}$ & 13.46 & 4.30 & 4.63 & 16.17 & 9.49 & 23 & 22\\ O1 & 10.20 & 3.08 & 3.25 & 13.45 & 6.84 & 10 & 14\\ O2 & 9.92 & 2.66 & 3.01 & 12.77 & 6.29 & 7 & 6\\ \rowcolor{deepdisp} CCNN & 10.84 & 2.73 & 3.03 & 15.64 & 7.90 & 15 & 15\\ PBCP$_{r}$ & 12.02 & 2.96 & 2.73 & 13.37 & 5.98 & 22 & 9\\ PBCP$_{d}$ & 11.76 & 3.09 & 3.93 & 12.56 & 6.87 & 20 & 13\\ EFN & 32.42 & 10.07 & 8.77 & 26.01 & 15.08 & 24 & 24\\ LFN & 10.37 & 4.31 & 4.71 & 16.27 & 9.03 & 11 & 21\\ MMC & 9.63 & 2.93 & 2.97 & 13.76 & 6.54 & 5 & 11\\ ConfNet & 10.39 & 2.42 & 3.11 & 12.89 & 5.92 & 12 & 4\\ LGC & 9.82 & 2.25 & 2.79 & 13.77 & 6.20 & 6 & 8\\ \rowcolor{deepvol} RCN & 11.99 & 4.08 & 3.68 & 21.00 & 9.25 & 21 & 23\\ MPN & 9.60 & 1.93 & 2.23 & 12.95 & 7.39 & 4 & 5\\ UCN & 9.58 & 2.35 & 2.80 & 12.97 & 6.80 & 3 & 7\\ LAF & \underline{8.41} & 2.24 & 2.54 & \underline{11.48} & 7.21 & 1 & 1\\ ACN & 9.51 & 2.38 & 2.30 & 12.89 & 8.82 & 2 & 12\\ CRNN & 11.41 & 3.71 & 3.35 & 17.05 & 7.19 & 18 & 19\\ CVA & 10.11 & 2.84 & 2.99 & 13.00 & \underline{5.18} & 8 & 3\\ \rowcolor{sgmcolor} SGMF & 11.00 & 3.16 & 3.29 & 12.59 & 6.38 & 16 & 10\\ \midrule \rowcolor{white} Opt. & 6.85 & 0.79 & 0.74 & 4.57 & 2.14 & - & -\\ D1(\%) & 33.25 & 10.33 & 9.00 & 26.68 & 15.74 & - & -\\ \midrule \end{tabular} & \begin{tabular}{.l;c|c;c|c;c.} \multicolumn{6}{c}{Train set: KITTI 2012} \\ \toprule & 2012 & 2015 & Midd. & ETH & R.\\ \midrule \rowcolor{forestvol} ENS$_{23}$ & 1.99 & 2.18 & 12.82 & 7.82 & 16\\ GCP & 2.02 & 2.47 & 13.12 & 6.34 & 15\\ LEV$_{22}$ & 1.79 & 1.98 & 12.20 & 6.79 & 11\\ LEV$_{50}$ & 1.72 & 1.89 & 12.50 & 7.47 & 14\\ FA & 2.24 & 2.35 & 13.02 & 7.55 & 18\\ \rowcolor{forestdisp} ENS$_{7}$ & 2.71 & 2.86 & 15.21 & 8.71 & 21\\ O1 & 1.69 & 1.72 & 11.40 & 7.20 & 9\\ O2 & 1.64 & 1.55 & 10.82 & 8.08 & 10\\ \rowcolor{deepdisp} CCNN & 1.90 & 1.92 & 12.01 & 7.39 & 13\\ PBCP$_{r}$ & 1.87 & 2.03 & 10.73 & 7.33 & 8\\ PBCP$_{d}$ & 1.92 & 2.04 & 16.27 & 14.03 & 22\\ EFN & 2.27 & 2.14 & 13.98 & 7.53 & 20\\ LFN & 2.02 & 2.04 & 12.74 & 8.04 & 17\\ MMC & 1.75 & 1.69 & 11.64 & 7.89 & 12\\ ConfNet & 2.33 & 2.27 & 13.84 & 7.08 & 19\\ LGC & 1.80 & \underline{1.49} & 10.89 & 6.63 & 5\\ \rowcolor{deepvol} RCN & 3.04 & 2.65 & 20.67 & 11.94 & 24\\ MPN & 1.57 & 1.67 & 8.92 & \underline{5.16} & 1\\ UCN & 1.57 & 1.62 & \underline{8.88} & 5.28 & 2\\ LAF & \underline{1.44} & 1.60 & 10.44 & 6.44 & 4\\ ACN & 1.70 & 1.74 & 9.20 & 5.19 & 3\\ CRNN & 3.14 & 2.80 & 18.54 & 10.49 & 23\\ CVA & 2.20 & 2.23 & 10.65 & 6.45 & 7\\ \rowcolor{sgmcolor} SGMF & 2.16 & 2.28 & 11.04 & 5.47 & 6\\ \midrule \rowcolor{white} Opt. & 0.79 & 0.74 & 4.57 & 2.14 & -\\ D1(\%) & 10.33 & 9.00 & 26.68 & 15.74 & -\\ \midrule \end{tabular} \end{tabularx} } \caption{\textbf{Results with Census-SGM algorithm}, learned measures.} \label{tab:census_sgm_learning} \end{table} \begin{figure*}[t] \scriptsize \centering \renewcommand{\tabcolsep}{1pt} \rotatebox{90}{KITTI} \rotatebox{90}{2015} \subfigure{ \includegraphics[width=0.11\textwidth, frame]{images/qualitative/census-CBCA/2015/000197_10.png}} \subfigure{ \includegraphics[width=0.11\textwidth, frame]{images/qualitative/census-SGM/2015/disparity.png}} \subfigure{ \includegraphics[width=0.11\textwidth, frame]{images/qualitative/census-SGM/2015/apkr_7.png}} \subfigure{ \includegraphics[width=0.11\textwidth, frame]{images/qualitative/census-SGM/2015/wmn.png}} \subfigure{ \includegraphics[width=0.11\textwidth, frame]{images/qualitative/census-SGM/2015/da_31.png}} \subfigure{ \includegraphics[width=0.11\textwidth, frame]{images/qualitative/census-SGM/2015/uc_cost.png}} \subfigure{ \includegraphics[width=0.11\textwidth, frame]{images/qualitative/census-SGM/2015/samm.png}} \subfigure{ \includegraphics[width=0.11\textwidth, frame]{images/qualitative/census-SGM/2015/k12-laf.png} } \\ \rotatebox{90}{Middlebury} \subfigure{ \includegraphics[width=0.11\textwidth, frame]{images/qualitative/census-CBCA/MiddEval3/Playtable.png}} \subfigure{ \includegraphics[width=0.11\textwidth, frame]{images/qualitative/census-SGM/MiddEval3/disparity.png}} \subfigure{ \includegraphics[width=0.11\textwidth, frame]{images/qualitative/census-SGM/MiddEval3/apkr_7.png}} \subfigure{ \includegraphics[width=0.11\textwidth, frame]{images/qualitative/census-SGM/MiddEval3/wmn.png}} \subfigure{ \includegraphics[width=0.11\textwidth, frame]{images/qualitative/census-SGM/MiddEval3/da_31.png}} \subfigure{ \includegraphics[width=0.11\textwidth, frame]{images/qualitative/census-SGM/MiddEval3/uc_cost.png}} \subfigure{ \includegraphics[width=0.11\textwidth, frame]{images/qualitative/census-SGM/MiddEval3/samm.png}} \subfigure{ \includegraphics[width=0.11\textwidth, frame]{images/qualitative/census-SGM/MiddEval3/k12-laf.png} } \\ \caption{\textbf{Qualitative results concerning Census-SGM algorithm.} Results on KITTI 2015 and Middlebury showing a variety of confidence measures. From left to right: reference image, disparity map and confidence maps by APKR$_7$, WMN, DA$_{31}$, UCC, SAMM and LAF.} \label{fig:qualitative_census_sgm} \end{figure*} \textbf{Learned measures, real data training.} Table \ref{tab:census_sgm_learning}, on the right, collects results for learned measures when trained on KITTI 2012 20 training images. On KITTI datasets and Middlebury, they frequently outperform VAR thanks to the much more similar domain observed during training. Specifically, this fact always occurs for O1, O2, MMC, LGC, MPN, UN, ACN and LAF. On the other hand, on ETH3D, they are competitive but often worse than top-performing hand-crafted measures. Only the overall top-performing LAF, UN and ACN, are always more effective than VAR with each dataset. This outcome confirms \colorbox{deepvol}{Cost-volume CNNs} as the most effective solution followed by LGC and \colorbox{sgmcolor}{SGMF}, the latter tailored explicitly for SGM pipelines. Interestingly, \colorbox{forestdisp}{disparity forests} methods O1 and O2 outperform \colorbox{forestvol}{cost-volume forests}, as well as most \colorbox{deepdisp}{disparity CNNs}. About the latter, using the right disparity map allows PBCP$_r$ to perform better than CCNN in the case of smooth disparity maps, while PBCP$_d$ still generalizes worse. Again, including the reference image and the disparity map only is effective only in the case of a large receptive field, as for MMC. \textbf{Qualitative results.} Figure \ref{fig:qualitative_census_sgm}, as for previous qualitative results, reports an example of disparity map computed by the Census-SGM algorithm on KITTI 2015 and Middlebury and the outcome of six confidence measures, five hand-crafted and LAF in the rightmost column. Other than the different behavior of hand-crafted measures, we can notice the effects of the different domains on the learned one. In this case, being both cost volumes and disparity maps much smoother, hand-crafted measures now assign high confidence to most pixels as well as learned measures (\emph{i.e.}{} LAF) do. \textbf{Summary.} When dealing with more accurate stereo algorithms, based on SGM, the disparity map alone rarely allows for top-performing confidence estimation, except in the case of VAR. Indeed, the much smoother disparity map makes it harder to detect outliers without taking into account the cost volume. This is observed for learned measures as well, among which those processing the cost volume results more effective with fewer exceptions (when using large receptive fields -- LGC, or the right disparity map as well -- PBCP$_r$). Measures tailored to SGM results in average performance. \begin{table}[t] \centering \scalebox{0.68}{ \renewcommand{\tabcolsep}{2pt} \begin{tabularx}{\textwidth}{cc} \begin{tabular}{.l;c|c|c|c|c;c.} \toprule & Driv. & 2012 & 2015 & Midd. & ETH & R.\\ \midrule \rowcolor{localcolor} APKR$_{5}$ & 10.88 & 0.86 & 1.57 & 6.05 & 4.03 & 4\\ APKRN$_{5}$ & 17.75 & 2.48 & 2.73 & 8.44 & 4.82 & 22\\ CUR & 17.14 & 2.84 & 2.93 & 9.65 & 6.62 & 29\\ DAM & 23.16 & 5.26 & 5.19 & 17.97 & 10.73 & 44\\ LC & 16.53 & 3.05 & 3.09 & 10.14 & 7.52 & 32\\ MM & 10.60 & 1.11 & 1.94 & 6.95 & 5.26 & 8\\ MMN & 17.98 & 3.08 & 3.04 & 10.10 & 6.26 & 33\\ MSM & 13.30 & 0.88 & 1.96 & 6.09 & 3.59 & 7\\ NLM & 10.60 & 1.11 & 1.94 & 6.95 & 5.26 & 9\\ NLMN & 17.98 & 3.08 & 3.04 & 10.10 & 6.26 & 34\\ PKR & 10.51 & 0.88 & 1.65 & 5.93 & 4.19 & 3\\ PKRN & 15.34 & 2.11 & 2.38 & 8.07 & 5.05 & 16\\ SGE & 13.12 & 0.81 & 1.86 & 5.96 & 3.41 & 6\\ WPKR$_{5}$ & 10.91 & 0.90 & 1.64 & 6.19 & 4.11 & 5\\ WPKRN$_{5}$ & 17.63 & 2.86 & 3.05 & 9.05 & 5.05 & 26\\ \rowcolor{fullcolor} ALM & 12.45 & 1.87 & 2.69 & 12.78 & 7.79 & 25\\ LMN & 23.28 & 3.15 & 3.75 & 11.34 & 5.73 & 35\\ MLM & 12.22 & 1.75 & 2.58 & 12.13 & 7.53 & 21\\ NEM & 17.66 & 4.38 & 4.43 & 18.24 & 12.03 & 41\\ NOI & 30.79 & 12.18 & 8.88 & 26.70 & 15.41 & 49\\ PER & 12.43 & 1.86 & 2.67 & 12.69 & 7.75 & 24\\ PWCFA & 11.85 & 1.45 & 2.18 & 8.33 & 6.33 & 13\\ WMN & 10.91 & 0.81 & 1.58 & \underline{5.45} & 3.33 & 1\\ WMNN & 13.80 & 1.33 & 2.03 & 6.53 & 4.07 & 11\\ \rowcolor{sgmcolor} PS & 15.83 & 2.33 & 2.83 & 9.88 & 7.46 & 27\\ \midrule \rowcolor{white} Opt. & 4.57 & 0.25 & 0.44 & 2.94 & 1.41 & -\\ D1(\%) & 26.92 & 6.08 & 6.03 & 21.80 & 12.59 & -\\ \midrule \end{tabular} & \begin{tabular}{.l;c|c|c|c|c;c.} \toprule & Driv. & 2012 & 2015 & Midd. & ETH & R.\\ \midrule \rowcolor{dispcolor} DA$_{15}$ & 18.31 & 2.65 & 3.18 & 7.63 & \underline{3.20} & 17\\ DMV & 18.18 & 2.43 & 2.90 & 10.37 & 6.27 & 31\\ DS$_{15}$ & 15.01 & 1.43 & 2.08 & 6.93 & 3.76 & 12\\ DTD & 11.39 & 2.26 & 1.89 & 12.46 & 7.76 & 20\\ MDD$_{21}$ & 15.82 & 2.40 & 2.61 & 12.18 & 5.93 & 28\\ MND$_{21}$ & 12.49 & 1.62 & 1.84 & 9.86 & 4.92 & 14\\ SKEW$_{21}$ & 12.31 & 1.97 & 2.36 & 10.84 & 7.71 & 19\\ VAR$_{17}$ & \underline{10.11} & \underline{0.78} & \underline{1.22} & 6.97 & 3.64 & 2\\ \rowcolor{lrcolor} ACC & 19.09 & 3.21 & 3.58 & 14.01 & 9.20 & 36\\ LRC & 20.04 & 3.58 & 4.08 & 14.92 & 9.08 & 38\\ LRD & 14.52 & 1.69 & 2.28 & 7.50 & 5.15 & 15\\ UC & 19.31 & 3.40 & 3.70 & 14.48 & 9.60 & 37\\ UCC & 13.10 & 1.06 & 1.99 & 6.37 & 3.70 & 10\\ UCO & 21.17 & 4.40 & 4.60 & 15.94 & 9.74 & 40\\ ZSAD & 15.53 & 5.39 & 4.69 & 15.94 & 10.36 & 39\\ \rowcolor{distcolor} DTS & 24.67 & 15.47 & 7.42 & 28.52 & 14.30 & 48\\ DSM & 13.35 & 6.96 & 2.98 & 7.17 & 4.67 & 18\\ SAMM & 11.56 & 7.90 & 2.14 & 11.73 & 6.44 & 30\\ \rowcolor{imagecolor} DB & 22.39 & 5.07 & 5.61 & 19.43 & 8.96 & 43\\ DLB & 22.45 & 3.64 & 4.34 & 18.25 & 9.98 & 42\\ DTE & 29.67 & 5.73 & 6.13 & 22.40 & 10.59 & 47\\ HGM & 27.25 & 5.57 & 5.72 & 21.04 & 11.17 & 45\\ IVAR$_{5}$ & 30.37 & 5.22 & 5.90 & 21.06 & 9.74 & 46\\ & & & & & & \\ \rowcolor{sgmcolor} SCS & 16.50 & 2.40 & 3.17 & 9.11 & 5.14 & 23\\ \midrule \rowcolor{white} Opt. & 4.57 & 0.25 & 0.44 & 2.94 & 1.41 & -\\ D1(\%) & 26.92 & 6.08 & 6.03 & 21.80 & 12.59 & -\\ \midrule \end{tabular} \end{tabularx} } \caption{\textbf{Results with MCCNN-SGM algorithm}, hand-crafted measures.} \label{tab:mccnn_sgm_hand} \end{table} \subsubsection{MCCNN-SGM} \textbf{Hand-crafted measures.} Table \ref{tab:mccnn_sgm_hand} reports the performance achieved by hand-crafted measures with the accurate MCCNN-SGM algorithm. The top-performing measure is WMN, followed by VAR$_{17}$ and PKR, all using different strategies. The outcome of this evaluation is very similar to the behavior observed in the Census-SGM experiments, confirming with SGM pipelines the excellent affinity of VAR and measures built from $c_{d_1}$ and $c_{d_2}$. Similarly to the previous experiments, the smooth disparity maps make measures processing the \colorbox{dispcolor}{disparity map} much less effective, with DS$_{15}$ the second-best in the category and only ranking 12 overall. On the other hand, confidences based on \colorbox{localcolor}{local properties} covers ranks from 3 to 9 while measures exploiting the \colorbox{fullcolor}{entire cost curve}, excluding WMN, shows up at positions 11 and 13 with WMNN and PWCFA. The best \colorbox{lrcolor}{left-right consistency} features rank 10 and 15, respectively, with UCC and LRD. As for Census-SGM experiments, DSM confirms the best among \colorbox{distcolor}{self-matching} measures ranking 18 and \colorbox{sgmcolor}{SGM-specific measures} show an average performance, placing over the middle of the leaderboard. As usual, \colorbox{imagecolor}{image properties} confirms ineffective. \textbf{Impact of the windows size.} Figure \ref{fig:mccnn_sgm_radius} plots the AUC achieved by varying the radius of $N(p)$ for measures computed over a local neighborhood. DA now saturates on $13\times13$ windows, while the other \colorbox{dispcolor}{disparity map} features mostly perform better with size 21, except for DS and VAR preferring respectively 15 and 17 windows size. All measures computed from \colorbox{localcolor}{local properties} and IVAR achieve their best results on $5\times5$ windows. \begin{figure}[t] \centering \begin{tabular}{c} \includegraphics[width=0.38\textwidth]{images/plots/mccnn-sgm1.pdf} \\ \includegraphics[width=0.38\textwidth]{images/plots/mccnn-sgm2.pdf} \\ \includegraphics[width=0.38\textwidth]{images/plots/mccnn-sgm3.pdf} \\ \end{tabular} \caption{\textbf{Impact of N(p) size}, MCCNN-SGM algorithm.} \label{fig:mccnn_sgm_radius} \end{figure} \begin{table}[t] \centering \scalebox{0.68}{ \renewcommand{\tabcolsep}{2pt} \begin{tabularx}{\textwidth}{cc} \begin{tabular}{.l;c;c|c;c|c;c;c.} \multicolumn{8}{c}{Train set: Driving} \\ \toprule & Driv. & 2012 & 2015 & Midd. & ETH & R. & CR.\\ \midrule \rowcolor{forestvol} ENS$_{23}$ & 8.40 & 1.40 & 1.97 & 8.45 & 5.97 & 18 & 15\\ GCP & 9.00 & 1.37 & 1.66 & 12.33 & 6.57 & 19 & 20\\ LEV$_{22}$ & 8.29 & 1.26 & 1.71 & 7.78 & 4.83 & 17 & 11\\ LEV$_{50}$ & 7.60 & 1.06 & 1.51 & 6.75 & 4.23 & 11 & 5\\ FA & 7.07 & 2.54 & 2.38 & 10.60 & 6.83 & 5 & 21\\ \rowcolor{forestdisp} ENS$_{7}$ & 9.41 & 2.15 & 2.59 & 9.64 & 6.11 & 21 & 18\\ O1 & 7.48 & 1.70 & 2.09 & 8.10 & 5.04 & 10 & 14\\ O2 & 7.34 & 1.59 & 2.15 & 7.84 & 4.82 & 9 & 13\\ \rowcolor{deepdisp} CCNN & 8.05 & 1.64 & 2.05 & 10.10 & 4.74 & 16 & 16\\ PBCP$_{r}$ & 9.74 & \underline{0.91} & \underline{1.40} & \underline{5.98} & 3.33 & 23 & 1\\ PBCP$_{d}$ & 7.76 & 1.41 & 1.98 & 6.74 & \underline{3.25} & 15 & 4\\ EFN & 9.40 & 3.26 & 3.52 & 11.45 & 6.42 & 20 & 22\\ LFN & 7.67 & 2.66 & 2.96 & 10.60 & 5.34 & 13 & 19\\ MMC & 7.24 & 1.60 & 1.99 & 8.34 & 4.26 & 6 & 12\\ ConfNet & 7.31 & 1.16 & 1.81 & 8.40 & 3.31 & 8 & 8\\ LGC & 7.03 & 1.15 & 1.76 & 7.56 & 3.76 & 4 & 6\\ \rowcolor{deepvol} RCN & 11.40 & 1.83 & 2.86 & 15.58 & 9.46 & 24 & 24\\ MPN & 7.30 & 1.43 & 1.60 & 5.99 & 3.85 & 7 & 2\\ UCN & 7.01 & 1.23 & 1.63 & 6.22 & 3.80 & 3 & 3\\ LAF & \underline{6.21} & 0.99 & 1.76 & 6.88 & 5.96 & 1 & 10\\ ACN & 6.81 & 1.59 & 2.00 & 6.46 & 4.28 & 2 & 7\\ CRNN & 9.54 & 1.30 & 2.21 & 16.61 & 9.38 & 22 & 23\\ CVA & 7.62 & 1.61 & 2.23 & 9.49 & 5.36 & 12 & 17\\ \rowcolor{sgmcolor} SGMF & 7.71 & 1.72 & 1.53 & 6.64 & 4.85 & 14 & 9\\ \midrule \rowcolor{white} Opt. & 4.57 & 0.25 & 0.44 & 2.94 & 1.41 & - & -\\ D1(\%) & 26.92 & 6.08 & 6.03 & 21.80 & 12.59 & - & -\\ \midrule \end{tabular} & \begin{tabular}{.l;c|c;c|c;c.} \multicolumn{6}{c}{Train set: KITTI 2012} \\ \toprule & 2012 & 2015 & Midd. & ETH & R.\\ \midrule \rowcolor{forestvol} ENS$_{23}$ & 0.82 & 1.64 & 7.94 & 5.39 & 17\\ GCP & 1.00 & 1.91 & 7.53 & 5.61 & 18\\ LEV$_{22}$ & 0.81 & 1.37 & 8.43 & 4.13 & 13\\ LEV$_{50}$ & 0.75 & 1.15 & 6.46 & 3.92 & 3\\ FA & 1.08 & 1.33 & 7.76 & 5.50 & 16\\ \rowcolor{forestdisp} ENS$_{7}$ & 1.27 & 1.82 & 9.84 & 6.55 & 21\\ O1 & 0.80 & 1.21 & 6.46 & 5.03 & 10\\ O2 & 0.72 & \underline{1.07} & 6.24 & 5.36 & 9\\ \rowcolor{deepdisp} CCNN & 0.89 & 1.22 & 7.64 & 5.11 & 14\\ PBCP$_{r}$ & 0.86 & 1.25 & 6.09 & 5.07 & 7\\ PBCP$_{d}$ & 1.08 & 1.44 & 12.71 & 12.18 & 22\\ EFN & 1.27 & 1.41 & 9.52 & 4.71 & 19\\ LFN & 0.99 & 1.17 & 7.75 & 5.35 & 15\\ MMC & 0.93 & 1.11 & 7.01 & 4.75 & 12\\ ConfNet & 0.87 & 1.36 & 6.93 & \underline{3.40} & 5\\ LGC & 0.85 & 1.10 & 6.87 & 4.83 & 11\\ \rowcolor{deepvol} RCN & 1.02 & 2.52 & 22.54 & 12.38 & 24\\ MPN & 0.63 & 1.14 & 6.76 & 3.82 & 4\\ UCN & 0.67 & 1.19 & 6.32 & 3.54 & 2\\ LAF & \underline{0.61} & 1.21 & \underline{6.01} & 3.72 & 1\\ ACN & 0.63 & 1.22 & 7.31 & 3.83 & 6\\ CRNN & 0.98 & 2.24 & 21.80 & 12.20 & 23\\ CVA & 0.77 & 1.49 & 8.61 & 6.06 & 20\\ \rowcolor{sgmcolor} SGMF & 0.83 & 1.83 & 6.46 & 4.25 & 8\\ \midrule \rowcolor{white} Opt. & 0.25 & 0.44 & 2.94 & 1.41 & -\\ D1(\%) & 6.08 & 6.03 & 21.80 & 12.59 & -\\ \midrule \end{tabular} \end{tabularx} } \caption{\textbf{Results with MCCNN-SGM algorithm}, learned measures.} \label{tab:mccnn_sgm_learning} \end{table} \begin{figure*}[t] \scriptsize \centering \renewcommand{\tabcolsep}{1pt} \rotatebox{90}{KITTI} \rotatebox{90}{2015} \subfigure{ \includegraphics[width=0.11\textwidth, frame]{images/qualitative/census-CBCA/2015/000197_10.png}} \subfigure{ \includegraphics[width=0.11\textwidth, frame]{images/qualitative/mccnn-SGM/2015/disparity.png}} \subfigure{ \includegraphics[width=0.11\textwidth, frame]{images/qualitative/mccnn-SGM/2015/apkr_7.png}} \subfigure{ \includegraphics[width=0.11\textwidth, frame]{images/qualitative/mccnn-SGM/2015/wmn.png}} \subfigure{ \includegraphics[width=0.11\textwidth, frame]{images/qualitative/mccnn-SGM/2015/da_31.png}} \subfigure{ \includegraphics[width=0.11\textwidth, frame]{images/qualitative/mccnn-SGM/2015/uc_cost.png}} \subfigure{ \includegraphics[width=0.11\textwidth, frame]{images/qualitative/mccnn-SGM/2015/samm.png}} \subfigure{ \includegraphics[width=0.11\textwidth, frame]{images/qualitative/mccnn-SGM/2015/k12-laf.png} } \\ \rotatebox{90}{Middlebury} \subfigure{ \includegraphics[width=0.11\textwidth, frame]{images/qualitative/census-CBCA/MiddEval3/Playtable.png}} \subfigure{ \includegraphics[width=0.11\textwidth, frame]{images/qualitative/mccnn-SGM/MiddEval3/disparity.png}} \subfigure{ \includegraphics[width=0.11\textwidth, frame]{images/qualitative/mccnn-SGM/MiddEval3/apkr_7.png}} \subfigure{ \includegraphics[width=0.11\textwidth, frame]{images/qualitative/mccnn-SGM/MiddEval3/wmn.png}} \subfigure{ \includegraphics[width=0.11\textwidth, frame]{images/qualitative/mccnn-SGM/MiddEval3/da_31.png}} \subfigure{ \includegraphics[width=0.11\textwidth, frame]{images/qualitative/mccnn-SGM/MiddEval3/uc_cost.png}} \subfigure{ \includegraphics[width=0.11\textwidth, frame]{images/qualitative/mccnn-SGM/MiddEval3/samm.png}} \subfigure{ \includegraphics[width=0.11\textwidth, frame]{images/qualitative/mccnn-SGM/MiddEval3/k12-laf.png} } \\ \caption{\textbf{Qualitative results concerning MCCNN-SGM algorithm.} Results on KITTI 2015 and Middlebury showing a variety of confidence measures. From top left to bottom right: reference image, disparity map and confidence maps by APKR$_7$, WMN, DA$_{31}$, UCC, SAMM and LAF.} \label{fig:qualitative_mccnn_sgm} \end{figure*} \textbf{Learned measures, synthetic data training.} Table \ref{tab:mccnn_sgm_learning}, on the left, collects results for learned measures when trained on synthetic images from the Driving train split. As for Census-SGM, on the synthetic test split, LAF performs the best, followed by ACN and UN all of the \colorbox{deepvol}{cost-volume CNNs}. Close follow-up methods are LGC and FA, respectively a \colorbox{deepdisp}{disparity CNN} and a \colorbox{forestdisp}{disparity forest}. In general, we can notice two opposite trends with CNNs and forests. When processing the cost volume, the former class is typically more effective, while forest-based methods processing the disparity map (\emph{e.g.}, O1 and O2) yield better results than those working in the cost volume space (\emph{e.g.}, LEV$_{50}$, LEV and GCP). Focusing on patch-based models, the left-right consistency enforced by PBCP$_{d}$ allows it to outperform CCNN, while PBCP$_{r}$ results less effective than both. Finally, \colorbox{sgmcolor}{SGMF} ranks in the lower half of the leaderboard, yielding, for instance, better accuracy than the majority of \colorbox{forestvol}{cost-volume forests}. Concerning generalization to real data, as for Census-SGM, the impact of domain shift is more significant. This time, none of the learned measures outperform the top-performing hand-crafted one WMN on KITTI 2012. On the other hand, this occurs in only three cases on KITTI 2015 (SGMF, LEV$_{50}$ and PBCP$_r$) and ETH3D (both PBCBs and ConfNet). In contrast, WMN is always more effective than any learned method on the Middlebury dataset. Conversely to Census-SGM, LAF loses rank 1, dropping to 10 in favor of PBCP$_{r}$. This outcome and the fourth place achieved by PBCP$_{d}$ highlights that the information from the right disparity map is highly impactful for MCCNN-SGM, a stereo algorithm producing very smooth disparity maps. In particular, enforcing left-right consistency allows for more substantial generalization even on Middlebury and ETH3D. Again, PBCP$_r$ better generalizes than PBCP$_d$. Most \colorbox{forestvol}{cost-volume forests} gain positions, conversely to \colorbox{forestdisp}{disparity forests} and \colorbox{deepdisp}{disparity CNNs}. In general, most \colorbox{deepvol}{cost-volume CNNs} keep their rankings with LAF, ACN and CVA notable negative exceptions and MPN a positive one. Finally, \colorbox{sgmcolor}{SGMF} improves its position from 14 to 9 confiming its effectiveness with SGM-based stereo methods. \textbf{Learned measures, real data training.} Table \ref{tab:mccnn_sgm_learning}, on the right, collects results for learned measures when trained on KITTI 2012 20 training images. We can notice that many of them now outperform the top-1 hand-crafted measure on the KITTI 2012 dataset, and more frequently on KITTI 2015, thanks to the much more similar domain observed during training. Specifically, the following measures, belonging to four different categories, are more effective than WMN on both KITTI datasets: LEV$_{50}$, O1, O2, MPN, UN, LAF, ACN and CVA. In contrast, none of the learned measures achieves better accuracy than WMN on Middlebury and ETH3D. In summary, \colorbox{deepvol}{cost-volume CNNs} confirm to be the most effective solution, with LAF and UN covering the top-2 positions, followed by LEV$_{50}$, MPN and ConfNet. O1 and O2, \colorbox{forestdisp}{disparity forests}, results the best in their category and better than all \colorbox{forestvol}{cost-volume forests} except LEV$_{50}$. Overall, in this experiment, SGMF achieves an accuracy slightly better than O1 and O2. Concerning patch-based networks, PBCP$_r$ once again stands as the best choice in these experiments. As already witnessed with the previous Census-SGM, \colorbox{deepdisp}{disparity CNNs} are rarely effective although ConfNet ranks 5. \textbf{Qualitative results.} Finally, as for previous qualitative results, Figure \ref{fig:qualitative_mccnn_sgm} shows an example of disparity maps from KITTI 2015 and Middlebury computed with the MCCNN-SGM algorithm and the output of six confidence maps, five hand-crafted and one learned (rightmost column). As observed in the case of Census-SGM, most measures assign high confidence to most pixels, correctly finding out that the amount of outliers in the disparity maps is very low. \textbf{Summary.} As observed for Census-SGM, the cost volume becomes a precious source of information to estimate confidence. Measures processing the disparity map alone rarely ranks on top of the leaderboard. A similar trend is observed, again, for learned measures as well that can properly learn to estimate confidence from the disparity map when processing a large receptive field or the right disparity map as well, while measures tailored to SGM confirm their average effectiveness among all methods. \subsection{GANet} To conclude our evaluation, we report experiments carried out with GANet to highlight how the final volumes produced by 3D neural networks for stereo can be converted into costs, allowing for the deployment of traditional and learned measures. Such an evaluation, using volumes from a deep neural network, is performed here for the first time. \textbf{Hand-crafted measures.} Table \ref{tab:ganet_hand} shows the performance achieved by hand-crafted measures. At first, we can notice how measures processing the \colorbox{dispcolor}{disparity map} performs much worse in this case. All of them dropping their rank below 20. We ascribe this fact to the extremely smooth disparity maps delivered by GANet, making it extremely hard to find outliers by only looking at disparity distributions. Most of top-20 positions mix measures processing \colorbox{localcolor}{local properties} or the \colorbox{fullcolor}{entire cost curve}. In particular, we point out the excellent performance achieved by MSM, reaching rank 1. We ascribe this fact to the soft-argmax operator used during training, forcing the output volume to have a strong maximum (converted to minima in our experiments). The results achieved by MSM suggest that the network itself produces weaker maxima when it is less certain about the predicted disparity. Other classic measures perform very well, such as ALM and MLM, rarely ranking in the top-10 positions in the previous experiments. Concerning measures with \textit{naive} variants, for the first time, some of them perform better than the original counterpart, such as PKRN, NLMN, and MMN. Probably, as another effect of the soft-argmax operator used during training. UCC is the first measure leveraging the \colorbox{lrcolor}{left-right consistency} and reaches rank 8, while within \colorbox{distcolor}{self-matching} measures SAMM achieves the best results and ranks 20. Finally, measures based on \colorbox{imagecolor}{image properties} confirm ineffective as in any previous experiment. \begin{table}[t] \centering \scalebox{0.68}{ \renewcommand{\tabcolsep}{2pt} \begin{tabularx}{\textwidth}{cc} \begin{tabular}{.l;c|c|c|c|c;c.} \toprule & Driv. & 2012 & 2015 & Midd. & ETH & R.\\ \midrule \rowcolor{localcolor} APKR$_{5}$ & 11.45 & \underline{2.48} & \underline{3.91} & \underline{12.82} & \underline{3.47} & 11\\ APKRN$_{5}$ & 10.75 & 3.61 & 5.41 & 15.21 & 4.71 & 17\\ CUR & 5.96 & 2.74 & 4.38 & 14.08 & 4.01 & 5\\ DAM & 16.10 & 8.33 & 9.69 & 27.82 & 10.50 & 40\\ LC & \underline{5.42} & 2.88 & 4.59 & 16.67 & 6.43 & 12\\ MM & 17.98 & 8.96 & 10.54 & 26.08 & 9.81 & 43\\ MMN & 8.35 & 3.87 & 5.64 & 17.09 & 5.33 & 18\\ MSM & 6.71 & 2.69 & 4.33 & 13.47 & 3.65 & 1\\ NLM & 17.97 & 8.95 & 10.53 & 26.07 & 9.81 & 42\\ NLMN & 8.35 & 3.87 & 5.64 & 17.09 & 5.33 & 19\\ PKR & 21.75 & 11.67 & 12.87 & 33.87 & 17.70 & 47\\ PKRN & 8.09 & 3.58 & 5.40 & 15.73 & 4.88 & 14\\ SGE & 7.11 & 2.60 & 4.26 & 13.37 & 4.16 & 7\\ WPKR$_{5}$ & 10.55 & 2.61 & 4.28 & 13.03 & 3.59 & 10\\ WPKRN$_{5}$ & 9.72 & 3.83 & 5.76 & 15.49 & 4.77 & 16\\ \rowcolor{fullcolor} ALM & 6.71 & 2.69 & 4.33 & 13.47 & 3.65 & 2\\ LMN & 16.61 & 8.12 & 9.52 & 23.78 & 7.85 & 36\\ MLM & 6.71 & 2.69 & 4.33 & 13.47 & 3.65 & 3\\ NEM & 6.56 & 2.67 & 4.33 & 13.73 & 4.08 & 6\\ NOI & 10.46 & 5.66 & 6.98 & 23.10 & 8.69 & 25\\ PER & 6.71 & 2.69 & 4.33 & 13.47 & 3.65 & 4\\ PWCFA & 7.14 & 2.72 & 4.20 & 14.48 & 3.59 & 9\\ WMN & 16.04 & 8.31 & 9.89 & 26.81 & 10.72 & 39\\ WMNN & 8.05 & 3.53 & 5.36 & 15.43 & 4.79 & 13\\ \midrule \rowcolor{white} Opt. & 1.69 & 0.57 & 0.85 & 5.28 & 0.99 & -\\ D1(\%) & 16.66 & 8.62 & 10.02 & 28.61 & 10.80 & -\\ \midrule \end{tabular} & \begin{tabular}{.l;c|c|c|c|c;c.} \toprule & Driv. & 2012 & 2015 & Midd. & ETH & R.\\ \midrule \rowcolor{dispcolor} DA$_{11}$ & 12.85 & 7.85 & 9.21 & 23.41 & 6.24 & 29\\ DMV & 16.84 & 7.16 & 8.55 & 24.39 & 8.84 & 35\\ DS$_{15}$ & 12.95 & 6.44 & 7.68 & 23.32 & 6.63 & 26\\ DTD & 13.21 & 7.61 & 9.17 & 27.13 & 7.88 & 34\\ MDD$_{21}$ & 11.44 & 6.42 & 7.31 & 25.02 & 9.20 & 28\\ MND$_{21}$ & 11.04 & 4.91 & 5.50 & 23.74 & 8.90 & 24\\ SKEW$_{21}$ & 9.90 & 3.95 & 4.51 & 22.57 & 8.23 & 23\\ VAR$_{21}$ & 7.08 & 3.42 & 4.26 & 22.52 & 6.74 & 21\\ \rowcolor{lrcolor} ACC & 13.89 & 6.59 & 8.18 & 24.20 & 9.45 & 30\\ LRC & 13.53 & 6.98 & 8.09 & 25.39 & 9.86 & 32\\ LRD & 8.06 & 3.53 & 5.22 & 16.67 & 5.17 & 15\\ UC & 13.81 & 6.80 & 8.45 & 24.39 & 9.61 & 31\\ UCC & 7.02 & 2.82 & 4.45 & 13.93 & 3.67 & 8\\ UCO & 15.33 & 7.77 & 8.84 & 26.95 & 10.01 & 38\\ ZSAD & 7.28 & 7.23 & 8.62 & 24.53 & 9.57 & 27\\ \rowcolor{distcolor} DTS & 18.87 & 12.36 & 12.14 & 34.33 & 14.69 & 46\\ DSM & 9.26 & 4.60 & 7.11 & 16.58 & 9.15 & 22\\ SAMM & 8.01 & 3.63 & 5.11 & 19.12 & 6.29 & 20\\ \rowcolor{imagecolor} DB & 12.62 & 7.63 & 10.26 & 26.10 & 7.93 & 33\\ DLB & 16.34 & 7.05 & 9.09 & 26.50 & 9.35 & 37\\ DTE & 21.34 & 8.19 & 9.95 & 28.04 & 10.01 & 44\\ HGM & 18.33 & 8.10 & 9.49 & 27.02 & 9.81 & 41\\ IVAR$_{5}$ & 23.52 & 8.08 & 9.99 & 26.71 & 10.01 & 45\\ & & & & & & \\ \midrule \rowcolor{white} Opt. & 1.69 & 0.57 & 0.85 & 5.28 & 0.99 & -\\ D1(\%) & 16.66 & 8.62 & 10.02 & 28.61 & 10.80 & -\\ \midrule \end{tabular} \end{tabularx} } \caption{\textbf{Results with GANet model}, hand-crafted measures.} \label{tab:ganet_hand} \end{table} \begin{figure}[t] \centering \begin{tabular}{c} \includegraphics[width=0.38\textwidth]{images/plots/ganet1.pdf} \\ \includegraphics[width=0.38\textwidth]{images/plots/ganet2.pdf} \\ \includegraphics[width=0.38\textwidth]{images/plots/ganet3.pdf} \\ \end{tabular} \caption{\textbf{Impact of N(p) size}, GANet model.} \label{fig:ganet_radius} \end{figure} \begin{table}[t] \centering \scalebox{0.68}{ \renewcommand{\tabcolsep}{2pt} \begin{tabularx}{\textwidth}{cc} \begin{tabular}{.l;c;c|c;c|c;c;c.} \multicolumn{8}{c}{Train set: Driving} \\ \toprule & Driv. & 2012 & 2015 & Midd. & ETH & R. & CR. \\ \midrule \rowcolor{forestvol} ENS$_{23}$ & 3.48 & 4.15 & 4.85 & 27.53 & 8.58 & 6 & 12\\ GCP & 5.35 & 3.60 & 5.07 & 20.68 & 7.35 & 19 & 6\\ LEV$_{22}$ & 3.67 & 4.63 & 4.66 & 30.98 & 7.62 & 10 & 14\\ LEV$_{50}$ & 3.49 & 3.18 & 4.96 & 20.73 & 6.19 & 7 & 4\\ FA & 3.41 & 4.54 & 5.63 & 27.81 & 10.11 & 4 & 16\\ \rowcolor{forestdisp} ENS$_{7}$ & 5.75 & 7.09 & 8.43 & 25.49 & 9.19 & 20 & 19\\ O1 & 3.62 & 7.65 & 9.66 & 25.63 & 8.68 & 9 & 21\\ O2 & 3.55 & 7.53 & 9.80 & 25.38 & 8.05 & 8 & 20\\ \rowcolor{deepdisp} CCNN & 4.33 & 4.78 & 6.72 & 24.71 & 9.75 & 14 & 13\\ PBCP$_{r}$ & 4.81 & 3.51 & 4.28 & 23.48 & 7.95 & 17 & 8\\ PBCP$_{d}$ & 4.48 & 5.69 & 6.96 & 22.55 & 8.56 & 15 & 10\\ EFN & 8.91 & 7.20 & 9.38 & 27.05 & 10.48 & 23 & 22\\ LFN & 5.88 & 5.92 & 8.08 & 26.35 & 9.16 & 22 & 18\\ MMC & 5.19 & 5.04 & 6.78 & 24.07 & 8.22 & 18 & 11\\ ConfNet & 5.85 & 6.33 & 8.38 & 29.12 & 11.12 & 21 & 23\\ LGC & 3.72 & 5.73 & 7.43 & 25.59 & 9.28 & 11 & 15\\ \rowcolor{deepvol} RCN & 4.61 & 3.63 & 5.38 & \underline{16.56} & \underline{5.18} & 16 & 1\\ MPN & \underline{3.21} & \underline{2.71} & \underline{4.06} & 20.19 & 6.43 & 1 & 3\\ UCN & 3.76 & 3.27 & 4.98 & 21.02 & 6.49 & 12 & 5\\ LAF & 3.46 & 3.81 & 4.94 & 22.64 & 7.32 & 5 & 7\\ ACN & 3.25 & 3.72 & 5.58 & 23.64 & 7.42 & 2 & 9\\ CRNN & 3.32 & 3.20 & 5.28 & 17.93 & 6.29 & 3 & 2\\ CVA & 3.81 & 5.54 & 7.92 & 26.11 & 9.92 & 13 & 17\\ \midrule \rowcolor{white} Opt. & 1.69 & 0.57 & 0.85 & 5.28 & 0.99 & - & -\\ D1(\%) & 16.66 & 8.62 & 10.02 & 28.61 & 10.80 & - & -\\ \midrule \end{tabular} & \begin{tabular}{.l;c|c;c|c;c.} \multicolumn{6}{c}{Train set: KITTI 2012} \\ \toprule & 2012 & 2015 & Midd. & ETH & R.\\ \midrule \rowcolor{forestvol} ENS$_{23}$ & 3.18 & 4.52 & 18.28 & 5.58 & 7\\ GCP & 4.19 & 5.39 & 21.00 & 5.24 & 9\\ LEV$_{22}$ & 2.26 & 3.32 & 17.58 & \underline{3.70} & 1\\ LEV$_{50}$ & 1.99 & 2.87 & 17.87 & 4.17 & 2\\ FA & 4.59 & 5.68 & 23.09 & 7.92 & 20\\ \rowcolor{forestdisp} ENS$_{7}$ & 5.05 & 6.00 & 22.46 & 6.37 & 18\\ O1 & 3.20 & 4.02 & 22.54 & 7.36 & 11\\ O2 & 2.76 & 3.67 & 22.03 & 7.10 & 8\\ \rowcolor{deepdisp} CCNN & 3.29 & 3.93 & 23.34 & 7.02 & 14\\ PBCP$_{r}$ & 4.02 & 4.93 & 19.83 & 8.59 & 13\\ PBCP$_{d}$ & 3.46 & 4.14 & 22.50 & 12.56 & 22\\ EFN & 4.84 & 5.36 & 23.83 & 4.96 & 17\\ LFN & 3.77 & 4.25 & 23.00 & 6.13 & 12\\ MMC & 3.84 & 4.49 & 23.89 & 5.45 & 16\\ ConfNet & 5.46 & 5.21 & 22.31 & 4.69 & 15\\ LGC & 3.53 & 4.61 & 22.42 & 6.31 & 10\\ \rowcolor{deepvol} RCN & 2.81 & 3.82 & \underline{16.12} & 6.04 & 4\\ MPN & 3.89 & 4.40 & 26.64 & 12.67 & 23\\ UCN & 2.62 & 3.18 & 23.31 & 12.23 & 21\\ LAF & \underline{1.70} & \underline{2.58} & 18.19 & 7.40 & 5\\ ACN & 2.17 & 2.96 & 17.99 & 6.89 & 6\\ CRNN & 2.41 & 3.20 & 16.33 & 6.18 & 3\\ CVA & 4.00 & 4.90 & 23.12 & 8.75 & 19\\ \midrule \rowcolor{white} Opt. & 0.57 & 0.85 & 5.28 & 0.99 & -\\ D1(\%) & 8.62 & 10.02 & 28.61 & 10.80 & -\\ \midrule \end{tabular} \end{tabularx} } \caption{\textbf{Results with GANet}, learned measures.} \label{tab:ganet_learning} \end{table} \begin{figure*}[t] \scriptsize \centering \renewcommand{\tabcolsep}{1pt} \rotatebox{90}{KITTI} \rotatebox{90}{2015} \subfigure{ \includegraphics[width=0.11\textwidth, frame]{images/qualitative/census-CBCA/2015/000197_10.png}} \subfigure{ \includegraphics[width=0.11\textwidth, frame]{images/qualitative/ganet/2015/disparity.png}} \subfigure{ \includegraphics[width=0.11\textwidth, frame]{images/qualitative/ganet/2015/apkr_7.png}} \subfigure{ \includegraphics[width=0.11\textwidth, frame]{images/qualitative/ganet/2015/wmn.png}} \subfigure{ \includegraphics[width=0.11\textwidth, frame]{images/qualitative/ganet/2015/da_31.png}} \subfigure{ \includegraphics[width=0.11\textwidth, frame]{images/qualitative/ganet/2015/uc_cost.png}} \subfigure{ \includegraphics[width=0.11\textwidth, frame]{images/qualitative/ganet/2015/samm.png}} \subfigure{ \includegraphics[width=0.11\textwidth, frame]{images/qualitative/ganet/2015/k12-laf.png} } \\ \rotatebox{90}{Middlebury} \subfigure{ \includegraphics[width=0.11\textwidth, frame]{images/qualitative/census-CBCA/MiddEval3/Playtable.png}} \subfigure{ \includegraphics[width=0.11\textwidth, frame]{images/qualitative/ganet/MiddEval3/disparity.png}} \subfigure{ \includegraphics[width=0.11\textwidth, frame]{images/qualitative/ganet/MiddEval3/apkr_7.png}} \subfigure{ \includegraphics[width=0.11\textwidth, frame]{images/qualitative/ganet/MiddEval3/wmn.png}} \subfigure{ \includegraphics[width=0.11\textwidth, frame]{images/qualitative/ganet/MiddEval3/da_31.png}} \subfigure{ \includegraphics[width=0.11\textwidth, frame]{images/qualitative/ganet/MiddEval3/uc_cost.png}} \subfigure{ \includegraphics[width=0.11\textwidth, frame]{images/qualitative/ganet/MiddEval3/samm.png}} \subfigure{ \includegraphics[width=0.11\textwidth, frame]{images/qualitative/ganet/MiddEval3/k12-laf.png} } \\ \caption{\textbf{Qualitative results concerning GANet.} Results on KITTI 2015 and Middlebury showing a variety of confidence measures. From top left to right: reference image, disparity map and confidence maps by APKR$_7$, WMN, DA$_{31}$, UCC, SAMM and LAF.} \label{fig:qualitative_ganet} \end{figure*} \textbf{Impact of the windows size.} Figure \ref{fig:ganet_radius} plots the AUC achieved by varying the radius of $N(p)$ for measures computed over a local neighborhood. Except for DA and DS, saturating respectively on $11\times11$ and $15\times15$ windows, all features computed from the \colorbox{dispcolor}{disparity map} show their best performance with a window size of 21. \colorbox{localcolor}{Local properties} and IVAR achieve their best accuracy on $5\times5$ kernels, rapidly degrading with larger windows. \textbf{Learned measures, synthetic data training.} Table \ref{tab:ganet_learning}, on the left, collects results for learned measures when trained on synthetic images from the Driving train split. Not surprisingly, \colorbox{deepvol}{cost-volume CNNs} cover the top 3 positions with MPN, ACN and CRNN, followed by \colorbox{forestvol}{cost-volume forests}. O1 and O2 are the only \colorbox{forestdisp}{disparity forests} appearing in the first ten positions and \colorbox{deepdisp}{disparity CNNs} perform much worse with the best one, LGC, ranking 11. This outcome occurs because of the very smooth disparity maps produced by GANet, over which finding outliers without analyzing the cost volume is particularly challenging. Regarding generalization to real data, \colorbox{deepvol}{cost-volume CNNs} cover the top-3 positions with RC, CRNN and MPN. They are followed by LEV$_{50}$ and GCP, respectively, with ranks 4 and 6. The first \colorbox{deepdisp}{disparity CNN} is PBCP$_d$ with rank 8. Finally, \colorbox{forestdisp}{disparity forests} such as O1 and O2, very effective on synthetic data, shows poor generalization and are at the bottom of the leaderboard. \textbf{Learned measures, real data training.} Table \ref{tab:ganet_learning}, on the right, reports results for learned measures trained on KITTI 2012 20 training images. Surprisingly, the top-2 methods are LEV and LEV$_{50}$, \emph{i.e.}{} \colorbox{forestvol}{cost-volume forests}, followed by \colorbox{deepvol}{cost-volume CNNs} CRNN, RC, LAF and ACN. The first method processing disparity only is a \colorbox{forestdisp}{disparity forest}, \emph{i.e.}{} O2 ranking 8, while \colorbox{forestdisp}{disparity CNNs} show up only from position 10 with LGC. Within patch-based methods, LFN, PBCP$_r$ and CCNN are the three most effective, starting with rank 12, while PBCP$_d$ is at the bottom of the leaderboard. \textbf{Qualitative results.} As for previous experiments, Figure \ref{fig:qualitative_ganet} reports disparity and confidence maps from KITTI 2015 and Middlebury. When dealing with the volumes produced by GANet, we can notice how some hand-crafted measures are not particularly meaningful, as in the case of WMN, while others remain effective. Not surprisingly, learned measures (\emph{i.e.}{} LAF) better distinguish the few outliers from the large amount of correct matches. \textbf{Summary.} When dealing with a modern, deep network such as GANet, measures processing the disparity map alone, either learned or not, lose most of their effectiveness. Given the extremely regular structure of the estimated disparity maps, the cost volume becomes a crucial cue to properly estimate the confidence. \section{Overall summary and discussion} \label{sec:discussion} Given the exhaustive experiments carried out in this paper, we summarize next the key findings. Concerning hand-crafted measures: \begin{itemize} \item For traditional algorithms, \colorbox{dispcolor}{disparity features} are meaningful cues to estimate a confidence measure and some of them (e.g., DA, VAR) often achieves surprising results. \item The local content is also a strong cue in both cost volume/disparity map allowing APKR to rank within the top 4 hand-crafted methods with any CBCA/SGM variant. \item Although very popular, measures exploiting the consistency between \colorbox{lrcolor}{left-right} images achieve average performance. Among them, LRD and, more frequently, the uniqueness constraint consistently represent the best approaches. \item Not surprisingly, \colorbox{imagecolor}{image priors} alone can not provide reliable information about confidence since different stereo algorithms may be less or more robust to image content, such as in the case of textureless regions. In particular, their AUC is often higher than D1, worse than random selection. \item When dealing with GANet, \colorbox{dispcolor}{disparity features} alone are no longer enough and consistently achieve poor results. Measures processing the \colorbox{fullcolor}{entire cost curve} or \colorbox{localcolor}{local properties} seem the most effective. Surprisingly, PKR and WMN perform poorly and are outperformed by their naive counterparts, probably because of the soft-argmax operator used for training that forces matching distributions to be unimodal. This effect is softened by local content, as seen for APKR and WPKR. \end{itemize} Concerning learned measures: \begin{itemize} \item These methods generalize well across synthetic and real environments compared to other tasks, such as disparity estimation, without requiring aggressive data augmentation or thousands of training samples. This behavior is due to the much more regular domain (i.e., disparity and matching costs) observed by forests and networks. \item Despite the inliers/outliers distribution is sometimes strongly unbalanced (i.e., for SGM algorithms and GANet), forests and CNNs learn to infer significant confidence scores that outperform traditional ones, although with minor margins compared to what occurs for CBCA algorithms. \item Drops occurring when moving between KITTI and Middlebury/ETH3D datasets are not marginal, because of the very different structure (\emph{i.e.}, geometry) of the observed environments and results to have higher impact with respect to image content. This fact makes learned methods often close to hand-crafted measures on Middlebury/ETH3D and, in some cases, even outperformed. \item Among learned methods, \colorbox{deepvol}{cost-volume CNNs} confirm to be the overall winning family, with \colorbox{deepdisp}{disparity CNNs} being competitive in particular when dealing with noisy stereo algorithms. \end{itemize} \section{Conclusion} \label{sec:conclusions} In this paper, we have presented an exhaustive review and evaluation of the state-of-the-art strategy to estimate stereo matching confidence. We have reviewed more than ten years of developments in this field, ranging from hand-engineered confidence measures to modern machine learning and deep learning solutions. Moreover, we have carried out an extensive evaluation for a thorough understanding of the topic, involving five stereo algorithms/networks and five datasets. We believe this review can represent a useful reference for researchers working in depth from stereo and practitioners willing to deploy stereo algorithms in the wild. Despite the significant improvement yielded by learning-based strategies, improving their generalization across real domains is crucial as a future research direction. \textbf{Acknowledgments} We gratefully acknowledge the support of NVIDIA Corporation with the donation of the Titan Xp GPU used for this research. The work of S. Kim was supported by the MSIT (Ministry of Science and ICT), Korea, under the ICT Creative Consilience program (IITP-2021-0-01819) supervised by the IITP. \bibliographystyle{IEEEtran}
{'timestamp': '2021-04-01T02:02:51', 'yymm': '2101', 'arxiv_id': '2101.00431', 'language': 'en', 'url': 'https://arxiv.org/abs/2101.00431'}
arxiv
\section{Introduction} \label{sec:introduction} Employing CNNs in semantic segmentation tasks has been proven to be extremely helpful in various applications, including object tracking~\cite{yilmaz2006survey,bertinetto2016fully,Zhu_2018_ECCV}, self-driving cars~\cite{Kim_2017_ICCV,Hecker_2018_ECCV}, and medical image analysis~\cite{ker8241753deep,shen2017deep,AYACHE2017xxiii,KAZEMINIA2020101938}. This success, however, is conditioned on the availability of huge manually annotated datasets to supervise the training of state-of-the-art (SOTA) network structures~\cite{rostami2018crowdsourcing,Toldo_Maracani_Michieli_Zanuttigh_2020}. This condition is not always realized in practice, especially in fields such as medical image segmentation, where annotating data requires the input of trained experts and privacy regulations make sharing data for crowd-sourcing extremely restricted, and at times impossible. A characteristic of data in the area of medical image segmentation is the existence of \textit{domain shift} between different imaging modalities, which stems from using imaging devices based on totally different electromagnetic principles, e.g., CT vs MRI. When domain gap exists between the distributions of the training (source) and the testing (target) data, the performance of CNNs can degrade significantly. This makes continual data annotation necessary for maintaining model performance. Domain shift is a major area of concern, as data annotation is a challenging procedure even for the simplest semantic segmentation tasks~\cite{estimating2011liu}. Annotating medical images is also expensive, as annotation can be performed only by physicians, who undergo years of training to obtain domain expertise. Unsupervised domain adaptation (UDA) is a learning setting aimed at reducing \textit{domain gap} without data annotation in the target domain. The goal is to adapt a source-trained model for improved generalization in the target domain using solely unannotated data~\cite{ghifary2016deep,venkateswara2017deep,saito2018maximum,zhang2018collaborative}. The core idea in UDA is to achieve knowledge transfer from the source domain to the target domain by aligning the latent features of the two domains in an embedding space. This idea has been implemented either using adversarial learning~\cite{hoffman2018cycada,dou2019pnp,tzeng2017adversarial,bousmalis2017unsupervised}, directly minimizing the distance of distributions of the latent features with respect to a probability metric~\cite{chen2019progressive,sun2017correlation,lee2019sliced,rost2021unsupervised}, or a combination of the two~\cite{choi2019self,sankaranarayanan2018generate}. While existing UDA algorithms have been successful in reducing cross-domain gap, the vast majority of these approaches require sharing data between the source and target domains to enforce distribution alignment. This requirement limits the applicability of most existing works when sharing data may not be possible, e.g., sharing data is heavily regulated in healthcare domains due to the confidentiality of patient data and from security concerns. Until recently, there has been little exploration of UDA when access to the source domain is limited~\cite{kundu2020universal,saltori2020sf,qiu2021sourcefree,yang2021generalized,rostami2021domain}. These recent works benefit from generative adversarial learning to maintain source distribution information. However, addressing UDA for classification tasks limits the applicability of such methods to the problem of organ semantic segmentation~\cite{zhao2019knowledge}. A similar problem is encountered with UDA for street semantic segmentation \cite{Kundu_2021_ICCV}, given medical devices produce data distributions requiring additional preparation with large background areas \cite{zhou2019prioraware}. Recent medical works propose adaptation without source access via entropy minimization ~\cite{bateson2022source,BatesonSFDA}, but these methods are susceptible to degenerate solutions. \textbf{Contribution:} we develop a UDA algorithm for the semantic segmentation of medical images when sharing data is infeasible due to confidentiality or security concerns. Our approach is able to reduce domain gap without having direct access to the source data during adaptation. We learn the internal distribution for the source domain, and transfer knowledge between the source and target domains by distribution alignment between the learned internal distribution and the latent distribution of features of the target domain. We validate our algorithm on two medical image segmentation datasets, and observe comparable performance to SOTA methods based on joint training. \section{Related Work} \label{sec:relatedwork} SOTA semantic segmentation algorithms use deep neural network architectures to exploit large annotated datasets \cite{long2015fully,noh2015learning,lin2017refinenet,lecun2015deep}. These approaches are based on training a CNN encoder using manually annotated segmentation maps to learn a latent embedding of the data. An up-sampling decoder combined with a classifier is then used to infer pixel-wise estimations for the true semantic labels. Performance of such methods is high when large amounts of annotated data are available for supervised training. However, these methods are not suitable when the goal is to transfer knowledge between different domains~\cite{saito2018maximum,pan2019transferrable}. Model adaptation from a fully annotated source domains to a target domains has been explored in both semi-supervised and unsupervised settings. Semi-supervised approaches rely on the presence of a small number of annotated target data samples~\cite{motiian2017few,zhang2019few}. For example, a weakly supervised signal on the target domain can be obtained using bounding boxes. However, manual data annotation of a small number of images is still a considerable bottleneck in the area of medical imaging because only trained professionals can perform this task. For this reason, UDA algorithms are more appealing for healthcare applications. UDA approaches have explored two main strategies to reduce the domain gap. A large number of works rely on generative adversarial networks (GANs)~\cite{Zhang_2018_CVPR,10.1007/978-3-319-59050-9_47}. The core idea is to use a GAN loss such that data points from both domains can be mapped into a domain-invariant embedding space~\cite{hoffman2018cycada}. To this end, a cross-domain discriminator network is trained to classify whether data embeddings correspond to the source or target domain. An encoder network attempts to fool the discriminator by producing domain agnostic representations for source and target data points. Following this alternating optimization process, a classifier trained using source domain encodings produced by the encoder network would also generalize in the target domain~\cite{Ma_2019_CVPR,dou2018unsupervised}. The weakness of GANs is mode collapse, which requires careful fine-tuning and selection of hyper-parameters in order to be overcome. Other UDA approaches aim to directly align the distributions of the two domains in a shared embedding space~\cite{lee2019sliced,rostami2021transfer,stan2021unsupervised}. A shared encoder network is used to generate latent features for both domains. A common latent feature space is achieved by minimizing a suitable probability distance metric between the source and target embeddings \cite{drossos2019unsupervised,LE2019249,rostami2019deep,liu2020pdam}. Selecting proper distance metrics has been the major focus of research for these approaches. Optimal transport has been found particularly suitable for deep learning based UDA ~\cite{courty2016optimal}. We utilize the Sliced Wasserstein Distance (SWD)~\cite{lee2019sliced,rostami2021lifelong} variant of the optimal transport with similar properties, but which allows for fast gradient based optimization. The above mentioned sets of approaches have been found helpful in various medical semantic segmentation applications~\cite{huo2018adversarial,zhang2018task,chen2018semantic,kamnitsas2017unsupervised}. However, both strategies require direct access to source domain data for computing the loss functions. To relax this requirement, UDA has been recently explored in a source-free setting to address scenarios where the source domain is not directly accessible~\cite{kundu2020universal,saltori2020sf}. Both Kundu et al.~\cite{kundu2020universal} and Saltori et al.~\cite{saltori2020sf} target image classification, and benefit from generative adversarial learning to generate pseudo-data points that are similar to the source domain data in the absence of actual source samples. While both approaches are suitable for classification problems, extending them to semantic segmentation of medical images is not trivial. First, training models that can generate realistic medical images is considerably more challenging due to importance of fine details. Second, one may argue that if generated images are too similar to real images, the information confidentiality of patients in the training data may still be compromised. Our work is based on using a dramatically different approach. We develop a source-free UDA algorithm that performs the distribution alignment of two domains in an embedding space by using an intermediate internal distribution to relax the need for source data. \section{Problem Formulation} \label{sec:problemformulation} \begin{figure*}[!htb] \centering \includegraphics[width=.8\textwidth]{Figures/problem-formulation.png} \caption{\small Proposed method: We first perform supervised training on source MR images. Using the source embeddings we characterize an internal distribution via a GMM distribution in the latent space. We then perform source free adaptation by matching the embedding of the target CT images to the learnt GMM distribution, and fine tuning of the classifier on GMM samples. Finally, we verify the improved performance that our model gains from model adaptation. } \label{figure:problem-formulation} \vspace{-5mm} \end{figure*} Consider a source domain $D^S=(X^S,Y^S)$ with annotated data and a target domain $D^T=(X^T)$ with unannotated data that despite having different input spaces $X^S$ and $X^T$, e.g., due to using different medical imaging techniques, share the same segmentation map space $Y$, e.g., the same tissue/organ classes. Following the standard UDA pipeline, the goal is to learn a segmentation mapping function for the target domain by transferring knowledge from the source domain. To this end, we must learn a function $f_{\theta}(\cdot):\{X^S\cup X^T\} \rightarrow \{Y\}$ with learnable parameters $\theta$, e.g., a deep neural network, such that given an input image $x^*$, the function returns a segmentation mask $\hat y$ that best approximates the ground truth segmentation mask $y^*$. Given the annotated training dataset $\{(x^s,y^s)\}_{i=1}^N$ in the source domain, it is straightforward to train a segmentation model that generalizes well in the source domain through solving an empirical risk minimization (ERM) problem, i.e., $ \hat\theta = \arg \min_\theta \frac{1}{N} \sum_{i=1}^N \mathcal{L} (y^s, f_\theta(x^s)))$, where $\mathcal{L}$ is a proper loss function, e.g., the pixel-wise cross-entropy loss, defined as $\mathcal{L}_{ce} (y^*, \hat y) = - \sum_{i=1}^W \sum_{j=1}^H \sum_{k=1}^K y^*_{ijk} \log \hat y_{ijk}$. Here, $K$ denotes the number of segmentation classes, and $W,H$ represent the width and the height the input images, respectively. Each pixel label $y^*_{ij}$ will be represented as a one hot vector of size $K$ and $\hat y_{ij}$ is the prediction vector which assigns a probability weight to each label. Due to the existence of domain gap across the two domains, i.e. discrepancy between the source domain distribution $p^s(X)$ and the target domain distribution $p^t(X)$, the source-trained model using ERM may generalize poorly in the target domain. We want to benefit from the information encoded in the target domain unannotated dataset $\{x^t\}_{i=1}^M$ to improve the model generalization in the target domain further. We follow the common strategy of domain alignment in a shared embedding space to adress UDA. Consider our model $f$ to be a deep convolutional neural network (CNN). Let $f = \phi \circ \chi \circ \psi$, where $\psi(\cdot):\mathbb{R}^{W\times H \times C} \rightarrow \mathbb{R}^{U \times V}$ is a CNN encoder, $\chi(\cdot):\mathbb{R}^{U\times V} \rightarrow \mathbb{R}^{W \times H \times K}$ is an up-scaling CNN decoder, and $\phi(\cdot) : \mathbb{R}^{W \times H \times K} \rightarrow \mathbb{R}^{W \times H \times K}$ is a classification network that takes as inputs latent space representations and assigns label-probability values. We model the shared embedding space as the output space of the sub-network $\chi\circ\psi(\cdot)$. Solving UDA reduces to ensuring the source and target embedding distributions are aligned in the embedding space. This translates into minimizing the distributional discrepancy between the $\chi\circ\psi(p^s(\cdot))$ and $\chi\circ\psi(p^t(\cdot))$ distributions. A large group of UDA algorithms \cite{wu2018_dcan_eccv,zhang2017_curriculum} select a probability distribution metric $D(\cdot,\cdot)$, e.g. SWD or KL-divergence, and then use the source and the target domain data points, $X^S=[x^s_1,\ldots, x^s_N]$ and $X^T=[x^t_1,\ldots,x^t_N]$, to minimize the loss term $D(\chi\circ\psi(p^s(\cdot)),\chi\circ\psi(p^t(\cdot)))$ as a regularizer. However, this will constrain the user to have access to the source domain data to compute $D(\chi\circ\psi(p^s(\cdot)),\chi\circ\psi(p^t(\cdot)))$ that couples the two domains. We provide a solution to align the two domains without sharing the source domain data, that benefits from an intermediate probability distribution \section{Proposed Algorithm} \label{sec:proposedalgorithm} Our proposed approach is based on using the internal distribution $\mathcal{P_Z}$ as a surrogate for the learned distribution of the source domain in the embedding space. Upon training $f_\theta$ using ERM, the embedding space would become discriminative for the source domain. This means that the source distribution in the embedding space will be a multimodal distribution, where each mode denotes one of the classes. This distribution can be modeled as a Gaussian Mixture Model (GMM). To develop a source-free UDA algorithm, we can draw random samples from the GMM and instead of relying on the source data, align the target domain distribution with the internal distribution in the embedding space. In other words, we estimate the term $D(\chi\circ\psi(p^s(\cdot)),\chi\circ\psi(p^t(\cdot)))$ with $D(\mathcal{P_Z}(\cdot),\chi\circ\psi(p^t(\cdot)))$ which does not depend on source samples. We use SWD as the distribution metric for minimizing the domain discrepancy. A visual concept-level description for our approach is presented in Figure \ref{figure:problem-formulation}. \textbf{The intermediate distribution.} The function $\psi \circ \chi$ transforms the input distribution $p^s(\cdot)$ to the internal distribution $\mathcal{P_Z}(\cdot) = \chi\circ\psi(p^s(\cdot))$ based on which the classifier $\phi$ assigns labels. This distribution will have $K$ modes. Our idea is to approximate $\mathcal{P_Z}(\cdot)$ via a GMM with $\omega \times K$ components, with $\omega$ components for each of the $K$ semantic classes: \begin{equation*} \small \mathcal{P_Z}(z) = \sum_{c=1}^{\omega K} \alpha_c p_c(z) = \sum_{c=1}^{\omega K} \alpha_c \mathcal{N} (z | \mu_c, \Sigma_c), \end{equation*} where $\alpha_c$ represents the mixture probabilities, $\mu_c$ represents the mean of the Gaussian $c$, and $\Sigma_c$ is the covariance matrix of the $c^{th}$ component. Under the above representation, each semantic class $k \in \{1 \dots K\}$ will be represented by $\omega$ components: $(k-1) \omega + 1 \dots k \omega$. When the network $f$ is trained on the source domain, we can estimate the GMM parameters class-conditionally from the latent features obtained from the source training samples $\{ \phi(\chi(x^s))_{ijt}, y^s_{ij} \}$. Once class specific latent embeddings are computed via access to the labels $Y^S$, we estimate the corresponding $\omega$ components using the EM algorithm. \textbf{Sample selection.} To improve class separations in the internal distribution $\mathcal{P}_Z$, we only use high-confidence samples in each class for estimating parameters of $p_c(\cdot)$. We use a confidence threshold parameter $\rho$, and discard all samples for which the classifier confidence on its prediction $p_{ij}$ is strictly less than $\rho$. This step helps cancel out class outliers. Let $\mathcal{S}_\rho = \{(x_{ij}^s, y_{ij}^s) | \max\phi(\chi(\psi(x_{ij}))) > \rho\}$ be the source data pixels on which the classifier $\phi$ assigns confidence greater than $\rho$. Also, let $\mathcal{S}_{\rho,k} = \{ (x,y) | (x,y) \in \mathcal{S}_\rho, y = k\}$. Then, for each class $k$ we generate empirical estimates for the $\omega$ components defined by triplets $(\hat \alpha_{\omega (k - 1) + 1}, \hat \mu_{\omega (k - 1) + 1}, \hat \Sigma_{\omega (k - 1) + 1} ) \dots (\hat \alpha_{\omega k}, \hat \mu_{\omega k}, \hat \Sigma_{\omega k})$ by applying EM to $\mathcal{S}_{\rho,k}$ data points. \textbf{The adaptation loss.} Given the estimated internal distribution parameters $\hat\alpha, \hat\mu, \hat\Sigma$, we can perform domain alignment. Adapting the model should lead to the target latent distribution $ \chi(\psi(p^t(X)))$ matching the distribution $\mathcal{P}_Z$ in the embedding space. To this end, we can generate a pseudo-dataset $D^P = (Z^P,Y^P)$ by drawing samples from the GMM and aligning $\chi(\psi(X^T))$ with $Z^P$ to reduce the domain gap. The alignment loss can then be formalized as: \begin{equation} \small \begin{split} \mathcal{L}_{adapt} = \mathcal{L}_{ce} (\phi(Z^P), Y^P) + \lambda \mathcal{D} (\chi(\psi(X^T)), Z^P) \end{split} \label{eq:AdaptLoss} \end{equation} The first term in Eq.~\ref{eq:AdaptLoss} involves fine-tuning the classifier on samples from the pseudo-dataset $(Z^P,Y^P)$ to ensure that it would continue to generalize well. The second term enforces the distributional alignment. Since the source samples are not used in Eq.~\ref{eq:AdaptLoss}, data confidentiality will also be preserved. The last ingredient for our approach is selection of the distance metric $\mathcal{D}(\cdot,\cdot)$. We used SWD for this purpose. The pseudocode for our approach, called Source Free semantic Segmentation (SFS), is presented in Alg. ~\ref{SSUDAalgorithmSS}. \begin{wrapfigure}{R}{0.5\textwidth} \begin{minipage}{0.5\textwidth} \vspace{-25mm} \begin{algorithm}[H] \caption{$\mathrm{SFS}\left (\lambda , \rho, \omega \right)$\label{SSUDAalgorithmSS}} {\small \begin{algorithmic}[1] \State \textbf{Initial Training}: \State \hspace{2mm}\textbf{Input:} Source dataset $\mathcal{D}^{\mathcal{S}}=(\bm{X}^{\mathcal{S}}, \bm{Y}^{\mathcal{S}})$, \State \hspace{4mm}\textbf{Training on Source Domain:} \State \hspace{4mm} $\hat{ \theta}_0=\arg\min_{\theta}\sum_i \mathcal{L}(f_{\theta}(\bm{x}_i^s),\bm{y}_i^s)$ \State \hspace{2mm} \textbf{Internal Distribution Estimation:} \State \hspace{4mm} Set $\rho=.97$, compute $\mathcal{S}_{\rho, k}$, and estimate $\hat\alpha_j, \hat\mu_j,$ and $\hat\Sigma_j$ class conditionally via EM \State \textbf{Model Adaptation}: \State \hspace{2mm} \textbf{Input:} Target dataset $\mathcal{D}^{\mathcal{T}}=(\bm{X}^{\mathcal{T}})$ \State \hspace{2mm} \textbf{Pseudo-Dataset Generation:} \State $\mathcal{D}^{\mathcal{P}}=(\textbf{Z}^{\mathcal{P}},\textbf{Y}^{\mathcal{P}})=([\bm{z}_1^p,\ldots,\bm{z}_N^p],[\bm{y}_1^p,\ldots,\bm{y}_N^p])$, where: $\bm{z}_i^p\sim \mathcal{P}_Z(\bm{z}), 1\le i\le N_p$ \State \hspace{2mm} \textbf{for} $itr = 1 \rightarrow ITR$ \textbf{do} \State \hspace{4mm} Draw batches from $\mathcal{D}^{\mathcal{T}}$ and $\mathcal{D}^{\mathcal{P}}$ \State \hspace{4mm} Update the model by solving Eq.~\eqref{eq:AdaptLoss} \State \hspace{2mm} \textbf{end for} \end{algorithmic}} \end{algorithm} \end{minipage} \vspace{-2mm} \end{wrapfigure} \section{Experimental Validation} \label{sec:experimentalvalidation} \subsection{Datasets} \textbf{Multi-Modality Whole Heart Segmentation Dataset (MMWHS)~\cite{ZHUANG201677}:} this dataset consists of multi-modality whole heart images obtained on different imaging devices at different imaging sites. Segmentation maps are provided for $20$ MRI 3D heart images and $20$ CT 3D heart images which have domain gap. Following the UDA setup, we use the MRI images as the source domain and CT images as the target domain. We perform UDA with respect to four of the available segmentation classes: ascending aorta (AA), left ventricle blood cavity (LVC), left atrium blood cavity (LAC), myocardium of the left ventricle (MYO). We will use the same experimental setup and parsed dataset used by Dou et al.~\cite{dou2018unsupervised} for fair comparison. For the MRI source domain we use augmented samples from $16$ MRI 3D instances. The target domain consists of augmented samples from of $14$ 3D CT images, and we report results on $4$ CT instances, as proposed by Chen et al.~\cite{chen2020unsupervised}. Each 3D segmentation map used for assessing test performance is normalized to have zero mean and unit variance. \textbf{CHAOS MR $\rightarrow$ Multi-Atlas Labeling Beyond the Cranial Vault:} the second domain adaptation task consists of data frames from two different dataset. As source domain we, consider the the 2019 CHAOS MR dataset \cite{CHAOSdata2019}, previously used in the 2019 CHAOS Grad Challenge. The dataset consists of both MR and CT scans with segmentation maps for the following abdominal organs: liver, right kidney, left kidney and spleen. Similar to \cite{chen2020unsupervised} we use the T2-SPIR MR images as the source domain. Each scan is centered to zero mean and unit variance, and values more than three standard deviations away from the mean are clipped. In total, we obtain $20$ MR scans, $16$ of which we use for training and $4$ for validation. The target domain is represented by the dataset which was presented in the Multi-Atlas Labeling Beyond the Cranial Vault MICCAI 2015 Challenge \cite{landman2015multiatlas}. We utilize the $30$ CT scans in the training set which are provided segmentation maps, and use $24$ for adaptation and $6$ for evaluating generalization performance. The value range in the CT scans was first clipped to $[-125,275]$ HU following literature \cite{zhou2019prioraware}. The images were re-sampled to an axial view size of $256\times256$. Background was then cropped such that the distance between any labeled pixel and the image borders is at least $30$ pixels, and scans were again resized to $256\times256$. Finally, each 3D scan was normalized independently to zero mean and unit variance, and values more than three standard deviation from the mean were clipped. Data augmentation was performed on both the training MR and training CT instances using: (1) random rotations of up to $20$ degrees, (2) negating pixel values, (3) adding random Gaussian noise, (4) random cropping. Both of the above problems involve $3D$ scans. However our network encoder architecture receives $2D$ images at its input, where each image consists of three channels. To circumvent this discrepancy, we follow the frame-by-frame processing methodology by Chen et al.~\cite{chen2019synergistic}. We convert higher dimensional features into $2D$ images by creating images from groups of three consecutive scan slices, and using them as labels for the segmentation map of the middle slice. Implementation details re included in the Appendix \vspace{-3mm} \subsection{Evaluation Methodology} Following the medical image segmentation literature, we use two main metrics for evaluation: dice coefficient and average symmetric surface distance (ASSD). The Dice coefficient is a popular choice in medical image analysis works and measures semantic segmentation quality~\cite{chen2019synergistic,chen2020unsupervised,zhou2019prioraware}. It is used for direct evaluation of segmentation accuracy. The ASSD is a metric which has been used~\cite{SUN201758,chen2020unsupervised,DOU201740} to assess the quality of borders of predicted segmentation maps which are important for diagnosis. A good segmentation will have a large Dice coefficient and low ASSD value, the desirability of a result being application dependant. We compare our approach to other state-of-the-art techniques developed for unsupervised medical image segmentation. We compare against adversarial approaches PnP-AdaNet~\cite{dou2019pnp}, SynSeg-Net~\cite{Huo_2019}, AdaOutput~\cite{Tsai_adaptseg_2018}, CycleGAN~\cite{zhu2020unpaired}, CyCADA~\cite{hoffman2018cycada}, SIFA~\cite{chen2020unsupervised}, ARL-GAN~\cite{chen2020anatomy}, DSFN~\cite{ijcai2020-455}, SASAN~\cite{tomar2021self}, DSAN~\cite{han2021deep}. These works are recent methods for semantic segmentation that serve as \textbf{upper bounds} for our approach, as we do not process the source domain data directly. We reiterate the advantage of our method is to preserve the confidentiality of patient data, and we do not claim best performance. We also compare against GenAdapt \cite{Kundu_2021_ICCV}, a SOTA street semantic segmentation method that is not tuned for the medical field. Finally, we also evaluate our model against AdaEnt~\cite{BatesonSFDA} and AdaMI~\cite{bateson2022source}, two recent source-free approaches designed for medical semantic segmentation, and observe our methods outperforms both these techniques. Our code is available as a supplementary material. \vspace{-4mm} \subsection{Quantitative and Qualitative Results} Tables \ref{table:results-cardiac} and \ref{table:results-abdomen} summarize the segmentation performance for our method along with other baselines. As mentioned, when compared to other UDA approaches our method has the additional benefit of not violating data confidentiality on the source and target. This means most other approaches should serve as \textbf{upper bounds} for our algorithm, as they do not enforce restrictions for jointly accessing source and target data. We also compare against a recent street semantic segmentation algorithm \cite{Kundu_2021_ICCV} to verify whether real world adaptation approaches are at a disadvantage due to the specificity of medical data. We observe this approach has indeed lowest performance out of the considered methods. On the MMWHS dataset we achieve SOTA performance on class AA. We obtain the highest Dice score out of the considered methods, due to our high average performance on all classes. The ASSD score is competitive with other approaches, the best such score being observed for GAN based methods. This shows our domain alignment approach successfully maps each class in the target embedding to its corresponding vicinity using the internal distribution. For the abdominal task we observe similar trends. We achieve SOTA performance on class \textit{Liver}, and competitive performance on the other classes. These results suggest that our method offers the possibility of domain adaptation with competitive performance. \begin{table}[ht!] \begin{adjustbox}{center} \scalebox{.77}{ \small \setlength\tabcolsep{1.5pt} \begin{tabular} { |c|cccc|c|cccc|c| } \hline &\multicolumn{5}{c|}{Dice} &\multicolumn{5}{c|}{Average Symmetric Surface Distance} \\ \hline Method &AA &LAC &LVC &MYO &Average &AA &LAC &LVC &MYO &Average \\ \hline Source-Only &28.4 &27.7 &4.0 &8.7 &17.2 &20.6 &16.2 &N/A &48.4 &N/A \\ \hline Supervised$^*$ &88.7 &89.3 &89.0 &88.7 &87.2 &2.6 &4.9 &2.2 &1.6 &3.6 \\ \hline GenAdapt$^*$ \cite{Kundu_2021_ICCV} &57 &51 &36 &31 &43.8 &N/A &N/A &N/A &N/A &N/A \\ \hline PnP-AdaNet \cite{dou2019pnp} &74.0 &68.9 &61.9 &50.8 &63.9 &12.8 &6.3 &17.4 &14.7 &12.8 \\ \hline SynSeg-Net \cite{Huo_2019} &71.6 &69.0 &51.6 &40.8 &58.2 &11.7 &7.8 &7.0 &9.2 &8.9 \\ \hline AdaOutput \cite{Tsai_adaptseg_2018} &65.2 &76.6 &54.4 &43.3 &59.9 &17.9 &5.5 &5.9 &8.9 &9.6 \\ \hline CycleGAN \cite{zhu2020unpaired} &73.8 &75.7 &52.3 &28.7 &57.6 &11.5 &13.6 &9.2 &8.8 &10.8 \\ \hline CyCADA \cite{hoffman2018cycada} &72.9 &77.0 &62.4 &45.3 &64.4 &9.6 &8.0 &9.6 &10.5 &9.4 \\ \hline SIFA \cite{chen2020unsupervised} &81.3 &79.5 &73.8 &61.6 &74.1 &7.9 &6.2 &5.5 &8.5 &7.0 \\ \hline ARL-GAN \cite{chen2020anatomy} &71.3 &80.6 &69.5 &\textbf{81.6} &75.7 &6.3 &5.9 &6.7 &6.5 &6.4 \\ \hline DSFN \cite{ijcai2020-455} &84.7 &76.9 &79.1 &62.4 &75.8 &N/A &N/A &N/A &N/A &N/A \\ \hline SASAN \cite{tomar2021self} &82.0 &76.0 &82.0 &72.0 &78.0 &\textbf{4.1} &8.3 &\textbf{3.5} &\textbf{3.3} &\textbf{4.9} \\ \hline DSAN \cite{han2021deep} &79.9 &\textbf{84.7} &\textbf{82.7} &66.5 &78.5 &7.7 &6.7 &3.8 &5.6 &5.9 \\ \hline AdaEnt$^*$ \cite{BatesonSFDA} &75.5 &71.2 &59.4 &56.4 &65.6 &8.5 &7.1 &8.4 &8.6 &8.2 \\ \hline AdaMI$^*$ \cite{bateson2022source} &83.1 &78.2 &74.5 &66.8 &75.7 &5.6 &\textbf{4.2} &5.7 &6.9 &5.6 \\ \hline \hline \textbf{SFS$^*$} &\textbf{88.0} &83.7 &81.0 &72.5 &\textbf{81.3} &6.3 &7.2 &4.7 &6.1 &6.1 \\ \hline \end{tabular} } \end{adjustbox} \caption{Segmentation performance comparison for the Cardiac MR $\rightarrow$ CT adaptation task. Starred methods perform source-free adaptation. Bolded cells show best performance.} \label{table:results-cardiac} \end{table} \begin{table}[ht!] \begin{adjustbox}{center} \scalebox{.77}{\small \setlength\tabcolsep{1.5pt} \begin{tabular} { |c|cccc|c|cccc|c| } \hline &\multicolumn{5}{c|}{Dice} &\multicolumn{5}{c|}{Average Symmetric Surface Distance} \\ \hline Method &Liver &R.Kidney &L.Kidney &Spleen &Average &Liver &R.Kidney &L.Kidney &Spleen &Average \\ \hline Source-Only &73.1 &47.3 &57.3 &55.1 &58.2 &2.9 &5.6 &7.7 &7.4 &5.9 \\ \hline Supervised &94.2 &87.2 &88.9 &89.1 &89.8 &1.2 &1.2 &1.1 &1.7 &1.3 \\ \hline SynSeg-Net \cite{Huo_2019} &85.0 &82.1 &72.7 &81.0 &80.2 &2.2 &1.3 &2.1 &2.0 &1.9 \\ \hline AdaOutput \cite{Tsai_adaptseg_2018} &85.4 &79.7 &79.7 &81.7 &81.6 &1.7 &1.2 &1.8 &1.6 &1.6 \\ \hline CycleGAN \cite{zhu2020unpaired} &83.4 &79.3 &79.4 &77.3 &79.9 &1.8 &1.3 &\textbf{1.2} &1.9 &1.6 \\ \hline CyCADA \cite{hoffman2018cycada} &84.5 &78.6 &80.3 &76.9 &80.1 &2.6 &1.4 &1.3 &1.9 &1.8 \\ \hline SIFA \cite{chen2020unsupervised} &88.0 &\textbf{83.3} &\textbf{80.9} &\textbf{82.6} &\textbf{83.7} &\textbf{1.2} &\textbf{1.0} &1.5 &\textbf{1.6} &\textbf{1.3} \\ \hline \hline \textbf{SFS$^*$} &\textbf{88.3} &73.7 &80.7 &81.6 &81.1 &2.4 &4.1 &3.5 &2.7 &3.2 \\ \hline \end{tabular} } \end{adjustbox} \caption{Segmentation performance comparison for the Abdominal MR $\rightarrow$ CT task.} \label{table:results-abdomen} \vspace{-3mm} \end{table} In Figure~\ref{figure:seg-maps}, we present the improvement in segmentation on CT scans from both datasets. In both cases, the supervised models are able to obtain a near perfect visual similarity to the ground truth segmentation which represent the upper-bound performance. Post-adaptation quality of the segmentation maps becomes much closer to the the supervised regime from a visual perspective. We observe fine details on image borders need more improvement in images $2,5,6,10$. This is in line with the observed ASSD performance. Overall, our approach offers significant gains with respect to the Dice coefficient, which directly measures the segmentation accuracy. The improvement in surface distance is also consistent, however best ASSD performance is observed for \cite{tomar2021self}, a method with joint access to source data. Still, our algorithm has the advantage of also maintaining data confidentiality during adaptation. \subsection{Ablation Studies and Empirical Analysis} We empirically demonstrate why our algorithm works by screening changes in the latent embedding before and after adaptation. To visualize the embeddings, we use UMAP~\cite{mcinnes2020umap} to reduce the high-dimensional embeddings to $2D$. Figures~\ref{figure:mmwhs-latent-features} and ~\ref{figure:abdomen-latent-features} showcase the impact of our algorithm on the latent distribution of the two datasets. In Figure~\ref{figure:mmwhs-latent-features1}, we record the latent embedding of the GMM distribution that is learned on the cardiac MR embeddings. Figure \ref{figure:mmwhs-latent-features2} exemplifies the distribution of the target CT samples before adaptation. We see from Table \ref{table:results-cardiac} that the source-trained model is able to achieve some level of pre-adaptation class separation which is confirmed in Figure \ref{figure:mmwhs-latent-features2}. In Figure \ref{figure:mmwhs-latent-features3} we observe that this overlap is reduced after adaptation. We also observe that the latent embedding of the target CT samples is shifted towards the internal distribution, making the source-trained classifier generalizable. We repeat the same analysis for the organ segmentation dataset, and observe a similar outcome. We conclude that our intuition is confirmed, and the algorithm mitigates domain shift by performing distribution matching in the latent embedding space. \begin{figure}[!htb] \centering \subfigure[GMM samples]{ \includegraphics[width=.2\textwidth]{Figures/mmwhs_gaussian_embedding_multi_class.png} \label{figure:mmwhs-latent-features1} } \subfigure[Pre-adaptation]{ \includegraphics[width=.2\textwidth]{Figures/mmwhs_target_non_adapted_multi_class.png} \label{figure:mmwhs-latent-features2} } \subfigure[Post-adaptation]{ \includegraphics[width=.2\textwidth]{Figures/mmwhs_target_adapted_multi_class.png} \label{figure:mmwhs-latent-features3} } \caption{\small Indirect distribution matching in the embedding space: (a) GMM samples approximating the MMWHS MR latent distribution, (b) CT latent embedding prior to adaptation (c) CT latent embedding post domain alignment. Colors correspond to: \textcolor{orange}{AA}, \textcolor{blue}{LAC}, \textcolor{green}{LVC}, \textcolor{red}{MYO}.} \label{figure:mmwhs-latent-features} \vspace{-3mm} \end{figure} \begin{figure}[!htb] \centering \subfigure[GMM samples]{ \includegraphics[width=.2\textwidth]{Figures/abdomen_gaussian_embedding_class_mixture.png} \label{figure:abdomen-latent-features1} } \subfigure[Pre-adaptation]{ \includegraphics[width=.2\textwidth]{Figures/abdomen_target_non_adapted_class_mixture.png} \label{figure:abdomen-latent-features2} } \subfigure[Post-adaptation]{ \includegraphics[width=.2\textwidth]{Figures/abdomen_target_adapted_class_mixture.png} \label{figure:abdomen-latent-features3} } \caption{\small Indirect distribution matching: (a) GMM samples approximating the CHAOS MR latent distribution, (b) Multi-Atlas CT embedding prior to adaptation (c) Multi-Atlas CT embedding post adaptation. Colors correspond to: \textcolor{red}{liver}, \textcolor{blue}{right kidney}, \textcolor{green}{left kidney}, \textcolor{orange}{spleen}.} \label{figure:abdomen-latent-features} \vspace{-3mm} \end{figure} \begin{figure}[!htb] \centering \subfigure[$\rho=0$]{ \includegraphics[width=.2\textwidth]{Figures/gaussians_rho=0_multi_class.png} \label{figure:gaussians-0} } \subfigure[$\rho=0.8$]{ \includegraphics[width=.2\textwidth]{Figures/gaussians_rho=.8_multi_class.png} \label{figure:gaussians-8} } \subfigure[$\rho=.97$]{ \includegraphics[width=.2\textwidth]{Figures/gaussians_rho=.97_multi_class.png} \label{figure:gaussians-97} } \caption{\small Learnt Gaussian embeddings on the cardiac dataset for different $\rho$.} \label{figure:mmwhs-gaussian-embeddings} \vspace{-3mm} \end{figure} We also investigate the impact of the $\rho$ parameter on our internal distribution. In Figure \ref{figure:mmwhs-gaussian-embeddings} we present the UMAP visualization for the learnt GMM embeddings for three different values of $\rho$. We observe that while some classes will be separated for $\rho=0$, using high confidence samples to learn the GMM will yield higher separability in the internal distribution. We observe our algorithm is robust when $\rho$ is close to $1$, hence our choice of $\rho=.97$. \begin{table}[ht!] \begin{adjustbox}{center} \scalebox{.75}{\small \setlength\tabcolsep{1.5pt} \begin{tabular} {|c| *{5}{|ccc|}} \hline &\multicolumn{3}{|c||}{Ignore} &\multicolumn{3}{|c||}{MYO} &\multicolumn{3}{|c||}{LAC} &\multicolumn{3}{|c||}{LVC} &\multicolumn{3}{|c|}{AA} \\ \hline Ignore &\textbf{97.3} &\textbf{99.3} &\textbf{99.3} &\textbf{1.5} &\textbf{20.3} &\textbf{70.0} &0.2 &80.2 &14.8 &0.9 &6.2 &76.1 &0.2 &43.8 &51.7 \\ \hline MYO &\textbf{13.2} &\textbf{10.4} &\textbf{89.5} &\textbf{81.6} &\textbf{72.2} &\textbf{72.2} &0.1 &52.7 &0.4 &\textbf{5.2} &\textbf{44.6} &\textbf{54.1} &0.0 &0.0 &0.0 \\ \hline LAC &\textbf{15.1} &\textbf{45.4} &\textbf{46.3} &\textbf{2.5} &\textbf{2.6} &\textbf{79.7} &\textbf{76.1} &\textbf{88.4} &\textbf{88.4} &\textbf{5.9} &\textbf{7.4} &\textbf{87.4} &0.4 &5.8 &77.0 \\ \hline LVC &0.6 &67.7 &2.3 &\textbf{16.5} &\textbf{33.4} &\textbf{66.3} &0.2 &83.8 &13.0 &\textbf{82.7} &\textbf{92.4} &\textbf{92.4} &0.0 &93.3 &0.0 \\ \hline AA &\textbf{18.5} &\textbf{7.8} &\textbf{90.9} &0.0 &0.0 &43.7 &\textbf{1.3} &\textbf{5.7} &\textbf{6.2} &0.1 &0.0 &12.9 &\textbf{80.1} &\textbf{91.2} &\textbf{91.2} \\ \hline \end{tabular} } \end{adjustbox} \caption{\small Percentage of shift in pixel labels during adaptation for the cardiac dataset. A cell $(i,j)$ in the table has three values. The first value represents the percentage of pixels labeled $i$ that are labeled $j$ after adaptation. The second value represents the percentage of switching pixels whose true label is $i$ - lower is better. The third value represents the percentage of switching pixels whose true label is $j$ - higher is better. Bolded cells denote label shift where more than $1\%$ of pixels migrate from $i$ to $j$.} \label{table:mmwhs-percentage-migrate} \end{table} \begin{table}[ht!] \begin{adjustbox}{center} \scalebox{.72}{\small \setlength\tabcolsep{1.5pt} \begin{tabular} {|c| *{5}{|ccc|}} \hline &\multicolumn{3}{|c||}{Ignore} &\multicolumn{3}{|c||}{Liver} &\multicolumn{3}{|c||}{R. Kidney} &\multicolumn{3}{|c||}{L. Kidney} &\multicolumn{3}{|c|}{Spleen} \\ \hline Ignore &\textbf{94.6} &\textbf{98.4} &\textbf{98.4} &\textbf{3.0} &\textbf{18.0} &\textbf{81.6} &0.7 &23.5 &74.3 &0.7 &34.9 &62.6 &\textbf{1.0} &\textbf{19.3} &\textbf{80.5} \\ \hline Liver &\textbf{6.6} &\textbf{38.1} &\textbf{60.8} &\textbf{92.6} &\textbf{91.3} &\textbf{91.3} &0.8 &10.4 &55.1 &0.0 &0.0 &0.0 &0.0 &39.0 &10.2 \\ \hline R.Kidney &\textbf{5.0} &\textbf{13.1} &\textbf{86.9} &0.2 &0.0 &76.9 &\textbf{94.8} &\textbf{94.7} &\textbf{94.7} &0.0 &0.0 &0.0 &0.0 &0.0 &0.0 \\ \hline L.Kidney &\textbf{2.2} &\textbf{24.2} &\textbf{75.0} &0.1 &0.0 &0.0 &0.0 &23.7 &0.0 &\textbf{97.5} &\textbf{87.8} &\textbf{87.8} &0.2 &0.0 &7.2 \\ \hline Spleen &\textbf{23.1} &\textbf{20.8} &\textbf{79.2} &0.1 &20.2 &0.0 &0.2 &75.0 &0.0 &0.0 &69.4 &0.0 &\textbf{76.6} &\textbf{78.7} &\textbf{78.7} \\ \hline \end{tabular} } \end{adjustbox} \caption{\small Percentage of shift in pixel labels during adaptation for the abdominal organ dataset. The same methodology as in Table \ref{table:mmwhs-percentage-migrate} is used.} \label{table:abdomen-percentage-migrate} \vspace{-4mm} \end{table} The outcome of pixel label shift is analyzed in Tables \ref{table:mmwhs-percentage-migrate} and \ref{table:abdomen-percentage-migrate}. In Table \ref{table:mmwhs-percentage-migrate} we observe that for the cardiac dataset there exists significant inter-class label transfer, for approximately $20\%$ of pixels, evenly distributed across classes. We see the majority of these shifts leading to an improvement in labeling accuracy, including all shifts where at least $1\%$ of labels migrate, which is in line with our other reported results. These findings also corroborate with our observed embeddings. We can see from Table \ref{table:mmwhs-percentage-migrate} that during adaptation there is significant label migration between \textit{LVC} and \textit{MYO}, and this can be observed in the increased separation between the two classes in Figures \ref{figure:mmwhs-latent-features2} and \ref{figure:mmwhs-latent-features3}. For the abdominal organ dataset we observe significantly less label shift between classes, with most of the activity involving previously labeled pixels being correctly le-labeled as \textit{Ignore} after adaptation, or pixels initially in \textit{Ignore} being correctly le-labeled to their appropriate class. We also perform an ablative experiment for the $\omega$ parameter using the the cardiac dataset in Table \ref{table:results-omega-components}. We observe a large increase in performance when using more than one component per class. However, this benefit decreases as more components are employed. We observe using more than $2$ components increases the Dice score, and more than a $30\%$ drop in ASSD. We conclude a larger number of class components can offer a more expressive approximation of the source distribution, leading to improvements for segmentation accuracy and organ border quality. In our study we choose $\omega=3$ to balance performance and complexity. Full experimental setup and additional results are provided in the appendix. \begin{table}[ht!] \begin{adjustbox}{center} \scalebox{.9}{ \small \setlength\tabcolsep{1.5pt} \begin{tabular} { |c|cccc|c|cccc|c| } \hline &\multicolumn{5}{c|}{Dice} &\multicolumn{5}{c|}{Average Symmetric Surface Distance} \\ \hline $\omega$-SFS &AA &LAC &LVC &MYO &Average &AA &LAC &LVC &MYO &Average \\ \hline \textbf{1-SFS} &86.2 &83.5 &75.4 &70.9 &79.0 &11.1 &5.0 &10.8 &3.6 &9.8 \\ \hline \textbf{3-SFS} &88.0 &83.7 &81.0 &72.5 &81.3 &6.3 &7.2 &4.7 &6.1 &6.1 \\ \hline \textbf{5-SFS} &88.0 &83.8 &81.9 &73.3 &81.7 &6.2 &7.4 &4.8 &5.7 &6.0 \\ \hline \textbf{7-SFS} &86.8 &84.8 &82.0 &73.5 &81.8 &4.8 &7.2 &4.4 &5.6 &5.9 \\ \hline \end{tabular} } \end{adjustbox} \caption{\small Segmentation performance versus $\omega$ for the Cardiac MR $\rightarrow$ CT adaptation task. } \label{table:results-omega-components} \vspace{-3mm} \end{table} \begin{figure*}[ht] \centering \includegraphics[width=.7\textwidth]{Figures/segmentation-maps-new.png} \caption{\small Segmentation maps of CT samples. The first five columns correspond to cardiac images, and last five correspond to abdominal images. From top to bottom: gray-scale CT images, source-only predictions, post-adaptation predictions, supervised predictions on the CT data, ground truth. } \label{figure:seg-maps} \vspace{-8mm} \end{figure*} \section{Conclusion} \label{sec:conclusion} We developed a novel UDA algorithm for semantic segmentation of confidential medical data. Our idea is based on estimating the source internal distribution via a GMM and then using is to align source and target domains indirectly. We provided a empirical analysis to demonstrate why our method is effective and it leads to competitive performance on two real-world datasets when compared to state of the art approaches in medical semantic segmentation that require joint access to source and target data for adaptation.
{'timestamp': '2022-10-10T02:07:47', 'yymm': '2101', 'arxiv_id': '2101.00522', 'language': 'en', 'url': 'https://arxiv.org/abs/2101.00522'}
arxiv
\section{Introduction} Networks have become nearly ubiquitous abstractions for complex systems arising in biological, technical, and social contexts, and many other applications~\cite{newman2010networks}. Mathematically, such networks are represented as graphs in which nodes represent entities and edges relations between such entities. Accordingly, graph-based tools have been employed to study and reveal properties of such network systems. Of particular interest has been the detection of \emph{community structure}, i.e., a grouping of nodes that are more similar to each other according to some criterion than to the rest of the network. There is is no standard definition of community structure~\cite{fortunato2010community,fortunato2016community,schaub2017many} and different notions of community structure exist. We adopt here the common viewpoint of defining communities as densely connected groups of nodes, when compared to the remainder of the network. Detecting such communities has led to insights about the function of proteins~\cite{lewis2010function}, social networks~\cite{traud2012social}, neuroscience~\cite{bassett2017network}, and many other fields~\cite{porter2009communities}. A wide range of community-detection algorithms exists, such as maximum-likelihood estimation of generative network models, spectral methods, and matrix-decomposition approaches~\cite{fortunato2010community,fortunato2016community}. Despite some known limitations, such as an inherent resolution limit~\cite{fortunato2007resolution}, one of the most popular community detection algorithms is modularity maximisation, which seeks to optimize the modularity score proposed in a seminal paper by Newman and Girvan~\cite{newman2004finding}. A current challenge in the analysis of real-world systems is that increased measurements and data availability have been creating a need for algorithms and analysis tools that scale to very large networks. In this context graphons have emerged as one promising non-parametric generative model for the study of large networks (a more detailed introduction to graphons will be given in~\Cref{sec:preliminaries}; briefly, graphons are functions on the unit square originally proposed as continuous limiting objects for dense graph sequences~\cite{lovasz2006limits}). Using the Aldous--Hoover representation theorem~\cite{jacobs2014unified,aldous1981representations,hoover1979relations}, it can be shown that graphons encapsulate a large number of popular existing generative graph models, such as the \emph{Erd\H os--R\'enyi graph}, the \emph{stochastic block model}~\cite{abbe2017community} and its variants, \emph{random dot product graphs}~\cite{athreya2017statistical}, and many further latent variable graph models~\cite{orbanz2014bayesian}. Graphons are thus very flexible probabilistic models that can represent a wide range of network structures. The price for this flexibility, however, is that a graphon-based network model may still be quite complex and not easy to interpret for a practitioner. Hence, when inferring a graphon from empirical data, we might end up trading one large complex network for another complex object, which has arguably impeded the adoption of general graphon models by applied scientists (see~\cref{fig:privacyGraphon}a for an illustration). Indeed, one reason for the interest in community detection is that communities enable a simplified description of a large network, by decomposing the network into modular ``building blocks''. To address this issue in the context of graphons, in this work we develop community detection using a form of modularity optimization for graphons. Our work thereby serves as a first step towards an effective, more interpretable summarization of an inferred graphon describing a complex network. \subsection{Motivation: community detection for graphons} \paragraph{Approximating and simplifying graphons via communities} As outlined above, one main motivation for developing a form of community detection for graphons arises from the need to simplify an empirically obtained graphon further. As graphons encapsulate many popular generative graph models, obtaining a community structure for graphons allows to estimate community structure for those without the need to construct networks from them. While we here concentrate on providing an ``assortative block simplification'' in terms of community structure via modularity maximisation, other approaches are conceivable as well. For instance, we may use low-rank approximations or corresponding spectral embeddings to obtain a simplified description of a graphon. In fact, we may be interested in other types of potential simplifications and analyses of graphons, including further structural decompositions such as core-periphery approximations~\cite{rombach2014core} or centrality measures~\cite{avella2018centrality}. See also~\Cref{ssec:related_work} for a brief overview of the emerging area of graphon analysis for applications. \paragraph{Community detection via continuous optimization} As graphons are objects defined in a continuous domain (functions on the unit square), some techniques from continuous mathematics become applicable for their analysis. This may provide a potential reservoir of new algorithms and analysis tools for networks. While not the main focus of this paper, we will see a simple example of this kind in \Cref{subsubsec:optimisation}, where an analytical solution to the modularity optimization problem on certain graphons is derived. More generally, a fruitful endeavour could be to characterise how classical network algorithms might be seen as discrete approximations of certain problems defined on graphons, which could lead to a deeper understanding of these problems. \paragraph{Privacy-preserving computation}\label{sec:privacy} The protection of sensitive data against unauthorised access is a crucial part of data warehousing and data analysis. Large-scale network data can be such sensitive information. For instance, network data may comprise health records such as brain connectomics~\cite{hagmann2008mapping}, individuals' social contact data such as their Facebook network~\cite{maier2017cover}, or commercially confidential information. Facebook friendships, for example, may be used to expose an individual's sexual orientation~\cite{jernigan2009gaydar}. Graphons are one way to represent such data as an approximation that partially preserves large- and meso-scale features of the data, while providing some anonymity for individuals. Importantly, it has been demonstrated that we can estimate graphons from network data while preserving the privacy of individual nodes~\cite{borgs2015private,borgs2018revealing} By sharing such a privacy preserving graphon, a data collecting entity can thus enable further analysis of such network data. This may lead to valuable insights into the system, while simultaneously preserving the privacy of the involved individuals. \Cref{fig:privacyGraphon}b shows a schematic for such an approach for the case of community detection, in which an external entity is given access to a graphon created from a system graph $G$ in a privacy-preserving way. The external entity can now detect communities and analyse the graphon to gain insights about the system, without compromising the privacy of the individual nodes. This procedure may also be of interest if the particular network analysis to be performed cannot be performed by the data collecting entity, e.g., because of a lack of sufficient computational resources. \begin{figure}[t]{ \centering \includegraphics[width=0.99\textwidth]{./pic/fig1_privacyGraphon_v4.pdf}} \caption{\textbf{Schematic: graphon modularity enables the detection of community structure, which are---similar to networks---a simplified representation of the mesoscale connectivity structure. Furthermore, graphon-based computations enable privacy preserving network analysis.} (a) Classic community detection infers a community structure in a network. Networks can be generated from graphons. The inverse process is the inference of graphons from network data. We establish a community detection for graphons which allows the inference of communities in graphons. (b) For the privacy-preserving network analysis, the data-hosting entity infers a graphon from a network and keeps the node positions $x_i$ private, while sharing the graphon with external entities (or publicly). The external entity can then compute the community structure of the graphon and returns it to the data-hosting entity, which combines it with the node positions $x_i$ to obtain the community membership of each node in the network. During the whole process, the privacy of individual nodes is preserved. } \label{fig:privacyGraphon} \end{figure} \subsection{Contributions} In this paper, we introduce the problem of modularity optimization for graphons. We define a modularity function for graphons and introduce corresponding algorithms to detect community structure in synthetic and empirically estimated graphons. Specifically, we adapt the popular Louvain algorithm for modularity maximization in networks to the context of graphons. Additionally, we discuss a simple continuous optimization variant for modularity we call \emph{sliced modularity optimization}. For selected graphons, this enables us to derive analytical expressions of the optimal community structure. Our characterization of community structure in terms of the modularity of a graphon further provides a necessary and sufficient criterion for graphs to contain no modular structure. Namely, for graphons that have a product form (the graphon operator has rank 1), any partition has modularity zero, i.e., there is no evidence for the presence of communities in terms of the modularity function. As there already exist a number of algorithms for inferring a graphon from network data, we focus mainly on a scenario where the graphon of interest is already given when developing our modularity optimization approach. In~\Cref{subseq:empiricalExamples}, however, we also study graphons inferred from empirically observed and synthetic network data. We report on how the graphon inference steps can impact the results of modularity optimization using numerical simulations. Using stochastic blockmodels, we also illustrate that combining graphon estimation with graphon community detection may improve the performance of modularity-based community detection in comparison with standard, graph-based modularity maximisation. Intuitively, by first fitting a graphon to the network we smooth out random fluctuations in the data, which can impede modularity maximization. At the same time, the full graphon description can be kept for a more refined interrogation of the network structure, e.g., in terms of centrality measures~\cite{avella2018centrality} or for sampling surrogate network data. While in the setting of stochastic blockmodels, there is a planted ground truth partition to compare against, for real networks this is, of course, not the case. We thus investigate numerically for several real networks the extent to which standard modularity optimization (i.e., directly applying modularity maximization on an observed graph) and graphon-based modularity maximization (i.e., first infer a graphon, then find the partition maximising graphon modularity) leads to the same results. For empirical data, we find that the accord between the community structure detected in a network and its estimated graphon depends on the chosen estimation algorithm. Assuming that partitions that optimize modularity in the graph are those we want to detect in the graphon, this is an important aspect if we want to use the graphon based scheme for privacy preserving computation. \newpage \subsection{Related work}\label{ssec:related_work} \paragraph{Graphon-based network analysis} Our work relates to the development of graphon analysis tools and metrics, which is an active field of research. Indeed, centrality measures~\cite{avella2018centrality}, controllability~\cite{gao2017control}, random-walk Laplacians~\cite{petit2019random}, epidemic spreading~\cite{vizuette2020sis}, and subgraph counts~\cite{coulson2016poisson} have all been recently derived for graphons. Graphons have also been proposed as a general tool for encapsulating sensitive information in a node-private way~\cite{borgs2015private,borgs2018revealing}. In light of our previous discussion, the graphon-modularity we present here, may thus also be interpreted as a privacy-preserving method for community detection. \paragraph{Graphon estimation} The estimation of graphons from network data has been studied in a number of publications, e.g.,~\cite{wolfe2013nonparametric,olhede2014network,chatterjee2015matrix}. Approaches include stochastic blockmodel approximations~\cite{airoldi2013stochastic}, neighbourhood-smoothing algorithms~\cite{zhang2017estimating}, or sorting-and-smoothing algorithms~\cite{yang2014nonparametric}. Estimating a general graphon exactly is only possible under certain identifiability conditions~\cite{chan2014consistent}. In practice, however, many approaches estimate a graphon as a \emph{mixture} of stochastic blockmodels, each consisting of many blocks of equal size (also called \emph{network histograms}~\cite{olhede2014network}). \paragraph{Community detection in networks} Many different approaches have been developed to detect communities in networks~\cite{fortunato2010community,fortunato2016community} and modularity-maximisation is one of the most widely-used paradigms. The {\sc Louvain}-algorithm is a fast heuristic to solve the modularity-maximisation problem~\cite{blondel2008fast}. An alternative to community detection is to identify an embedding of discrete nodes in a continuous latent space (e.g.,~\cite{grover2016node2vec}). These latent embeddings may be interpreted in terms of generalized community structure~\cite{newman2015generalized,hoff2002latent}, or indeed graphon estimation~\cite{orbanz2014bayesian}. \subsection{Outline}\label{ssec:outline} The rest of the paper is structured as follows. After briefly reviewing some preliminaries in \cref{sec:preliminaries}, we formally define graphon-modularity in \cref{sec:results}. We then present approaches to optimise the graphon-modularity in \cref{subsubsec:optimisation} and we discuss different synthetic graphons in \cref{subsec:syntheticGraphons}. In~\cref{subseq:sampling} we consider the issue of modularity maximisation on graphon inferred from finite graphs and graphs sampled from latent graphons. We finally perform numerical experiments on the performance of our methods for empirically networks in \cref{subseq:empiricalExamples} and conclude with a discussion in \Cref{sec:discussion}. \section{Preliminaries}\label{sec:preliminaries} \subsection{Graphs} We represent networks mathematically as finite, unweighted, and undirected graphs. A graph is an ordered pair $G=(V,E)$ composed of a set $V$ of nodes (vertices), and a set of edges (links) $E$, where each edge $e\in E$ corresponds to an unordered tuple of two nodes~\cite{newman2010networks,agnarsson2006graph}. We denote the number of nodes in a graph as $N=|V|$ and the number of edges as $M=|E|$. Without loss of generality we will assume that the nodes of the graphs have been labeled by the nonzero integers such that $V = \{1,\ldots, N\}$. Using this labeling we can define the \emph{adjacency matrix} $\mathbf{A}$ of the (labeled) graph as the $N \times N$ matrix with elements $A_{ij}=1$, if $(i,j) \in E$ and $A_{ij}=0$, otherwise. Based on this algebraic representation we can compute the degree $k_i$ of each node $i$ as $k_i=\sum_{j=1}^N A_{ij}$, i.e., $k_i$ is the number of edges incident to node $i$. \subsection{Graphons} Graphons originally emerged in the study of limits of large scale networks~\cite{Lovasz2006,borgs2008convergent,borgs2017graphons,lovasz2012large,glasscock2015graphon}, and have been defined as limits of (dense) graphs for which the number of nodes $N\rightarrow \infty$. A \emph{graphon} is a measurable function $W :[0,1]^{2} \rightarrow[0,1]$, that is symmetric with respect to its arguments such that $W(x, y)=W(y, x)$. An intuitive way to think of a graphon is in terms of the limiting object of a heatmap image (``pixel picture'')~\cite{glasscock2015graphon} of a graph's adjacency matrix as follows. We assume that as the graph size $N\rightarrow \infty$, the heatmap image (the pixel picture) of the adjacency matrix is always spatially scaled to maintain the dimension of the unit square. In the limit there are thus $N\rightarrow \infty$ nodes associated with the unit interval $[0,1]$ and the values $x$ and $y$ in a graphon may thus be interpreted as the indices of the vertices in an infinite graph. While this heuristic explanation provides some intuition, it needs refinement. Observe that for any graph we can permute the node labels and thereby change its representation in terms of the adjacency matrix, while leaving the graph structure unchanged, For a graphon to be a valid limiting objects of graphs rather than of adjacency matrices (i.e., labeled graphs), a graphon can only be defined as a limiting object up to measure preserving bijections of its arguments, i.e., $W(x,y) = W(\pi(x),\pi(y))$, where $\pi: [0,1] \rightarrow [0,1]$ is a measure preserving map. A more precise characterization of the equivalence classes of graphons is provided in~\cite{lovasz2012large,glasscock2015graphon}. Graphons may also be interpreted as nonparametric random graph models, as introduced in \cite{Lovasz2006} under the name $W$-random graphs. We can sample a random graph of size $N$ within this model as follows. First, each node $i\in \{1,\ldots,N\}$ is assigned a latent position $u_i \in [0,1]$ (typically drawn uniformly at random). Second, any pair of nodes $i,j$ is then connected with an edge with probability $\mathbb{P}(A_{ij} = 1) = W(u_i,u_j)$. Similar to graphs we may associate a degree function $k(x)$ to every node $x$ in a graphon via the following Lebesgue integral: \begin{align} k(x) = \int_0^1 W(x,y)\ dy\,. \end{align} Likewise we define the edge density $\mu$ of a graphon as: \begin{align} \mu = \int_{{[0,1]}^2} W(x,y)\ dxdy = \int_0^1 k(x)\ dx\,. \end{align} \subsection{Community-detection in networks} A community is a set of nodes, such that nodes within the same community are more densely connected to each than to nodes in other communities~\cite{fortunato2010community,fortunato2016community,porter2009communities}. We restrict our discussion to \emph{non-overlapping} communities, such that each node belongs to exactly one community. For convenience, we describe the vertex to group assignment by the function $g_V: V \to \{1,2,\dots,c\}$, which maps each node to one of the $c$ communities. Many different heuristic algorithms to find such a function have been developed (see~\cite{schaub2017many,yang2016comparative,rosvall2019different} for reviews). Among the most widely-used heuristics is the so-called \emph{modularity maximisation}. For this, one defines a modularity function \begin{align}\label{eq:modularity} Q(g_V) = \frac{1}{2M} \sum _{i,j=1}^N \left( A_{ij} - P_{ij}\right)\delta[ g_V(i),g_V(j) ] = \frac{1}{2M} \sum _{i,j=1}^N B_{ij} \, \delta[ g_V(i),g_V(j) ]\,, \end{align} which is a quality index for a group assignment function $g_V$ of a network with adjacency matrix $\mathbf{A}$~\cite{newman2006modularity}. Here, the matrix $\mathbf{B}=[B_{ij}]$ is the \emph{modularity matrix} and its entries $B_{ij} = A_{ij}-P_{ij}$ are equal to the entries of the adjacency matrix shifted by a chosen \emph{null model} term $P_{ij}$. This null model term is typically chosen to be the expected connection strength between nodes $i$ and $j$ under a chosen random graph model. The null model thus serves as a baseline to which the actual connections of the adjacency matrix are compared. Since the Kronecker-delta $\delta[ \cdot, \cdot ]$ in \Cref{eq:modularity} is $1$ if its arguments are equal and $0$ otherwise, the above sum only takes into accounts elements of the modularity matrix for which nodes $i$ and $j$ belong to the same community $g_V(i)=g_V(j)$. Accordingly, the modularity of a particular group assignment $g_V$ is equal to the sum (rescaled by $2M$) of the intra-community edges minus the expected weight of intra-community edges. There are numerous choices for the null model term $P_{ij}$. There exist null models for spatially embedded networks~\cite{expert2011uncovering,sarzynska2015null}, null models for networks constructed from correlation models~\cite{macmahon2013community,bazzi2016community}, and for many other situations~\cite{fortunato2016community}. Here we focus on the typically considered Newman--Girvan null model $P_{ij}=k_i k_j /(2M)$~\cite{newman2004finding}, also known as the Chung--Lu model~\cite{Chung2002}, which preserves the expected degree distribution of the graph. With this choice for $P_{ij}$ the modularity $Q$ can be written as: \begin{align}\label{eqn:modularityGen} Q(g_V) = \frac{1}{2M} \sum _{i,j=1}^N \left( A_{ij} - \frac{k_i k_j}{2M} \right)\delta[g_V(i),g_V(j)] \,. \end{align} Clearly there are a number of equivalent group assignments, as the group labels can be permuted without changing the induced partition of the nodes. It is thus the partition of the nodes induced by the group labels that is important for the modularity score, rather than the labels per se. The task of community detection can now be formalized as the following~\emph{modularity-maximisation problem}~\cite{bazzi2016community}: Find a partition of the nodes (respectively a group assignment) that maximises the modularity function $Q$ \begin{align}\label{eq:mod_optimization} \max_{g_V} Q(g_V) = \max_{g_V} \left\{\sum _{i,j=1}^N B_{ij} \, \delta[ g_V(i),g_V(j) ] \right\}\,, \end{align} where $g_V$ is a group assignment function, mapping each node to one community. Note that in the optimization problem \Cref{eq:mod_optimization} the number $c$ of communities is not fixed. The modularity maximization problem may thus be viewed as searching over the set of all possible partitions of the nodes. Since this set becomes extremely large even for moderately sized graphs, \Cref{eq:mod_optimization} is computationally difficult to optimize. In fact, it has been shown that modularity maximisation is an NP-hard problem~\cite{brandes2007modularity}. In practice, the modularity optimization problem is thus solved approximately using (greedy) heuristic procedures, such as the \emph{Louvain algorithm} or the \emph{Leiden algorithm}~\cite{blondel2008fast,genlouvain,traag2019louvain}, which have been shown to yield good empirical performance. \section{A modularity function for graphons} \label{sec:results} In this section, we define the modularity function for graphons, which we will later employ for community detection in graphons. Analogously to the community-detection problem for graphs, the community-detection problem for graphons can be expressed as the identification of a group assignment function \begin{align} g: [0,1] \to \{1,2,\dots,c\}\,, \label{eqn:communityFunction} \end{align} which assigns each node position $x \in [0,1]$ to one of $c$ communities. To find such a community-assignment function, we define a modularity function for graphons. \begin{definition}[Graphon modularity]\label{def:graphonModularity} For a graphon $W(x,y)$, a graphon null model $P(x,y)$ and a group assignment function $g$, we define the \emph{graphon-modularity} as \begin{align} Q(g) = \frac{1}{\mu} \int_0^1 \int_0^1 \underbrace{\big[ W(x,y) - P(x,y)\big] }_{\mathrm{modularity\ surface}\ B(x,y)}\delta(g(x)-g(y))\ dx dy\,, \label{eqn:modularityGraphon} \end{align} where $\delta(\cdot)$ denotes Dirac's delta function, and we have defined the \emph{modularity surface} $B(x,y) = W(x,y) - P(x,y)$ as analog of the modularity matrix for graphons. \end{definition} Analogous to graph case, the graphon modularity function may be interpreted as a measure of the quality of a node partition induced by the group assignment function $g$. Likewise, the modularity surface $B(x,y)$ indicates how well a graphon $W(x,y)$ at location $(x,y)$ is connected compared to the null model term $P(x,y)$. As for graphs, different choices for the \emph{null model} $P(x,y)$ may be sensible. For simplicity we here restrict the discussion again to a Newman--Girvan-type null model: \begin{align} P(x,y) = \frac{1}{\mu} k(x)k(y)\,. \end{align} Note that since graphs generated for sufficiently smooth graphons~\cite{lovasz2006limits,avella2018centrality} will converge to graphons in the limit, the definition of the modularity surface~\cref{def:graphonModularity}, precisely corresponds to the (scaled) limiting object of the modularity matrix. \begin{proof}(Sketch) It can be shown that the normalized degree of node $i$ converges as $N\rightarrow \infty$~\cite{avella2018centrality} and accordingly the degree density of the graph will converge to the graphon density $\mu$. This implies that the null model term will be well defined in the limit. Since furthermore the (scaled) adjacency matrix $\mathbf{A}/N$ will converge to the graphon $W$, both terms that define the modularity surface converge and are well defined. \end{proof} Given a group assignment $g(x)$, we further define the (relative) size $S_{i} \in (0,1]$ of a community $c_i$ as \begin{align} S_{i} = \int_0^1 \delta (g(x),c) \ dx\,. \end{align} The maximal size $S_{i}$ of any community equals one, which indicates that there exists a single group consisting of all nodes. Analogously to graphs, we can now detect communities in graphons by finding a function $g$ that maximises the graphon modularity \cref{eqn:modularityGraphon}. \begin{definition}[Modularity-maximisation problem for graphons]\label{def:graphonModularityMaximisation} Given a non-empty graphon $W(x,y)$ and a graphon null model $P(x,y)$ that define the modularity surface ${B(x,y)=W(x,y)-P(x,y)}$, the \emph{modularity-maximisation problem} is: \begin{align} \max_{g(x)} & \int_0^1 \int_0^1 B(x,y)\delta(g(x),g(y))\ dxdy\,, \end{align} where $g$ is a group assignment function such that $S_{i} > 0$ for all communities $c_i$, i.e., each community has a nonzero measure. \end{definition} \begin{remark}[Measure zero sets and $L_2$ equivalence] Recall how a graphon can only be defined meaningfully up to measure preserving transformations. The same is true, \emph{mutatis mutandis}, for the group assignment function $g$. Indeed, from the above \cref{def:graphonModularity} of graphon modularity, it should be clear that a group assignment function can only be meaningfully defined up to $L_2$ equivalence. Specifically, let $L_2([0,1])$ denote the Hilbert space of functions $f:[0,1]\rightarrow \mathbb{R}$ with inner product $\langle f_1, f_2\rangle = \int_0^1f_1(x)f_2(x)dx$ and norm $\|f_1\|=\sqrt{\langle f_1,f_1\rangle}$. The elements of $L_2([0,1])$ are the equivalence classes of integrable functions that differ only on measure zero sets, i.e., we identify two function $f_1\equiv f_2$ with each other if $\|f_1-f_2\|=0$. For instance, changing the group assignment value $g(x)$ for any single $x\in [0,1]$ will not alter the modularity $Q(g)$ or the size of the communities $S_i$. This measure preserving change of $g$ leads to a non-identfiability of the precise function $g$ in the optimization of graphon modularity. However, analogous to the possibility of permuting the group labels, this non-identifiability does not lead to practical problems, as in practice we are only concerned with group assignment functions up to $L_2$ equivalence. Similarly, we only consider communities with nonzero measure, i.e, we will require that $S_{i}>0$ for all $c_i$, as specified in \cref{def:graphonModularityMaximisation}. \end{remark} As for modularity optimization for graphs, finding an optimal solution for the graphon modularity optimization problem is only possible for special cases. In \Cref{subsubsec:optimisation}, we thus explore two procedures to find either analytical expressions of the optimal community structure, or approximate solutions via numerical algorithms. \section{Optimising graphon-modularity}\label{subsubsec:optimisation} Here we explore two approaches to identify a maximum-modularity partition for graphons (see \Cref{fig:graphonOptimisation} for schematic representations). The first approach is to discretise the modularity surface $B(x,y)$ (see \Cref{def:graphonModularity}) and use a generalised Louvain algorithm ({\sc GenLouvain}) to find a group assignment function $g$. The second approach is (semi-)analytical and works if we can constrain the set of group assignment function $g$ to be monotonically increasing, which we can do for certain synthetic graphons. In this case we can find the exact maxima of modularity. We will show in \Cref{subsec:syntheticGraphons} that for selected synthetic graphons both methods return essentially identical results, providing some further validation for the Louvain heuristic. \subsection{Maximisation of graphon modularity via discretization} We use the {\sc GenLouvain} algorithm~\cite{genlouvain} on a piecewise constant approximation of $W(x,y)$, as illustrated in \Cref{fig:graphonOptimisation}, to heuristically optimize graphon modularity. {\sc GenLouvain} is a variant of the fast \emph{Louvain}-algorithm~\cite{blondel2008fast}, which was originally designed for standard modularity optimization on simple graphs. To apply the \textsc{GenLouvain} algorithm, we first need to discretize the graphon $W(x,y)$ appropriately by trading off two aspects. First, we need to chose a fine enough grid to capture the variation of the graphon $W(x,y)$ in $x$ and $y$ direction. Second, we would like to choose an as coarse as possible grid, to limit the computational costs of the optimization performed via {\sc GenLouvain}. In the following we approximate $W(x,y)$ using a uniformly spaced grid of size $2000\times 2000$ unless otherwise stated. For this grid size, detecting community structure in discretised graphons is possible with commodity hardware in a few minutes. We observe that this choice of the discretization for $W(x,y)$ is fine enough for all the problems considered in this paper. Increasing the resolution of the grid further has essentially no effect for the results, in practice. We remark, that more elaborate discretization schemes are conceivable and might result in computational gains. For instance, one could employ multigrid discretization schemes to obtain a better approximation of local features of the modularity surface, without incurring a large extra computational cost~(for a review of multigrid schemes see~\cite{stuben2001review}). \begin{figure}[t] \begin{center} \includegraphics[width=0.49\textwidth]{./pic/fig2_optimisationSchematic.pdf} \end{center} \caption{\textbf{Optimizing graphon modularity.} We discuss two procedures to maximise graphon-modularity. (Left panel) We discretise the graphon into intervals $[x,x +\Delta x]$ and apply a Louvain algorithm to optimise the modularity function for the resulting matrix. (Right panel) We restrict the modules to be continuous intervals (in this example $[0,x_1]$ and $(x_1,1]$). We optimise the modularity by continuously varying the border $x_1$ between the communities. In this schematic, there exist only two communities, although in general there can be any number of communities.} \label{fig:graphonOptimisation} \end{figure} \subsection{Maximisation of graphon modularity via continuous optimisation} We now consider a setup in which we can analytically establish the optimal partitions of a graphon in terms of the modularity function. This provides us with a way to validate the results we obtain from the discretization based graphon-modularity optimization outlined in the previous section. Moreover, it highlights that (within certain situations) tools from continuous optimization can be employed to analyse modularity maximizing partitions of graphons. To this end, we restrict the possible group assignment functions $g(x)$ to be piecewise constant on $c$ intervals: \begin{equation} g(x) = \begin{cases} 1 \quad \text{if} \quad x\in[0,x_1)\\ 2 \quad \text{if} \quad x\in[0,x_1)\\ \vdots \\ c \quad \text{if} \quad x\in[x_{c-1},1]\\ \end{cases} \end{equation} For certain synthetic graphons the partitions can be assumed to be of such a form. If the group assignment function $g(x)$ is of such a form, we can rewrite the graphon modularity function as: \begin{align} Q(g) = \frac{1}{\mu} &\sum_{i=1}^c L(x_{i-1},x_i) \,,\ \text{with} \\ L(a,b) =& \int_{a}^{b} \int_{a}^{b} B(x,y) dx dy = 2\int_{a}^{b} \int_{a}^{x} B(x,y)dxdy\,, \end{align} where the last equality follows from the symmetry ($B(x,y)=B(y,x)$) of the modularity surface. We call the function $L(a,b)$ a \emph{modularity slice} as the modularity function may be seen as a simple linear sum of these slices. Note that within the above formulation, we have thus restricted the (combinatorial) optimization problem to a much simpler optimization with $c-1$ degrees of freedom, namely finding the end-points of the first $c-1$ intervals over which $g(x)$ is constant. For instance, if we know that there are $c=3$ communities we obtain: \begin{align} Q(g) \propto L(0,x_1) + L(x_1,x_2) + L(x_2,1)\,, \end{align} which has only $x_1$ and $x_2$ as free variables. This continuous optimisation problem can in many cases be solved analytically. When this is not directly possible, however, we can optimise it using standard optimisation procedures, such as the Nelder--Mead method~\cite{nelder1965simplex}. In the following, we will use the sliced-modularity approach to prove the maximum-modularity partition for a synthetic graphon. In the appendix, we discuss a generalised sliced-modularity approach, which allows the detection of communities in settings when less is known about the location of communities on the line. \section{Modularity optimization for synthetic graphons}\label{subsec:syntheticGraphons} In this section we explore the detection of community structure for different given synthetic graphons, and show how the obtained group assignments provide some simplified description block description of the graphons. \subsection{Graphons with zero modularity surface}\label{subsec:withoutCommunity} Maximising the graphon-modularity returns a group assignment function $g(x)$ with the highest graphon-modularity $Q$. If the modularity surface of the graphon is $B(x,y)=0$, however, all functions $g(x)$ have the same modularity $Q=0$. In this case, it is not possible to find a partition that has a higher modularity than any other. Accordingly, we will say that such a graphon does not exhibit a community structure. Note that in contrast to the graph case, such a degenerate situation is possible even if the graphon itself is non-zero and well defined. \begin{proposition} Graphons of the form $W(x,y)=f(x)f(y)$ do not have community structure. \label{theorem:multiplicative} \end{proposition} \begin{proof} Let $W(x)$ be a graphon of the form $W(x,y)=f(x)f(y)$. The degree function is thus $k(x) = f(x) \int_0^1 f(y) dy$, the edge density is $\mu = \int_0^1 f(y) dy\int_0^1 f(x) dx$ and the null model term can be computed as $P(x,y) = f(x)f(y)$. Therefore the modularity surface is $B(x,y)=0$ and it follows that the modularity function is zero for all partitions. \end{proof} An example of a graphon without community structure is the graphon associated to the Erd\H os--R\'enyi (ER) graph model $G(n,p)$, which can be represented as a graphon $W(x,y)=p$ with a constant connection probability $p \in [0,1]$. Indeed the ER graphon belongs to the class of multiplicative graphons of~\Cref{theorem:multiplicative} as $W(x,y)=\sqrt{p}\sqrt{p} = f(x)f(y)$ and thus has no community structure. In fact, the reverse is also true and all non-empty graphons without community structure are multiplicative (up to $L_2$ equivalence). \begin{proposition} Let $W(x,y)$ be a non-empty graphon with vanishing modularity surface $B(x,y)=0$. Then, the graphon is of the form $W(x,y)=f(x)f(y)$. \label{theorem:zero} \end{proposition} \begin{proof} As $W(x,y)$ and $P(x,y)$ are positive, if follows from $B(x,y)=0$ that $W(x,y)\equiv P(x,y)$ (in the sense of $L_2$ equivalence), where the null model term is given by $P(x,y)=k(x)k(y)/\mu$. We can therefore write $W(x,y)=f(x)f(y)$ with $f(x)=k(x)/\sqrt{\mu}$. \end{proof} Note that this implies that the linear (graphon) integral operator, i.e., the integral operator whose kernel is given by the graphon has rank 1 \subsection{A core-periphery model: the $\lambda$-graphon}\label{subseq:lambdaGraphon} \begin{figure}[b!] {\centering \includegraphics[width=0.99\textwidth]{./pic/fig3_lambdaGraphon.pdf} \caption{\textbf{Graphon modulurity maximization for a graphon with core-periphery structure.} In a core-periphery $\lambda$-graphon (see text) with $\lambda = 0.2$ we detect two communities. The panels show the graphon $W(x,y)$, the degree $k(x)$, the modularity surface $B(x,y)$, and the community structure $g(x)$ returned by the GenLouvain algorithm, respectively. The sliced-modularity approach returns similar results for the community structure.} \label{fig:lambdaGraphon}} \end{figure} We consider a graphon with core-periphery structure $W(x,y) = (1-\lambda)xy + \lambda$, modulated by a parameter $\lambda \in [0,1]$. We will call this particular graphon $W(x,y)$ the $\lambda$-graphon in the following. Note that the $\lambda$-graphon may be seen as a convex mixture of (a) a flat connectivity profile with probability $\lambda$, corresponding to random ER-like connectivity, and (b) a coordinate dependent connectivity profile $xy$, which may be interpreted in terms of a continuous core-periphery structure. Indeed, the larger the coordinate of the node, the higher its connectivity, as computing the degree function of the $\lambda$-graphon confirms: \begin{equation*} k(x) = \lambda + (1-\lambda)x/2. \end{equation*} The edge density of the $\lambda$-graphon is $\mu = (1-\lambda)/4 + \lambda$ and, accordingly, the modularity surface is \begin{equation*} B(x,y)=(1-\lambda)\lambda \frac{(2x-1)(2y -1)}{(1+3\lambda)} \end{equation*} Note that when $\lambda=0$ and $\lambda=1$ we have $B(x,y) =0$ and we cannot detect communities for these cases as discussed above. For $\lambda=1$, the $\lambda$-graphon becomes the constant graphon $W(x,y)=1$, which clearly does not have a community structure as all nodes are equivalent. For $\lambda =0$ we obtain $W(x,y)=xy$, which does not have a community structure because of its multiplicative structure. Numerically optimising the graphon modularity with the {\sc GenLouvain}-approach for $\lambda=0$ and $\lambda=1$ yields indeed a single community with $Q=0$. Let us now focus on scenarios for which $\lambda \in (0,1)$. In Fig.~\ref{fig:lambdaGraphon}, we show the degree $k(x)$, the modularity surface $B(x,y)$, and the detected community structure $g(x)$ for $\lambda=0.2$ as an example. Optimising modularity with the {\sc GenLouvain}-approach for general $\lambda \in (0,1)$, we always obtain a partition into two communities that split the unit interval in half at $x=1/2$. To confirm this numerical results let us use the sliced-modularity approach to analytically compute the optimal community structure for two continuous groups. First we compute the modularity slice: \begin{align} L(a,b) = \frac{(a-b)^2 (-1+a+b)^2 (1- \lambda)\lambda }{3\lambda + 1}\,. \end{align} To obtain the optimal border $x_1$ between the two communities we maximise \begin{align} L(0,x_1;\lambda)+L(x_1,1;\lambda) = \frac{2(1-\lambda)\lambda}{1+3\lambda} (x_1-1)^2 x_1^2 = \kappa(x_1-1)^2 x_1^2 \,. \label{eqn:lambdaL} \end{align} As $\lambda \in (0,1)$, the factor $\kappa =2(1-\lambda)\lambda/(1+3\lambda)$ is greater than zero, and maximising the modularity is therefore equivalent to maximising $h(x) = (x_1-1)^2 x_1^2$. The local extrema of $h(x_1)$ with $dh/dx_1=0$ are $0$, $1/2$, and $1$. Evaluating the second derivative reveals that $0$ and $1$ are local minima and that $x=1/2$ is a maximum. For $\lambda\in (0,1)$ the optimal modular structure thus indeed consists of two equal-sized communities with the border at $x_1=1/2$, confirming the numerical results from the \textsc{GenLouvain} approach. Using the above information about the optimal split for $\lambda \in (0,1)$, we can also calculate the maximum modularity as a function of the $\lambda$ parameter: \begin{align} Q_{\text{max}}(\lambda) = \frac{L(0,1/2;\lambda)+L(1/2,1;\lambda)}{\mu(\lambda)} = \frac{\lambda (1-\lambda)}{2(3\lambda +1)^2}\,, \end{align} which has its maximum $Q_{\text{max}}=1/32=0.03125$ at $\lambda =1/5$. The example shown in Fig.~\ref{fig:lambdaGraphon} is therefore the $\lambda$-graphon with the largest possible modularity score. Note that as $\lim _{\lambda \to 0} Q_{\text{max}}(\lambda) = 0$ and $\lim _{\lambda \to 1} Q_{\text{max}}(\lambda) = 0$, the maximum modularity $Q_{\text{max}}$ vanishes when the $\lambda$-graphons approach the boundary cases without community structure. In this case the optimal value of modularity is thus continuous in $\lambda$. \subsection{A uniform attachment model: the $\max$ graphon}\label{subseq:maxGraphon} \begin{figure}[b!] {\centering \includegraphics[width=0.99\textwidth]{./pic/fig4_maxGraphon.pdf}} \caption{\textbf{Graphon modularity maximisation for a graphon with uniform attachment.} For the max graphon discussed in the text, we obtain a partition consisting of three communities. The panels show the graphon $W(x,y)$, the degree $k(x)$, the modularity surface $B(x,y)$, and the community structure $g(x)$ returned by the GenLouvain algorithm, respectively. The sliced-modularity apporach returns similar results for the community structure.} \label{fig:Maxgraphon} \end{figure} Synthetic models for growing networks have been widely used to model phenomena observed in real-world networks, such as long-tailed degree distributions~\cite{albert2002statistical}. These models typically consist of an iterative procedure that adds nodes and edges sequentially until a certain number of nodes is reached. Some graphons can be seen as a limit of such a network growing process~\cite{borgs2011limits}. The sequence of \emph{growing uniform attachment} graphs we discuss next is a particular example of such a growth process that exhibits such a convergence. We start with a graph $G_1$ consisting of a single node and no edges. For $n\geq2$, we then construct $G_n$ from $G_{n-1}$ by adding a new vertex and adding every possible not already present edge in the network with probability $1/n$. It can be shown~\cite{borgs2011limits} that this graph sequence almost surely converges to the \emph{max graphon} displayed in Fig.~\ref{fig:Maxgraphon}, which is defined as \begin{align} W(x,y) &= 1- \max(x,y) \end{align} Computing the degree function of the $\max$ graphon as $k(x) = (1-x^2)/2$, we obtain a modularity surface of \begin{align} B(x,y) = 1- \max(x,y) - \frac{3}{4}(x^2-1)(y^2-1)\,. \end{align} Optimising this function with the {\sc GenLouvain} approach yields a partition of the unit interval into the sets $[0,0.3730)$, $[0.3730,0.4605)$, and $[0.4605,1]$, corresponding to a medium sized community that consists of the highest-degree nodes, a small community consisting of medium degree nodes, and a large community consisting of all small degree nodes. As we can see form the modularity surface in \Cref{fig:Maxgraphon}, these three sets provide indeed an approximate block-based description of the nodes within the graphon and may facilitate an easier interpretation of this model. To confirm these results we again resort to our sliced-modularity approach using an Ansatz with three communities. We obtain a modularity slice $L(a,b)$ that is a polynomial of order six in $a$ and $b$. To estimate the maxima of the sixth order polynomial in terms of the partition endpoints $x_1, x_2$ we use Mathematica's Brent--Dekker method~\cite{brent1971algorithm} and obtain $x_1 \approx 0.369$ and $x_2 \approx 0.463$ (see online material). With higher computational effort, it is also possible to obtain the optimal community borders with the sliced-modularity approach for a larger number $c$ of communities. For $c=5$, for example, we obtain $x_1 = 0$, $x_2 \approx 0.369$, $x_3 \approx 0.463$, and $x_4 = 1$, which represents a community structure with two communities of vanishing size, yielding \emph{de facto}, the same community structure with $c=3$. These results are well in line with the values obtained with {\sc GenLouvain}, given that the discretisation of the graphon for the {\sc GenLouvain} approach and possible numerical inaccuracies encountered when finding the maxima using the sliced-modularity method. \section{Modularity of graphs sampled from unstructured and structured graphons}\label{subseq:sampling} \subsection{Modularity of graphs sampled from graphons without structure}\label{subsec:samplingER} In a number of benchmark tests for community detection on graphs the characterisation of a graphon with no community structure in~\Cref{subsec:withoutCommunity} is implicitly assumed to hold also for finite graphs sampled from a corresponding graphon model. For instance, in \cite{fortunato2016community,Lancichinetti2009}, it is advocated that for graphs sampled from an ER model, a community detection algorithm should return a null result that indicates that there are no communities present. While the idea is intuitively appealing, there are some issues when adopting this viewpoint in the finite regime. In particular, a finite network sampled from a sparse ER model may not necessarily be representative of the underlying ER model, i.e., the random samples may not be concentrated around the expected featureless ER graphon~\cite{le2017concentration,joseph2016impact}. This is in accordance with earlier results that state that samples drawn from an ER model can have a weak community structure arising from statistical fluctuations~\cite{guimera2004modularity}. In particular in~\cite{guimera2004modularity}, the authors showed that for large networks the maximum modularity approaches $Q \sim (pN)^{-2/3}$ (for a constant $p$, independent on $N$). Therefore the modularity vanishes for $N\to \infty$, which matches the infinite size limit that graphons represent. \subsection{Modularity of graphs sampled from structured graphons}\label{subsec:pp} \subsubsection{The planted partition model} The planted partition (PP) model is a prominent random graph model with group structure, which can be described as a graphon. For a $c$-block PP model each node $x$ belongs to exactly one group $g^{\star}(x)$, where $g^{\star}: [0,1] \rightarrow \{1,\ldots,c\}$ is the group assignment function. The $c$-block PPM graphon can then be written as: \begin{align} W(x,y) &= \begin{cases} p_{\mathrm{in}} & \mathrm{if}\ g^{\star}(x) = g^{\star}(y) \,,\\ p_{\mathrm{ex}} & \mathrm{otherwise}, \end{cases} \end{align} which means that nodes have an internal connection probability $p_{\mathrm{in}} \in [0,1]$ if they are in the same group, and an external connection probability $p_{\mathrm{ex}} \in [0,1]$ otherwise. To obtain an assortative community structure we assume $p_{\mathrm{ex}}<p_{\mathrm{in}}$. \begin{figure}[t] {\centering \includegraphics[width=0.99\textwidth]{./pic/fig5_plantedPartition.pdf} \caption{\textbf{Graphon modularity maximization for planted partition graphons.} In a planted partition graphon with $c=3$ blocks we recover the planted community structure. Each community has an internal connection probability of $p_{\mathrm{in}}=0.2$ and the connection probability between communities is $p_{\mathrm{ex}}=0.01$. The degree function is constant $k(x) = 1/3\times 0.2 + 2/3\times 0.01 \approx 0.0734$. The modularity surface $B(x,y)$ is positive in the communities and negative between communities. The community function $g(x)$ indicates that we correctly identify the three planted communities.} } \label{fig:SBMgraphonK3} \end{figure} For the PP graphon, we can compute the degree as: \begin{align} k_{\mathrm{PP}}(x) &= \frac{(p_{\mathrm{in}} + (c-1)p_{\mathrm{ex}}) }{c} \,, \end{align} and the total connectivity: \begin{align} \mu_{\mathrm{PP}} &= \frac{(p_{\mathrm{in}} + (c-1)p_{\mathrm{ex}}) }{c}\,, \end{align} Accordingly, the modularity surface is \begin{align} B_{\mathrm{PP}}(x,y) &= \begin{cases} \frac{c-1}{c} (p_{\mathrm{in}} - p_{\mathrm{ex}}) & \text{if } g^{\star}(x)=g^{\star}(y),\\ \frac{(p_{\mathrm{ex}} - p_{\mathrm{in}})}{c} & \mathrm{otherwise}. \end{cases} \end{align} which is positive for nodes belonging to the same block and negative across blocks. Accordingly, we maximise the graphon-modularity if we choose the community structure $g(x)$ equal to the planted one $g^{\star}(x)$ and obtain a maximum modularity of \begin{align} Q_{\text{max}} &= \frac{1}{\mu} \frac{c-1}{c^2}(p_{\mathrm{in}} - p_{\mathrm{ex}} ) = \frac{c-1}{c} \frac{p_{\mathrm{in}} - p_{\mathrm{ex}}}{ p_{\mathrm{in}} + (c-1)p_{\mathrm{ex}} }\,, \end{align} Thus for all $c>1$ and $p_{\mathrm{ex}}<p_{\mathrm{in}}$, the graphon-modularity is positive as desired for a model with community structure. In Fif.~\ref{fig:SBMgraphonK3}, we show an example PP graphon, for which we indeed perfectly recover the planted partition $g^{\star}(x)$. \subsubsection{Modularity of graphs sampled from planted partition models and inferred graphons} We now consider the numerical performance of modularity optimization for a PP model with $c=3$ groups in three scenarios: (i) if we had access to the correct graphon, (ii) for a graph sampled from such a graphon, and (iii) for a graphon inferred from such a sampled graphon. We start by considering the simple baseline case, in which we have access to an appropriately discretized version of the true graphon. In this case, we can simply use the {\sc GenLouvain} algorithm, or any other approach and recover the $c=3$ planted communities, as long as $p_{\mathrm{ex}}<p_{\mathrm{in}}$ (results not shown). \begin{figure}[t] {\centering \includegraphics[width=0.99\textwidth]{./pic/fig6_graphonSamplingEstimation.pdf} \caption{\textbf{Numerical comparison of graphon modularity and graph-based modularity optimization.} We measure the alignment between community structure in graphs sampled from the graphon with the planted partition (dotted lines), and graphons estimated from the sampled graphs (solid lines) as the adjusted mutual information (AMI). The larger the size $N$ of the sampled networks, the better is the recovery of the planted partition. In all cases, there exists a regime for which the graphon estimation improves the detected community structure. Here we fix $p_\text{in}=0.05$.} \label{fig:SBMgraphonPvary} } \end{figure} Next we consider modularity optimization for graphs sampled from such such a planted partition model graphon, and for the graphons inferred from such samples. We construct planted partition graphons with $c=3$ planted partitions and internal connection probability $p_{\mathrm{in}}=0.05$, with varying external link probability $p_{\mathrm{ex}} \in [0,0.05]$. Then we sample networks of varying sizes $N \in \{1000, 2000, 10000\}$ from this graphon as follows. First, we create $N$ nodes with associated uniformly spaced coordinates in $[0,1]$, such that $x_i= (i-1)/(N-1)$ is the position of node $i$. We then draw edges between all (unordered) pairs $(x_i,x_j)$ of nodes with probability $W(x_i,x_j)$ to obtain the symmetric adjacency matrix of an undirected graph. Finally, we estimate the graphon from the sampled graph with a matrix-completion approach, which we choose because it is fast and does not have free hyperparameters~\cite{keshavan2010matrix}. We use {\sc GenLouvain} to optimise the modularity function of the sampled graphs and the inferred graphons and compare the detected partition with the planted one by computing the \emph{adjusted mutual information} (AMI)~\cite{vinh2010information}. A maximal value of AMI$=1$ indicates that two partitions are identical and a minimal value of AMI$=0$ indicates that two partitions do not provide more information about each other than expected by random chance. The results of our numerical comparison are shown in Fig.~\ref{fig:SBMgraphonPvary}. The dotted lines correspond to the results of modularity optimization on the sampled graphs, the solid lines show the results when we first infer a graphon and second apply modularity optimization on the inferred graphon. We find that for modularity optimization both on the sampled graph as well as the inferred graphon, for small external connection probabilities $p_{\mathrm{ex}}$ the AMI is one and thus we recover the planted partitions perfectly. For larger connection probabilities $p_{\mathrm{ex}}$ the AMI decreases, which indicates that we do not fully recover the planted partitions. We further see that if we increase the number of sampled nodes, the results obtained from modularity optimization improve, and we are able to find the correct partition even for larger values of $p_\text{ex}$ (i.e., for smaller differences $p_\text{in} - p_\text{ex}$), corresponding to the fact that the sampled graphs converge to the graphon, for which the detection of the planted structures is always possible if $p_\text{in}> p_\text{ex}$. Indeed, it is known that for dense graphs described by graphons the accurate detection of planted communities is a problem that can be efficiently solved by many algorithms, in contrast to the case of sparse graphs for which a detectability limit exists~\cite{decelle2011inference}. We find that the AMI curves for the estimated graphons follow a behaviour similar to the AMI curves for modularity optimization on the the sampled graphs. Interestingly, however, for all considered graph sizes $N$ there exists a range of connection probabilities $p_{\mathrm{ex}}$ for which modularity optimization on the estimated graphon yields a better performance. This indicates that graphon estimation can improve the performance of modularity optimization for recovering planted partitions in graphs by smoothing fluctuations in the observed connectivity structure. \section{Modularity optimization and community structure for graphons estimated from empirical data}\label{subseq:empiricalExamples} Real-world network data can be large but is always of finite size. We thus cannot observe graphons directly but rather finite graphs consisting of discrete nodes and edges. Accordingly, we need to estimate graphons from finite observations. Many different methods have been proposed for this estimation task~\cite{wolfe2013nonparametric,olhede2014network,zhang2017estimating,chan2014consistent}. Most of these graphon estimators are consistent, i.e., the estimation error vanishes as the number of nodes $N \rightarrow \infty$. However, different graphon estimators may estimate different graphons for the same finite graph, and identifying the most appropriate estimator for a certain data set is an open research question~\cite{gao2015rate}. In the following, we employ three prototypical methods for graphon estimation from empirically observed graphs: (i) a \emph{sorting-and-smoothing} algorithm, which is a consistent histogram estimator~\cite{chan2014consistent}, (ii) a matrix-completion approach~\cite{keshavan2010matrix}, and (iii) \emph{universal singular value thresholding} (USVT)~\cite{chatterjee2015matrix}. We choose these three methods because they do not have hyperparameters that have to be chosen by the user. Using the estimated graphons we then employ modularity maximisation using the {\sc GenLouvain} approach to obtain a simplified picture of the graphons in terms of community structure. We find that the graphon-estimation approach can have a strong influence on the community structure detected by graphon-modularity maximisation. To quantify the extent to which the community structure $g_{\mathrm{graphon}}(x)$ obtained from the estimated graphon resembles the community structure $g_{\mathrm{network}}(x)$ obtained from a graph itself, we compute the AMI between both for six empirical networks (see Table~\ref{tab:normalisedInformation}). It is important to note that there is no ground truth in this setting~\cite{peel2017ground}, i.e., the communities obtained from direct modularity optimization on the observed graph are but one possible clustering of the network, similar to the clustering obtained from the graphon. In fact in some cases one may even argue that the graphon modularity results are less prone to random fluctuations as the estimation strategies involved typically involve some kind of smoothing procedure (as observed for the PP graphon in \cref{subsec:pp}). We find, that for all networks, the choice of the graphon estimator has a strong influence on the community structure that we detect in the graphon. The sort-and-smooth estimator leads to a community structure that differs strongly from the one detected in the network itself, as indicated by small AMI values. Modularity maximization using an inferred graphon based on a matrix-completion approach yields partitions that are commensurate with the partitions found from direct modularity optimization on the graph ($\text{AMI}>0.4$) for all data sets. The ``best results'' is this sense are provided by the USVT estimator. Interestingly, for the data sets analysed here, the USVT estimator always yields the highest AMI if it does not give a zero result. This zero AMI score occurs if the USVT estimator returns a constant graphon $W(x,y)=\text{const.}$, which means all partitions will have the same modularity score of $0$ (and thus no partition will be detected). This suggests that the USVT algorithm is a good `first choice' for the estimation step of graphons for modularity optimization. In the following we concentrate on the matrix completion and the USVT estimators as the sort-and-smooth approach yields results that are largely incomparable to the other methods. Our results indicate that if there is strong community structure, direct modularity optimization and graphon-based modularity optimization yield the same results. For instance, in the US-senate voting network~\cite{waugh2009party}, which has a strong community structure, we find that the modularity maximisation for graphon and network yield virtually the same partition. In cases when the community structure in the graphon differs from the one in the network, we usually detect less communities in the graphon because the graphon-estimation smoothes some of the connectivity signal. For the Facebook network the AMI is $0.45$, which means that more than half of the information of the graph partition can be revealed by clustering the graphon. For the brain connectivity network~\cite{hagmann2008mapping}, which has shown to have a modular structure that enables the parallel processing of the information~\cite{klimm2014individual,klimm2014resolving}, we find intermediate AMI of $0.54$. Our analysis indicates, that a privacy-preserving community detection via graphon modularity is indeed possible, but extent to which we loose information in comparison to the graph partition depends on the data set and the type of graphon-estimation algorithm. We postpone a more detailed investigation of this behaviour for future work. \begin{table}[t] \centering \begin{small} \begin{tabular}{c| c | c || c c c} data set & reference & $N$ & \multicolumn{3}{c}{AMI($g_{\mathrm{network}}$, $g_{\mathrm{graphon}}$)}\\ & & & Matrix completion & USVT & Sort-and-smooth \\ \hline Zachary Karate Club & \cite{zachary1977information} & 34 & ${\mathbf{0.43}}$ &\~0 & 0.09 \\ Senate voting & \cite{waugh2009party} & 102 & 0.9286 & ${\mathbf{1}}$ & 0.01 \\ Facebook network & \cite{maier2017cover} & 329 & ${\mathbf{0.45}}$ & 0 & 0 \\ Brain connectivity & \cite{hagmann2008mapping} & 998 & 0.48 & ${\mathbf{0.54}}$ & 0.14 \\ Political blog & \cite{adamic2005political} & 1224 & 0.60 & ${\mathbf{0.79}}$ & 0.17 \\ Protein complex & \cite{klimm2020hypergraphs} & 8243 & 0.44 & ${\mathbf{0.60}}$ & 0.04\\ \end{tabular} \vspace{0.2cm} \end{small} \caption{The agreement between partitions obtained from clustering a graph directly and clustering a graphon estimated from the graph depends strongly on the data set and the used estimation algorithm. We show the adjusted mutual information (AMI) between the partition $g_{\mathrm{network}}$ obtained from a graph and the partition obtained from the graphons $g_{\mathrm{graphon}}$ that we estimated from the graph, using three different approaches. We also provide a reference for the data and the number $N$ of nodes in each network. For each data, we highlight the estimation method that yields the best result. While the matrix-completion method always yields decent results ($\text{AMI}>0.4$), the USVT is better for some data sets. For all data sets, the sort-and-smooth algorithm yields small AMIs.} \label{tab:normalisedInformation} \end{table} \section{Discussion}\label{sec:discussion} In this manuscript, we considered the problem of modularity optimization from the perspective of graphons. We showed how a generalised modularity-maximisation algorithm for graphs can be used for modularity optimization on graphons after suitable discretization and discussed how in certain cases analytical solutions for the modularity optimization problem for graphs can be obtained. For future research, exploring how far further insights into trace maximisation problems, such as modularity optimization, can be obtained by using such a perspective based on operators defined on a continuous domain would be of interest. Interestingly, it has been shown recently that maximum-likelihood estimation of an stochastic block model (a problem closely related to Modularity optimization~\cite{pamfil2019relating,newman2016equivalence}) is equivalent to a discrete surface tension~\cite{boyd2019stochastic}, thus providing a connection to partial differential equations and continuous problem formulations. There are also other avenues to explore in the future: In this manuscript, we discussed graphon-modularity with the popular Newman--Girvan null model. Our framework does, however, also allow the use of other null models or a resolution parameter, which might reveal a hierarchical community structure in graphons. One limitation of graphons is that they describe limits of dense graphs~\cite{orbanz2014bayesian}. Many empirical networks, however, are sparse. \emph{Exchangeable random measures} have been proposed as a way to construct sparse graph-variants~\cite{caron2017sparse}. It would be relevant for applications, to extend modularity-based approaches to also detect community structure in these objects. From a privacy-preserving computing point of view, it would be interesting to explore to what extent a graphon description could be de-anonymised, when obtaining information about the network from which it was estimated. Furthermore, an investigation in how far other graph-measures that can be extended to graphons allow for privacy-presering computation would be interesting. \section{Code availability} {\sc Matlab} and {\sc Mathematica} code to implement the discussed methods and reproduce all figures is available under \url{http://github.com/floklimm/graphon}.
{'timestamp': '2021-01-05T02:19:25', 'yymm': '2101', 'arxiv_id': '2101.00503', 'language': 'en', 'url': 'https://arxiv.org/abs/2101.00503'}
arxiv
\section{Conclusions} This work proposes AECNN, or the Aligned Edge Convolutional Neural Network, which addresses the challenges of learning rotationally-invariant representations for point clouds. Rotation invariance is achieved by representing points' coordinates relative to local reference frame. The proposed AECNN architecture is designed to better extract and fuse information from local and global features. In this way, the AECNN architecture is able to generalize well to unseen rotation. Extensive experiments are performed in classification and segmentation and demonstrate effectiveness of AECNN. \section{Acknowledgement} This work was supported by a grant from the Ford Motor Company via the Ford–University of Michigan Alliance under award N028603. {\small \bibliographystyle{ieee} \section{Introduction} The development of low-cost 3D sensors has the potential to revolutionize the way robots perceive the world. For this revolution to be realized, algorithms to interpret and classify the large volumes of point clouds generated by these sensors must be developed. To construct such algorithms, one could be inspired by the successes of deep learning approaches that robustly interpret 2D images in the presence of noise or lighting, rotation, and scaling variability. These deep learning approaches achieve impressive performance by relying on representations that enforce lighting, rotation, and scaling invariance. Unfortunately, the lack of a representation that is able to enforce rotation invariance has hindered the application of deep learning techniques to analyze point clouds. \begin{figure}[t] \centering \includegraphics[width=\linewidth]{{figures/seg_comparison.pdf}} \caption{An comparison of the performance of state-of-the-art techniques to the method developed in this paper while performing part segmentation on rotated point clouds from the ShapeNet dataset. We report results on models of arbitrary rotation during testing while they trained with only rotation along vertical direction ($x$ axis) and on models of arbitrary rotation during both training and testing ($y$ axis) (subfigure a). This degradation in performance can be seen on the quality of part segmentation in unseen views (subfigure b, where different colors correspond to different part categories).} \label{fig:seg_comparison} \end{figure} To address this challenge, researchers have typically converted point clouds into regular 2D~\cite{feng2018gvcnn,su2015multi,kanezaki2018rotationnet,su2018deeper} or 3D~\cite{voxnet,qi2016volumetric,wu20153d} grids before applying \acp{CNN} to learn a meaningful representation. Unfortunately, this conversion process degrades the resolution of measured objects which can adversely affect point cloud analysis. More recently, PointNet~\cite{qi2017pointnet} was proposed to preserve some of this geometric information by using a symmetric kernel that could enforce permutation invariance. This approach allowed a user to directly treat a point cloud as an input into a \ac{DNN} and get a global vector representing the input point cloud as an output. This work was subsequently extended in a variety of ways to preserve local structure within a point cloud that proved to be important while performing classification~\cite{qi2017pointnet++,wang2019dynamic,liu2019relation}. However, the representations developed by these methods rely on an individual point's absolute position, which hinders their ability to develop algorithms that are invariant to rigid body transformations. Fig.~\ref{fig:seg_comparison}, for instance, illustrates the deficiency of these methods when they are applied to perform part segmentation on views that are unseen during training. Typically, one can address this limitation and improve the robustness of \acp{DNN} to rigid body transformations by augmenting the training set with additional examples. However, this requires additional computation and increased model capacity. For instance, during classification, a model must learn a function that maps the same object under different rigid body transformations into a similar feature in a feature space. Rather than augment the training set, other approaches have focused on developing representations that can preserve rotational symmetry by directly converting point clouds into a spherical voxel grid and then extracting rotation-equivariant features~\cite{esteves2018learning,rao2019spherical,you2018prin}. Unfortunately this conversion still sacrifices resolution that can adversely affect point cloud analysis. To remedy this loss of information, others have proposed to represent point clouds relative to a \ac{LRF}, which is determined by a local subset of a point cloud~\cite{chen2019clusternet,zhang2019rotation}. Each point in a neighborhood of a constructed \ac{LRF} is represented with respect to that \ac{LRF} and a local feature is learned for each point set. Subsequently these local features are fused together to define global features. These \ac{LRF}-based learned representations are invariant to rotation; however, as we illustrate in this paper, the accuracy of techniques utilizing \ac{LRF}-based representation are only marginally better than those utilizing an absolute coordinate based representation for point cloud classification tasks. This is in part because the learned local features for a pair of points are not aligned before they are fused together. To address the limitations of existing approaches, this paper proposes a novel 3D representation of point clouds that is invariant under rotation and introduces a new neural network architecture, the \ac{AECNN}, to utilize this representation. As in prior work, we leverage the notion of \acp{LRF} to ensure that different orientations of a point cloud are mapped into the same representation. Each point in a neighborhood of a constructed \ac{LRF} is represented with respect to that \ac{LRF} before subsequent processing. This ensures that the model is able to learn internal geometric relationships between points rather than learning geometric relationships that are a function of the absolute coordinates of the points that may change after rotation. Our proposed \ac{AECNN} architecture processes these local internal features and aligns them with local internal features drawn from other \acp{LRF} before fusing them together in a hierarchical fashion to define global features. Importantly, in contrast to prior work that utilizes a spherical coordinate system~\cite{chen2019clusternet} or non-orthogonal basis~\cite{sun2019srinet}, we construct a basis for the \acp{LRF} that is orthonormal. This ensures that feature alignment can be computed in a straightforward manner which makes the hierarchical fusion of local features tenable. The contributions of this paper are three-fold: First, we propose a novel representation of points clouds that is invariant to arbitrary rotations. Second, we propose a novel alignment strategy to align neighboring features within distinct \acp{LRF}. This makes it feasible to perform feature fusion within a hierarchical network, which makes a reasonable feature fusion between local and global features. Finally, we illustrate that our propose representation is robust to rotation and achieves state-of-the-art results in both point cloud classification and segmentation tasks. \section{Learning Rotation-Invariant Representation of Point Clouds} This section introduces our proposed \ac{RIR} of point clouds using \acp{LRF}, our proposed aligned edge convolution designed for \ac{RIR}, and the proposed hierarchical network architecture for classification and segmentation tasks. \begin{figure}[t] \centering \includegraphics[width=\linewidth,height=0.4\linewidth]{{figures/LRF.pdf}} \caption{ An illustration of aligned edge convolution and the \acp{LRF} that help define it. To construct the \ac{RIR}, one takes the reference point $p_i$ and the $k$-nearest points to it (subfigure a). The \ac{LRF} is determined by $p_i$ and the anchor point $m$ which is defined as the barycenter of the $k$-nearest points to $p_i$. The coordinates of $k$-nearest points are described with respect to the \ac{LRF}. Note that \acp{LRF} may not be aligned due to independence of the local neighborhood of points that define each \ac{LRF} (subfigure b). } \label{fig:LRF} \end{figure} \subsection{Rotation-Invariant Representation} \label{section:RIR} To construct a representation that is invariant to rotation, we represent a point's coordinates relative to a \ac{LRF}. Each \ac{LRF} is defined using three orthonormal basis vectors and is designed to be dependent on local geometry, as is depicted in Fig. \ref{fig:LRF} (a). To define this \ac{LRF}, suppose we are given a reference point $p_i$ in a point cloud and a set of neighboring points $\{p_1,\ldots,p_k\}$ to $p_i$ in the point cloud whose coordinates are all described with respect to a coordinate system with global origin $o$. Note, we describe how to select these reference points in Section \ref{subsec:network}, and neighboring points are those within a certain radius to the reference point. Next, define an anchor point $m$ as the barycenter of the neighboring points: \begin{equation} m = \frac{1}{k} \sum_{j=1}^{k} p_j, \end{equation} and the plane $\alpha$ that is orthogonal to $\vv{op_i}$ and intersects with $p_i$. Using these definitions, we can define the projection of $m$ onto the plane $\alpha$: \begin{equation} \vv{p_ip_m} = \vv{om} - \frac{\vv{op_i}}{|\vv{op_i}|} \cdot \langle \vv{om}, \frac{\vv{op_i}}{|\vv{op_i}|}\rangle. \end{equation} With this definition, we can construct the following coordinate axes for the \ac{LRF}: \begin{equation} \label{eq:1} \vv{x}:= \frac{\vv{p_ip_m}}{|\vv{p_ip_m}|}, \;\;\; \vv{z}:= \frac{\vv{op_i}}{|\vv{op_i}|}, \;\;\; \vv{y}:= \vv{z} \times \vv{x}. \end{equation} Note that $z$ axis is defined as the direction from global origin $o$ pointing at $p_i$; the $x$ axis is defined as the direction from $p_i$ pointing at $p_m$; and the $y$ axis is defined as the direction of cross product of $z$ and $x$ axis. The origin of \ac{LRF} is at the reference point $p_i$. We assume that the global origin $o$ is known, and in our case we use the center of point clouds. We introduce rotation invariance by representing the set of neighboring points relative to their \ac{LRF}: \begin{equation} \label{eq:2} t^i_j = (\langle p_{ij}, \vv{x} \rangle, \langle p_{ij}, \vv{y} \rangle, \langle p_{ij}, \vv{z} \rangle) \end{equation} where $p_{ij} = p_j - p_i$ for each $p_j \in \{p_1,\ldots,p_k\}$. Note $t^i_j$ is the \ac{RIR} for the point $p_j$ relative to the LRF at point $p_i$. We then use a PointNet structure to capture the geometry within the neighboring points using the \ac{RIR}: \begin{equation} f(\{t^i_1, ..., t^i_k\}) = MAX(\{h(t^i_1), ..., h(t^i_k)\}) \end{equation} where $f$ is a learning function, which takes a point set as input, and outputs a feature vector representing input point clouds, $h$ is a feature transformation function and is approximated by a \ac{MLP}. Note, the max pooling layer aggregates information. \subsection{Aligned Edge Convolution} To capture the geometric relationship between points in a point cloud, the notion of edge convolution via DGCNN has been developed~\cite{wang2019dynamic}. To understand how edge convolution works, suppose we are given a point cloud with $n$ points, denoted by $P = \{p_1, ..., p_n\} \subseteq {\rm I\!R}^3$, along with F-dimensional features corresponding to each point, denoted by $X = \{x_1, ..., x_n\} \subseteq {\rm I\!R}^F$. Suppose we construct the $k$-\ac{NN} graph $(V, E)$ in the feature space, where $V={1, ..., n}$ and $E\subseteq V \times V$ are vertices and edges, then the edge convolution output at $i$-th vertex is given by: \begin{equation} \label{eq:6} x'_i = \underset{j:(i,j)\in E}{MAX} \; g(x_i, x_j - x_i) \end{equation} where $g$ is a \ac{MLP}. Note, edge convolution is essentially performing feature fusion. It fuses the global information captured by $x_i$ with local neighborhood information captured by $x_i - x_j$. To be able to do this, $x_i$ and $x_j$ must be learned in the same coordinate system. Unfortunately, it is nonviable to directly apply edge convolutions to features in our case. This is because in our case, $x_i$ and $x_j$ are learned relative to two different \acp{LRF}, and the \acp{LRF} of $x_i$ and $x_j$ may not be aligned, as is shown in the Fig. \ref{fig:LRF} (b). As a result, applying edge convolution directly on our learned features may create inconsistent features. To resolve this problem, we propose aligning $x_j$ into the \ac{LRF} of $x_i$ before performing feature fusion. We call our approach, which is depicted in Fig. \ref{fig:architecture}, Aligned Edge Convolution (Aligned EdgeConv). To construct our approach, we begin by understanding the relationship between different \acp{LRF} which can be described using a rotation $R$ and translation $T$. To construct this rotation and translation, suppose the basis of the \ac{LRF} for each feature is denoted by $E = \{e_1, ..., e_n\} \subseteq {\rm I\!R}^{3\times3}$. Then the rotation matrix and translation vector can be computed by: \begin{equation} R_j = e_i \cdot e_j^{-1} = e_i \cdot e_j^\top \end{equation} \begin{equation} T_j = t^i_j \end{equation} where $e_j$ is an orthogonal matrix defined in \eqref{eq:1} and $t_j$ is defined in \eqref{eq:2}. $R$ and $T$ describe the relationship between \acp{LRF}, so we use them to transform $x_j$ into the \ac{LRF} of $x_i$. Though it is easy to invert a rotation and translation in 3D, extending it to the high dimensional feature space that $x_j$ lives in would be challenging. One option to resolve this problem is to apply an approach similar to the \ac{STN} proposed in the PointNet wherein one predicts a transformation matrix from $R$ and $T$ and applies it to $x_j$: \begin{equation} \label{eq:3} \hat{x}_j = \phi(R_j, T_j) \cdot x_j \end{equation} where $\phi$ is a \ac{MLP} and outputs an $F \times F$ matrix compatible with $x_j$. Typically a regularization term is added to the loss during training to constrain the feature transformation matrix to be close to an orthogonal matrix. Another option is to take $R$, $T$ and $x_j$ as inputs and directly output a transformed feature: \begin{equation} \label{eq:4} \hat{x}_j = \phi(R_j, T_j, x_j) \end{equation} In this paper, we utilize the second option. As we show in Section \ref{section:aligned_edgeconv}, option one requires more \acp{GPU} memory and has more parameters. Therefore we update the \eqref{eq:6} by: \begin{equation} x'_i = \underset{j:(i,j)\in E}{MAX} \; q(x_i, \hat{x}_j - x_i). \end{equation} Similar to PointNet++~\cite{qi2017pointnet++}, we also include the \ac{RIR} $t^i_j$ in the edge convolution to maintain more information. So the aligned edge convolution is given by \begin{equation} x'_i = \underset{j:(i,j)\in E}{MAX} \; q(x_i, \hat{x}_j - x_i, t^i_j). \end{equation} \subsection{Network Architecture} \label{subsec:network} Our proposed network architecture that takes raw point clouds as input and learns a representation is depicted in Fig. \ref{fig:architecture}. Our architecture is inspired by techniques that perform local-to-global learning which has been successfully applied to 2D images~\cite{zhao2017pyramid} and has been shown to effectively extract contextual information. We exploit a hierarchical structure to learn both local and global representation. Our approach captures larger and larger local regions using two \ac{SA} blocks, proposed by PointNet++~\cite{qi2017pointnet++}, and the global features are constructed by aggregating outputs from the last \ac{SA} block using max pooling. \begin{figure*}[t!] \centering \includegraphics[width=1\linewidth]{{figures/architecture.pdf}} \caption{An illustration of the deep hierarchical architecture proposed in this paper to learn a rotationally invariant representation of point clouds for classification. The network takes $N$ points as inputs and uses two \ac{SA} blocks to hierarchically learn a representation of larger and larger regions. The final part aggregates features from the last \ac{SA} block and outputs a feature vector encoding the input point set. The SAFirst block samples reference points and builds a $k$-\ac{NN} graph in Euclidean space. It converts points into the \ac{RIR} and transforms them using a shared-weights PointNet structure that outputs feature vectors encoding information for each reference point' neighbors. The SANext block applies a similar process to the SAFirst block except for building the $k$-\ac{NN} graph in feature space and extracting features using Aligned EdgeConv. The feature alignment module within Aligned EdgeConv aligns local features to the \ac{LRF} of the reference point using the rotation matrix $R$ and the translation vector $T$ that are defined in the Section \ref{section:RIR}. Then the aligned local features are fused with the feature at the reference point along with translation vector $T$. Note mlp in the figure is abbreviated for \ac{MLP}. The output is classification scores for $c$ classes.} \label{fig:architecture} \end{figure*} The two \ac{SA} blocks each have distinct structures; however, they share the same processing pipeline: sampling, grouping, and processing. The structure of the first \ac{SA} block (SAFirst) is illustrated in the green block in Fig. \ref{fig:architecture}. Given the input point clouds, we use farthest point sampling (FPS) to subsample the point cloud while preserving its geometric structure. The constructed points serve as the reference points during the construction of a $k$-\ac{NN} graph. The $k$-\ac{NN} graph is computed in Euclidean space, and it is used to generate the \ac{RIR} described in Section \ref{section:RIR}. A shared-weights PointNet structure then processes the \acp{RIR} for each local set of points and outputs a feature vector describing the set of points near each reference point. The structure of SANext is shown within the blue block in Fig. \ref{fig:architecture}. The sampling and grouping strategy in SANext is identical to the one in SAFirst except that one quarter the number of points are selected as reference points and the $k$-\ac{NN} graph is dynamically updated and computed in the feature space, which has been shown to be more beneficial and have larger receptive fields than a fixed graph version~\cite{wang2019dynamic}. Then the proposed aligned edge convolution extracts features encoding larger local regions than the previous \ac{SA} block. The rotation matrix $R$ and translation vector $T$, which can be derived from basis and positions of \acp{LRF}, are fed into a feature alignment module to align local features to the frame of reference point. Essentially, the SANext is the building block that can be used to iteratively capture larger and larger local regions. Note for the segmentation task, we require a feature for each point. We adopt a similar strategy to PointNet++~\cite{qi2017pointnet++}, which propagates features from subsampled points to original points. Specifically, the interpolated features from the previous layer are concatenated with skip linked features output from \ac{SA} blocks. The interpolation is done via the inverse distance weighted average based on $k$-\ac{NN}. Importantly, the proposed feature alignment idea is also integrated in this feature propagation pipeline. \section{Related work} This section reviews the various techniques that have been applied to represent point clouds. \textbf{View-Based and Volumetric Methods.} A variety of methods have represented 3D shape as a sequence of 2D images since they can leverage existing algorithms from 2D vision~\cite{he2016deep,he2017mask,long2015fully}. These view-based methods typically project a 3D shape onto 2D planes from different views. These different images are then processed by \acp{CNN}. Though these methods achieve good performance at classification tasks using off-the-shelf architectures and pre-trained model \cite{feng2018gvcnn,su2015multi,kanezaki2018rotationnet,su2018deeper}, the projection of 3D shape onto 2D planes sacrifices 3D geometric structures that are critical during point cloud analysis. Converting point clouds into 3D voxels can preserve some of this geometric information. The higher the resolution of quantization, the more geometric information is preserved. These converted point clouds can then leverage existing \acp{CNN} with 3D kernels~\cite{voxnet,qi2016volumetric,wu20153d}. Since points are only sampled from the surface of objects, regular quantization can waste valuable resolution on the empty space within or outside objects. Better partitioning methods, such as KD-tree~\cite{klokov2017escape} and Oct-tree~\cite{wang2017cnn,tatarchenko2017octree} have been proposed to address this limitation. In contrast to these methods, our approach works directly with point clouds without requiring any conversion. \textbf{Point Set Learning.} Point set learning methods take raw point clouds as input. The pioneering work in this area is PointNet~\cite{qi2017pointnet}, which independently transforms each point and outputs a global feature vector describing the input point cloud by aggregation using a max pooling layer. Unfortunately, PointNet is unable to learn local structure over increasing scales, which is important for high-level learning tasks. Extensions that utilize hierarchical structure~\cite{qi2017pointnet++,li2018so}, graph network~\cite{wang2019dynamic,zhang2018graph}, or relation-aware features~\cite{liu2019relation} have been proposed to preserve local geometric structure during processing. Other extensions that rethink the convolution operation to better accommodate point cloud processing have also been proposed~\cite{wu2019pointconv,li2018pointcnn}. However, the representation that is learned by these approaches changes when the point clouds in the training set are rotated. As a result, these representations perform poorly when utilized during classification or segmentation tasks on rotated versions of point clouds that were not included during training. \textbf{Rotation Learning.} Various methods have been proposed to either learn rotation-invariant or rotation-equivariant representations. For instance, \acp{STN} have been proposed to learn rotation-invariant representations~\cite{qi2017pointnet}. The \ac{STN} learns a transformation matrix to align input point clouds without requiring that the alignment place the point clouds in some fixed ground-truth orientation. As a result, the transformation matrix is not guaranteed to align objects to a consistent orientation which restricts its utility. Other approaches achieve rotation invariance by relying on \acp{LRF} ~\cite{chen2019clusternet,zhang2019rotation,sun2019srinet}. However, the difficulty of aligning the features learned with respect to \acp{LRF}, as described earlier, has limited the potential expressive capabilities of these techniques. Since designing a model that is invariant to rotation is difficult, a variety of methods have attempted to achieve rotation-equivariance using spherical convolutions~\cite{esteves2018learning,rao2019spherical,you2018prin}. Spherical convolutions require the spherical representation of a point cloud. Unfortunately projecting 3D point clouds into 2D sphere results in a loss of information. \section{Experiments} This section describes how we implement the network described in Section \ref{subsec:network} and how we validate its utility. First, we evaluate our method on a shape classification task (Sec \ref{section:modelnet40}) and part segmentation task (Sec \ref{section:shapenet}). Second, we evaluate the design of our \acp{LRF} (Sec \ref{section:LRF_validation}) and illustrate the effectiveness of the proposed aligned edge convolution (Sec \ref{section:aligned_edgeconv}). \subsection{Implementation details} \label{section:implementation} We implement our network in PyTorch. All experiments are run on a single NVIDIA Titan-X GPU. During optimization, we use the Adam optimizer with batch size 32. Models are trained for 250 epochs. The learning rate starts with $1e{-3}$ and scale by $0.2$ every $100$ epochs. In some experiments, we augment the dataset with arbitrary rotations. However, it is impossible to cover all rotations in 3D space. Similar to ClusterNet~\cite{chen2019clusternet}, we uniformly sample possible rotations. Each rotation is characterized by a rotation axis $v$ and a rotation angle $\theta$ that is given by: \begin{equation} R = I + (\sin{\theta})K + (1 - \cos{\theta})K^2 \end{equation} where $K$ denotes the cross-product matrix for the rotation axis $v$ which has a unit length and $I$ is the identity matrix. In the experiments, we sample 3-dimensional vectors from a normal distribution and normalize $v$ to be a unit vector. We follow the approach presented in~\cite{esteves2018learning} to perform experiments in three different settings: 1) training and testing with rotation along the vertical direction (Y/Y), 2) training with rotation along vertical direction and testing with arbitrary rotation (Y/AR) and 3) performing arbitrary rotation during training and testing (AR/AR). The last two settings in particular are used to evaluate the generalization ability of the model under unseen rotations. \begin{table*}[t] \begin{center} \begin{tabular}{lccccc} \hline Method & Inputs & Input size & Y/Y & Y/AR & AR/AR \\ \hline MVCNN 80x~\cite{su2015multi} & view & $80 \times 224^2$ & 90.2 & 81.5 & 86.0 \\ Spherical CNN~\cite{esteves2018learning} & voxel & $2 \times 64^2$ & 88.9 & 76.9 & 86.9\\ \hline PointNet~\cite{qi2017pointnet} & point & $1024 \times 3$ & 88.5 & 21.8 & 83.6 \\ PointNet++~\cite{qi2017pointnet++} & point & $1024 \times 3$ & 89.3 & 31.7 & 84.9 \\ RS-CNN~\cite{liu2019relation} & point & $1024 \times 3$ & 89.6 & 24.7 & 85.2\\ DG-CNN~\cite{wang2019dynamic} & point & $1024 \times 3$ & 91.7 & 31.5 & 88.0 \\ \hline RI-CNN~\cite{zhang2019rotation} & point & $1024 \times 3$ & 86.5 & 86.4 & 86.4\\ SRINet~\cite{sun2019srinet} & point & $1024 \times 3$ & 87.0 & 87.0 & 87.0\\ ClusterNet~\cite{chen2019clusternet} & point & $1024 \times 3$ & 87.1 & 87.1 & 87.1\\ SF-CNN~\cite{rao2019spherical} & point & $1024 \times 3$ & \textbf{92.3} & 84.8 & 90.1\\ \hline Ours & point & $1024 \times 3$ & 91.0 & \textbf{91.0} & \textbf{91.0} \\ \hline \end{tabular} \end{center} \caption{Classification results on ModelNet40 dataset. We report the accuracy (\%) in three different settings: training and testing with rotation along the vertical direction (Y/Y), training with rotation along vertical direction and testing with arbitrary rotation (Y/AR), and performing arbitrary rotation during training and testing (AR/AR). Though our model is only the third best performer in the Y/Y setting it is the top model in each of the other categories. In particular our proposed model has superior performance in the Y/AR and AR/AR, which means that it can generalize well to unseen rotations.} \label{table:classification} \end{table*} \subsection{Shape Classification} \label{section:modelnet40} One of the primary point clouds analysis tasks is to recognize the category of point clouds. This task requires a model to learn a global representation. \textbf{Dataset.} We evaluate our model on ModelNet40, which is a shape classification benchmark~\cite{wu20153d}. It provides 12,311 CAD models from 40 object categories, and there are 9,843 models for training and 2,468 models for testing. We use their corresponding point clouds provided by PointNet~\cite{qi2017pointnet}, which contain 1024 points in each point clouds. During training we augment the point clouds with random scaling in the range $[-0.66, 1.5]$ and random translation in the range $[-0.2, 0.2]$ as in~\cite{klokov2017escape}. During testing, we perform ten voting tests while randomly sampling 1024 points and average the predictions. \textbf{Point clouds classification.} We report the results of our model and compare it with other approaches in the Table \ref{table:classification}. Three different training and testing setting are performed, which are introduced in Section \ref{section:implementation}. All approaches, except for the last five which are specially designed for rotation learning, perform well in the Y/Y setting, but experience a significant drop in accuracy when evaluated on unseen rotation as shown in the Y/AR setting. We conclude that these approaches only generalize well to rotations that they are trained on. However, our proposed method performs equally well across all three settings. Every evaluated approach has lower accuracy in the AR/AR setting than the Y/Y setting, except for RI-CNN, SRINet, ClusterNet, and our proposed method. This is most likely due to the difficulty of mapping identical objects in different poses to a similar feature space. This requires larger model complexity and is difficult to address with just dataset augmentation. RI-CNN (86.4\%), SRINet (87.0\%) and ClusterNet (87.1\%) are specially designed for rotation invariance. Our model has superior performance in the setting of Y/AR and AR/AR (91.0\%), which means our proposed method generalizes well to unseen rotations. \begin{table}[t] \begin{center} \begin{tabular}{lcccc} \hline Method & Input size & Y/Y & Y/AR & AR/AR \\ \hline PointNet~\cite{qi2017pointnet} & $2048 \times 3$ & 79.3 & 43.0 & 73.9 \\ PointNet++~\cite{qi2017pointnet++} & $2048 \times 3$ & \textbf{80.6} & 45.9 & 75.5 \\ DG-CNN~\cite{wang2019dynamic} & $2048 \times 3$ & 79.2 & 46.1 & 71.8 \\ RS-CNN~\cite{liu2019relation} & $2048 \times 3$ & 80.0 & 50.7 & 73.3\\ \hline RI-CNN~\cite{zhang2019rotation} & $2048 \times 3$ & - & 75.3 & 75.5\\ SRINet~\cite{sun2019srinet} & $2048 \times 3$ & 77.0 & 77.0 & 77.0\\ \hline Ours & $2048 \times 3$ & 80.2 & \textbf{80.2} & \textbf{80.2} \\ \hline \end{tabular} \end{center} \caption{Part segmentation results on ShapeNet dataset. Point cooridnates are taken as inputs, and \ac{mIoU} across all classes is reported in three different settings including Y/Y, Y/AR and AR/AR. Our model outperforms all approaches except PointNet++ in Y/Y setting. Our model has superior performance in the Y/AR and AR/AR settings, which means that it can generalize well to unseen rotations.} \label{table:segmentation} \vspace{-2mm} \end{table} \begin{figure}[t] \centering \includegraphics[width=\linewidth,height=0.6\linewidth]{{figures/seg.pdf}} \caption{Qualitative results of our proposed method on part segmentation task on the ShapeNet dataset. From top to bottom, segmentation results of different categories are shown. From left to right, we show ground truth label and results when the input point clouds are arbitrarily rotated during testing. Different colors correspond to different part categories. Our model is robust to arbitrary rotations of the input point clouds.} \label{fig:seg} \end{figure} \begin{figure}[t] \centering \includegraphics[width=\linewidth,height=0.6\linewidth]{{figures/seg_unseen_comparison.pdf}} \caption{Qualitative results of part segmentation on ShapeNet. The Y/AR setting is adopted for all models. From top to bottom, segmentation results of different categories are shown. From left to right, we show ground truth label and the results from different approaches. Different colors correspond to different part categories. Our method achieves state-of-the-art performance while other approaches fail to generalize to unseen rotation.} \label{fig:seg_unseen_comparison} \end{figure} \subsection{Part Segmentation} \label{section:shapenet} The part segmentation task requires assigning each point in a point cloud a category label. Since this is a point-wise classification task, part segmentation is typically more challenging than classification. \textbf{Dataset.} We evaluate our model on ShapeNet part dataset~\cite{yi2016scalable}, which contains 16,881 shapes from 16 categories and annotated with 50 parts in total. We split the dataset into training, validation and test sets following the convention in PointNet++~\cite{qi2017pointnet++}. 2048 points are randomly picked on the shape of objects. We concatenate the one-hot encoding of the object label to the last feature layer in the model as in~\cite{qi2017pointnet++}. During evaluation, mean inter-over-union (mIoU) that are averaged across all classes is reported. \textbf{3D part segmentation.} We report the result of our model and compare it with other approaches in Table \ref{table:segmentation} and (subfigure a) in the Fig. \ref{fig:seg_comparison}. Results align well with performance in the classification task. In addition, our method outperforms other approaches in all three settings, except for PointNet++ which is slightly better than our proposed method in the Y/Y setting. The consistent performance of our method in all three settings demonstrates good generalization to unseen rotations. Qualitative results of part segments are illustrated in Fig.~\ref{fig:seg}. The comparison results with other approaches in the Y/AR setting are also visualized in Fig.~\ref{fig:seg_unseen_comparison}. \begin{table}[t] \small \begin{center} \begin{tabular}{lcccc} \hline Method & EdgeConv & AEConv1 & AEConv2 & AEConv3\\ \hline Acc. & 89.6 & 90.2 & 48.5 & 91.0 \\ Para. & 1.94M & 2.14M & - & 1.99M \\ FLOPs & 4170M & 6393M & - & 4841M \\ \hline \end{tabular} \end{center} \caption{Ablation study on aligned edge convolution and comparison with original edge convolution. Accuracy, number of parameters and FLOPs per sample are reported. No further experiments were done on AEConv2 due to its poor accuracy. The number of neighbors is 48. } \label{table:aligned_edgeconv} \end{table} \subsection{\ac{LRF} Analysis} \label{section:LRF_validation} We achieve rotation invariance by expressing points coordinates respect to \acp{LRF}. Note that the \ac{LRF} is handcrafted rather than learned from raw data. As a result, one may be concerned about the effectiveness of the designed \ac{LRF}~\cite{spezialetti2019learning}. Currently, common ways of designing \acp{LRF} use the eigenvectors of the covariance matrix of the local point set~\cite{mian2010repeatability,tombari2010unique} or rely on the surface normal as the reference axis~\cite{petrelli2011repeatability}. However, computing eignvectors for all points in some local neighborhood of points is time-consuming and estimating an accurate normal from point clouds is still challenging. In this study, we consider several alternative ways to compute \acp{LRF} and illustrate their effects on our models' performance. The definition of \ac{LRF} is introduced in the Section \ref{section:RIR}. Note that given a reference point, the only variation in the definition of the \ac{LRF} arises from the $x$ axis. Because the $z$ axis is defined as the direction from the global origin to the reference point, and the $y$ axis is defined by the cross product of the $z$ and $x$ axis. Recall that the $x$ axis is associated with the anchor point $m$, which is shown in the Fig. \ref{fig:LRF}. Here we investigate three different aspects that influence the determination of the anchor point: searching methods, ways of grouping the data, and the number of neighbors. We perform experiments on shape classification, and Table \ref{table:LRF} shows the results. \begin{table}[t] \small \begin{center} \begin{tabular}{cc|cc|cccc|c} \hline \multicolumn{2}{c|}{Searching} & \multicolumn{2}{c|}{Grouping} & \multicolumn{4}{c|}{\# neighbors} & \multirow{2}{*}{Acc.} \\\cline{1-8} knn & ball & Mean & Max. D & 10 & 16 & 32 & 48 \\ \hline & \checkmark & \checkmark & & & & & \checkmark & 90.4 \\ & \checkmark & & \checkmark & & & & \checkmark & 90.3 \\ \checkmark & & & \checkmark & & & & \checkmark & 90.3 \\ \checkmark & & \checkmark & & & & & \checkmark & \textbf{91.0} \\ \checkmark & & \checkmark & & \checkmark & & & & 89.6 \\ \checkmark & & \checkmark & & & \checkmark & & & 90.3 \\ \checkmark & & \checkmark & & & & \checkmark & & 90.8 \\ \hline \end{tabular} \end{center} \caption{Ablation study on \acp{LRF}. Models are evaluated on ModelNet40 dataset in the Y/AR setting. Three aspects which effect \acp{LRF} are studied: searching methods, grouping ways and the number of neighbors. } \label{table:LRF} \end{table} We compare two searching methods: ball query and k-\ac{NN} search. Ball query finds all points within a certain radius to the reference point, but only up to $k$ points are considered in the experiments. k-\ac{NN} finds a fixed $k$ nearest points to the reference point. As is shown in the first four rows of Table \ref{table:LRF}, given the same grouping method models with k-\ac{NN} search have equal or higher accuracy than ball query. However the performance of the ball query method is marginally sensitive to the size of the radius chosen, which needs to be assigned manually, as is shown in Table \ref{table:radius}. \begin{table}[t] \begin{center} \begin{tabular}{ccccc} \hline Radii & (0.1, 0.2) & (0.1, 0.4) & (0.2, 0.2) & (0.2, 0.4)\\ \hline Acc. & 89.1 & 89.3 & 90.3 & \textbf{90.4} \\ \hline \end{tabular} \end{center} \caption{Ablation study on radius in ball query. Models are evaluated on ModelNet40 dataset in the Y/AR setting. Model's performance is marginally sensitive to radius if ball query is used. (r1, r2) indicates the radius in the first SABlock and the second SABlock respectively.} \label{table:radius} \end{table} We study two ways of determining the anchor point: we define the anchor point as the mean of neighboring points or as the point with largest projected distance to reference point on plane $\alpha$ shown in the Fig. \ref{fig:LRF} (b). From rows three and four in Table \ref{table:LRF}, we conclude that anchor points computed from mean of neighbors is preferred (91.0\%) over anchor points with largest projection distance (90.3\%). The last four rows of Table \ref{table:LRF} illustrate the performance of our model with different numbers of neighboring points. We find performance drops with decreasing of $k$ and the model with 48 nearest points achieves the best performance (91.0\%). Further increasing the number of nearest points leads to extra computation burden. \subsection{Aligned EdgeConv Analysis} \label{section:aligned_edgeconv} The proposed AECNN is specially designed to learn a rotation-invariant representation. Recall that we align features before doing feature fusion within the edge convolution and call it aligned edge convolution (AEConv). This study compares the original edge convolution which does not perform feature alignment~\cite{wang2019dynamic} with our proposed aligned edge convolution. We also experiment with different strategies for doing alignment. The results are shown in Table \ref{table:aligned_edgeconv}. We report three different strategies for alignment: transforming the source feature by a transformation matrix in the feature space (AEConv1), which is defined in \eqref{eq:3}; taking source feature $x_j$, LRF $e_i$ of source point, LRF $e_j$ of reference point and translation $T$ as inputs to predict the aligned feature (AEConv2); taking source $x_j$ along with rotation matrix $R$ and translation $T$ as inputs to predict the aligned feature (AEConv3), which is defined in \eqref{eq:4}. Our proposed feature alignment idea is verified by comparison between the first column and the last columns, where aligned edge convolution has higher accuracy (91.0 \%) than the original edge convolution (89.6 \%) which has no alignment process. AEConv1 (90.2 \%) also outperforms edge convolution, but it loses slightly to AEConv3. Due to limited GPU memory, we need to reduce the number of learning kernels within the SAFirst block of AEConv1, so that it can be fed into a single GPU during training. Even in this case, AEConv1 still has more parameters (2.14M) to learn than AEConv3 (1.99M) and more FLOPs per sample during the test (6393M) than AEConv3 (4841M). Additionally, AEConv2 is not able to converge.
{'timestamp': '2021-01-05T02:19:00', 'yymm': '2101', 'arxiv_id': '2101.00483', 'language': 'en', 'url': 'https://arxiv.org/abs/2101.00483'}
arxiv
\section{Introduction} Given a set of points $X \subset \mathbb{R}^n$, the vanishing ideal of $X$ is the set of polynomials in $\mathbb{R}[x_1,\ldots,x_n]$ that vanish for any $\mathbf{x}\in X$. \begin{align} \mathcal{I}(X) = \qty{g \in \mathbb{R}[x_1,\ldots,x_n] \mid \forall \mathbf{x} \in X, g(\mathbf{x}) = 0}. \end{align} The approximate computation of bases of vanishing ideals has been extensively studied~\cite{abbott2008stable,heldt2009approximate,fassino2010almost,robbiano2010approximate,limbeck2013computation,livni2013vanishing,kiraly2014dual,kera2018approximate,kera2019spurious,kera2020gradient,wirth2022conditional} in the last decade, where a basis comprises approximately vanishing polynomials, i.e., $g(\mathbf{x})\approx 0, (\forall\mathbf{x}\in X)$. Approximate basis computation and approximately vanishing polynomials are exploited in various fields such as dynamics reconstruction, signal processing, and machine learning~\cite{torrente2009application,hou2016discriminative,kera2016vanishing,kera2016noise,wang2018nonlinear,wang2019polynomial,antonova2020analytic,karimov2020algebraic}. A wide variety of applications is possible because the approximate basis computation takes a set of noisy points as its input---suitable for the recent data-driven applications---and efficiently computes a set of multivariate polynomials that characterize the given data. Coefficient normalization, where polynomials are normalized to gain a unit coefficient norm, is the most common choice in computer algebra. In contrast, in machine learning, the basis computation of vanishing ideals is performed in a monomial-agnostic manner to sidestep symbolic computation and term orderings~\cite{livni2013vanishing,kiraly2014dual,kera2019spurious}. In this case, efficient access to the coefficients of terms is not possible. Thus, polynomials are handled without proper normalization. A recent study solved this problem by gradient normalization~\cite{kera2020gradient}, which used the gradient (semi-)norm $\sqrt{\sum_{x \in X} \norm{\nabla g(x)}^2}$. Interestingly, the data-dependent nature of gradient normalization provides new properties that could not be realized by other basis computation algorithms. However, the direct application of gradient normalization to the monomial-aware basis computation in computer algebra does not take over these advantages and merely increases the computational cost. Thus, an effective data-dependent normalization remains unexplored for computer-algebraic approaches. In this study, we propose a new normalization, called gradient-weighted normalization, which is a hybrid of coefficient normalization conventionally used in computer algebra and the gradient normalization recently developed in machine learning. Gradient-weighted normalization can be applied to several existing basis computation algorithms for vanishing ideals in computer algebra. In particular, we focus on the approximate computation of border bases because these are the most common choices in the approximate computation~\cite{abbott2008stable,heldt2009approximate,limbeck2013computation} as they have greater numerical stability than the Gr\"obner bases~\cite{stetter2004numerical,fassino2010almost}. We highlight the following advantages of gradient-weighted normalization in the approximate border basis computation. As an example, we analyze the approximate Buchberger--M\"oller (ABM) algorithm~\cite{limbeck2013computation}. \begin{itemize} \item Gradient-weighted normalization realizes an approximate border basis computation that outputs polynomials that are more robust against perturbation on the input points. \item With gradient-weighted normalization, eigendecomposition-based (or singular value decomposition (SVD)-based) approximate border basis computation methods are equipped with scaling consistency; scaling input points does not change the configuration of the output basis and only linearly scales the evaluation values for the input points. \item Gradient-weighted normalization only requires a small modification to an algorithm to work with, causing subtle changes in the analysis of the original one. Unlike gradient normalization, gradient-weighted normalization does not change the order of magnitude of time complexity. \end{itemize} In particular, the second advantage, the scaling consistency, provides us an important insight into approximate basis computation: without it, not only the approximation tolerance $\epsilon$ but also a scaling factor $\alpha$ of points must be properly chosen. In Proposition~\ref{prop:coefficient-normalization-failure}, we prove that, under a mild condition, an approximate basis computation with coefficient normalization always fails if the scaling factor is not properly set. This result implies that even preprocessing of points (e.g., scaling points to range in $[-1, 1]$) for numerical stability can cause a failure of the approximate basis computation. We consider that this study reveals a new direction in approximate border basis computation toward data-dependent normalization and its analysis. \section{Related Work} The gradient of polynomials has been exploited for approximate computation of vanishing ideals in several studies. In~\cite{abbott2008stable}, the first-order approximation (and thus gradient) of polynomials was computed to discover a set of monomials with their evaluation matrix still in full-rank for small perturbations in the points. Similarly, ~\cite{fassino2013simple} considered the first-order approximation of polynomials to compute a low-degree polynomial that approximately passed through the given points in terms of the geometrical distance. However, the former incurred a heavy computational cost and strong sensitivity to the hyperparameter $\gamma$, while the latter only focused on the lowest degree polynomial and did not give a basis. Furthermore, both methods used coefficient normalization. In ~\cite{kera2020gradient}, which is the most similar to this study, polynomials normalized by the gradient norm were considered, which is, to the best our knowledge, the first data-dependent normalization to compute approximately vanishing polynomials. However, their method focuses on monomial-agnostic basis computation, where coefficients of terms are inaccessible. Although this can help when symbolic computation and term ordering are unfavorable, how helpful data-dependent normalization is in the monomial-\textit{aware} setting---the standard in computer algebra---is still unknown. The direct application of gradient normalization in border basis computation cannot fully exploit the advantages of monomial-agnostic basis computation. Furthermore, the method to relate the gradient norm to the coefficient norm, which plays an important role in approximate border bases, remains unclear. In this study, we propose gradient-weighted normalization, which brings all the merits of gradient normalization into monomial-aware computation while retaining the same order of magnitude of the time complexity of algorithms. Furthermore, by exploiting the monomial-aware setting, a more detailed analysis is performed with gradient-weighted normalization. Particularly, the gradient-weighted norm of the terms and polynomials in basis computation can be lower and upper bounded. In addition, the coefficient norm can be upper bounded by the gradient-weighted norm. \section{Preliminaries} We consider a finite set of points $X\subset\mathbb{R}^n$, a polynomial ring $\mathcal{R}_n = \mathbb{R}[x_1,\ldots, x_n]$, and set of terms $\mathcal{T}_n \subset \mathcal{R}_n$, where $x_1,\ldots, x_n$ are indeterminates, throughout the paper. The vanishing ideal $\mathcal{I}(X)\subset\mathcal{R}_n$ is thus zero-dimensional. The definitions of the order ideal and the border basis are based on those in~\cite{kreuzer2005computational,kehrein2005charactorizations}, while the definitions of approximate notions are based on~\cite{heldt2009approximate}. \begin{definition} Given a set of points $X = \{\mathbf{x}_1,\mathbf{x}_2,...,\mathbf{x}_{N}\} \subset \mathbb{R}^n$, with gentle abuse of notation, the \textbf{evaluation vector} of a polynomial $h\in\mathcal{R}_n$ and its gradient $\nabla h$ are defined as follows, respectively. \begin{align*} h(X) & =\mqty(h(\mathbf{x}_{1}) & h(\mathbf{x}_{2}) & \cdots & h(\mathbf{x}_{N}))^{\top}\in\mathbb{R}^{N},\\ \nabla h(X) & = \mqty(\nabla h(\mathbf{x}_{1})^{\top} & \nabla h(\mathbf{x}_{2})^{\top} & \cdots & \nabla h(\mathbf{x}_{N})^{\top})^{\top}\in\mathbb{R}^{nN}. \end{align*} For a set of polynomials $H=\qty{ h_{1},h_{2},\ldots,h_{s}} \subset\mathcal{R}_n$ and the set of their gradients $\nabla H=\qty{ \nabla h_{1},\nabla h_{2},\ldots,\nabla h_{s}}$, each \textbf{evaluation matrix} is defined as \begin{align*} H(X) & = \mqty(h_{1}(X) & h_{2}(X) & \cdots & h_{s}(X))\in\mathbb{R}^{N\times s}, \\ \nabla H(X) & = \mqty(\nabla h_{1}(X) & \nabla h_{2}(X) & \cdots & \nabla h_{s}(X))\in\mathbb{R}^{nN\times s}. \end{align*} \end{definition} \begin{definition} A polynomial $f \in \mathcal{R}_n$ is said to be \textbf{unitary} if the norm of its coefficient vector equals one. \end{definition} \begin{definition} A finite set of terms $\mathcal{O}\subset \mathcal{T}_n$ is called an \textbf{order ideal} if the following holds: if $t\in \mathcal{T}_n$ divides $o\in\mathcal{O}$, then $t \in \mathcal{O}$. The \textbf{border} of $\mathcal{O}$ is defined as $\partial\mathcal{O} = \qty(\bigcup_{k=1}^n x_k\mathcal{O}) \backslash \mathcal{O}$. \end{definition} \begin{definition}\label{def:border-basis} Let $\mathcal{O} \subset \mathcal{T}_n$ be an order ideal. Then, an \textbf{$\mathcal{O}$-border prebasis} $G$ is a set of polynomials in the form $b - \sum_{o\in O} c_o o$, where $b \in \partial \mathcal{O}$, and $c_o \in \mathbb{R}$. If $\mathcal{O}$ is a basis of the $\mathbb{R}$-vector space $\mathbb{R}[x_1,x_2,\ldots, x_n]/I$, then $G$ is called an \textbf{$\mathcal{O}$-border basis} of an ideal $I$. \end{definition} \begin{definition} Given $\epsilon \ge 0$, a polynomial $g\in\mathcal{R}_n$ is said to be an \textbf{$\epsilon$-approximately vanishing} for a set of points $X\subset \mathbb{R}^n$, if $\|g(X)\|\le\epsilon$, where $\|\cdot\|$ denotes the $L_2$ norm. \end{definition} \begin{definition} Given $\epsilon \ge 0$, an ideal $\mathcal{I}\subset\mathcal{R}_n$ is said to be an \textbf{$\epsilon$-approximate vanishing ideal} for a set of points $X\subset \mathbb{R}^n$ if there exists a system of unitary polynomials that generates $\mathcal{I}$ and is $\epsilon$-approximately vanishing for $X$. \end{definition} \begin{remark}\label{rem:O-basis-property} Let us consider the $\mathcal{O}$-border basis $G$ of the vanishing ideal $\mathcal{I}(X)$ of $X\subset\mathbb{R}^n$. The evaluation vectors of the order terms span $\mathbb{R}^{|X|}$. The evaluation vectors of the terms in $\mathcal{O}$ are linearly independent, and $|\mathcal{O}| = |X|$, where $|\cdot|$ denotes the cardinality of set. In the approximate case, the former still holds, and the latter becomes $|\mathcal{O}| \le |X|$. \end{remark} \paragraph{Other notation} We denote the support of a given polynomial by $\mathrm{supp}(\cdot)$ and the set of linear combinations of a given set of terms with coefficients in $\mathbb{R}$ by $\Span{\cdot}$. Further, $\cnorm{\cdot}$ denotes the coefficient norm of a polynomial (i.e., $\cnorm{g}=\sqrt{\sum_{i} c_i^2}$ for $g=\sum_{i}c_it_i$, where $c_i\in\mathbb{R}$ and $t_i\in\mathcal{T}_n$). The total degree of a polynomial is denoted by $\degree{\cdot}$ and $\degreek{k}{\cdot}$ denotes the degree of polynomial with respect to $x_k$. \section{Border bases with gradient-weighted normalization} \begin{definition}\label{def:gradient-norm} The \textbf{gradient norm} of a polynomial $g\in\mathcal{R}_n$ with respect to $X\subset\mathbb{R}^n$ is $\gnorm{g} = \sqrt{\sum_{x \in X} \norm{\nabla g(x)}^2}/Z$, where $Z = \sqrt{\sum_{k=1}^n \mathrm{deg}_k(g)^2}$ and $\gnorm{g}:=0$ if $g$ is a constant polynomial. \end{definition} \begin{definition} The \textbf{gradient-weighted norm}\footnote{Strictly speaking, this is a semi-norm because $\gwnorm{f}=0$ (and $\gnorm{f}=0$) for $f \in \mathcal{R}_n$ does not imply $f=0$. However, all the terms (except 1) and polynomials appearing in the border basis computation do not vanish with respect to the gradient-weighted norm. For simplicity, we refer to $\gwnorm{\cdot}$ (and $\gnorm{\cdot}$) as a norm in this study.} of a polynomial $g = \sum_{i}c_i t_i, (c_i\in\mathbb{R},t_i\in\mathcal{T}_n)$ is defined by $\gwnorm{g} = \sqrt{\sum_{i} c_i^2 \|t_i\|_{g,X}^2}$. If the gradient-weighted norm of $g$ is equal to one, then $g$ is \textbf{gradient-weighted unitary}. \end{definition} \begin{remark} For any term $t\in\mathcal{T}_n$, its gradient norm and gradient-weighted norm are identical, i.e., $\gnorm{t} = \gwnorm{t}$. The proofs in this study work with any constant $Z>0$; however, our choice of $Z$ provides simpler bounds. \end{remark} In general, the gradient-weighted norm and coefficient norms of a polynomial are not always correlated; a large gradient-weighted norm does not necessarily imply a large coefficient norm and vice versa. The following two examples illustrate this: \begin{example}\label{example:zero-gcnorm} Let us consider a polynomial $f = x^2y^2 - c \in \mathbb{R}[x,y], (c\in\mathbb{R})$. The gradient-weighted norm of $f$ is $\gwnorm{f} = 0$ for $X = \{(1, 0), (0, 1)\}$, whereas the coefficient norm $\cnorm{f}=\sqrt{1+c^2}$ can be arbitrarily enlarged by increasing $|c|$. \end{example} \begin{example}\label{example:large-gcnorm} Let us consider a polynomial $f = (x^2 + y^2 - 1)/\sqrt{3} \in \mathbb{R}[x,y]$. The coefficient norm of $f$ is $\cnorm{f}=1$, whereas the gradient-weighted norm for $X = \{(k, 0), (0, k)\}$ is $\gwnorm{f}=2\abs{k}/\sqrt{3}$, which can be arbitrarily enlarged by increasing $|k|$. \end{example} Example~\ref{example:zero-gcnorm} also indicates that normalizing polynomials with their gradient-weighted norms is not always a valid approach because it could lead to zero-division. However, we can prove that gradient-weighted normalization is always valid in border basis computation. First, we prove the following lemma. \begin{lemma}\label{lemma:odiv-is-o} Let $\mathcal{O}\subset\mathcal{T}_n$ be an order ideal. Then, the followings hold. \begin{enumerate} \item $\forall o\in\mathcal{O}\backslash\{1\}$, $\exists k \in \{1,\ldots,n\}$, $\pdiv{o}{x_k}/\degreek{k}{o} \in \mathcal{O}$. \item $\forall b \in \partial\mathcal{O}$, $\exists k \in \{1,\ldots,n\}$, $\pdiv{b}{x_k}/\degreek{k}{b} \in \mathcal{O}$. \end{enumerate} \end{lemma} \begin{proof} \textit{Proof of (1).} Note that, if $o \ne 1$, there always exists some $x_k$ such that $\degreek{k}{o} > 0$ (i.e., $\pdiv{o}{x_k} \ne 0$) because the total degree of $o$ is positive. Let $o = \prod_{l=1}^n x_l^{\alpha_l}\in\mathcal{O}$, where $\alpha_l\in \mathbb{Z}_{\ge 0}$ and $\alpha_k > 0$. Then, $\pdv*{o}{x_k} = \degreek{k}{o}x_k^{\alpha_{k}-1}\prod_{l\ne k} x_l^{\alpha_l}$. Because $x_k^{\alpha_{k}-1}\prod_{l\ne k} x_l^{\alpha_l}$ divides $o$, it holds $\pdiv{o}{x_k}/\degreek{k}{o} \in \mathcal{O}$. \textit{Proof of (2).} For $b \in \partial\mathcal{O}$, we can write $b = x_k o$ for some $x_k$ and $o\in\mathcal{O}$. Thus, $b = x_k \prod_{l=1}^n x_l^{\alpha_l}\in\mathcal{O}$ and $\pdv*{b}{x_k} = (\alpha_k+1)\prod_{l=1}^n x_l^{\alpha_l} = \degreek{k}{b} o$; hence, $\pdiv{b}{x_k}/\degreek{k}{b} = o \in \mathcal{O}$. \end{proof} Now, we prove the validity of gradient-weighted normalization in border basis computation. \begin{proposition}\label{prop:gcnorm-theorem} Let $G \subset\mathcal{R}_n$ be an $\mathcal{O}$-border basis of the vanishing ideal $\mathcal{I}(X)$ of $X\subset\mathbb{R}^n$. Then, the following holds. \begin{enumerate} \item Any $o\in\mathcal{O}\backslash \{1\}$ has a nonzero gradient-weighted norm, i.e., $\gwnorm{o} \ne 0$. \item Any border term $b\in\mathcal{\partial O}$ has a nonzero gradient-weighted norm, i.e., $\gwnorm{b} \ne 0$. \item Any $g\in G$ has a nonzero gradient-weighted norm, i.e., $\gwnorm{g} \ne 0$. \end{enumerate} \end{proposition} \begin{proof} \textit{Proof of (1) and (2).} From Lemma~\ref{lemma:odiv-is-o}, for any non-constant order term and border term, say $t \in \mathcal{O}\cup\partial\mathcal{O}\backslash\{1\}$, there exists a partial derivative with a term that is again an order term. Because order terms are nonvanishing for $X$ (cf. Remark~\ref{rem:O-basis-property}), the gradient-weighted norm of $t$ is nonzero. \textit{Proof of (3).} From Definition~\ref{def:border-basis}, the support of a border basis polynomial $g\in G$ is $\{b\} \cup \mathcal{O}$, where $b$ is a border term. As points (1) and (2), non-constant order terms and border terms have nonzero gradient-weighted norm (equivalently, nonzero gradient norm), and the gradient-weighted norm of $g$ is nonzero. \end{proof} Proposition~\ref{prop:gcnorm-theorem} indicates that gradient-weighted normalization is always valid in the basis computation. Furthermore, gradient-weighted unitary polynomials have a bounded gradient norm. \begin{proposition}\label{prop:gradient-norm-ub} For any gradient-weighted unitary polynomial $g\in\mathcal{R}_n$ for $X\subset\mathbb{R}^n$, it is $\norm{\nabla g(X)} \le \degree{g}\sqrt{|X|}$. \end{proposition} \begin{proof} Let $g=\sum_{i=1}^s c_it_i, (c_i\in\mathbb{R}, t_i\in\mathcal{T}_n)$. In addition, we define an index set $\mathfrak{j}(g) = \{i \in \{1,\ldots, s\} \mid \gwnorm{t_i}\ne 0\}$. Then, \begin{align} \nabla g(\mathbf{x}) &= \sum_{i\in \mathfrak{j}(g)}c_i \gwnorm{t_i} \frac{\nabla t_i(\mathbf{x})}{\gwnorm{t_i}}, \\ &= \sum_{i\in \mathfrak{j}(g)}c_i \gwnorm{t_i} \frac{\nabla t_i(\mathbf{x})}{\norm{\nabla t_i(X)}}\sqrt{\sum_{k=1}^n {\degreek{k}{t_i}^2}}, \end{align} Using $\sqrt{\sum_k {\degreek{k}{t_i}^2}}\le \degree{t_i} \le \degree{g}$, the triangle inequality, and $\gwnorm{g} = \sqrt{\sum_{i=1}^s c_i^2 \gwnorm{t}^2} = 1$, \begin{align} \|\nabla g(\mathbf{x})\| &\le \degree{g} \sum_{i\in \mathfrak{j}(g)}|c_i| \gwnorm{t_i} \frac{\norm{\nabla t_i(\mathbf{x})}}{\norm{\nabla t_i(X)}}, \\ &\le \degree{g} \sqrt{\sum_{i\in \mathfrak{j}(g)}c_i^2 \gwnorm{t_i}^2} \sqrt{\sum_{i\in \mathfrak{j}(g)}\frac{\norm{\nabla t_i(\mathbf{x})}^2}{\norm{\nabla t_i(X)}^2}},\\ &= \degree{g}\sqrt{\sum_{i\in \mathfrak{j}(g)}\frac{\norm{\nabla t_i(\mathbf{x})}^2}{\norm{\nabla t_i(X)}^2}}, \end{align} where at the second inequality, we employed the Cauchy--Schwarz inequality. Thus, \begin{align} \norm{\nabla g(X)} &= \sqrt{\sum_{\mathbf{x}\in X} \norm{\nabla g(\mathbf{x})}^2},\\ &\le \degree{g}\sqrt{\sum_{\mathbf{x}\in X}\sum_{i\in \mathfrak{j}(g)}\frac{\norm{\nabla t_i(\mathbf{x})}^2}{\norm{\nabla t_i(X)}^2}}, \\ &= \degree{g} \sqrt{\sum_{i\in \mathfrak{j}(g)} 1}, \\ % &\le \degree{g}\sqrt{|X|}. \end{align} At the last inequality, we used $\abs{\mathrm{supp}(g)\backslash \{1\}}\le\abs{\mathcal{O}}\le \abs{X}$. \end{proof} \begin{remark} If we use $Z = 1$ in Definition~\ref{def:gradient-norm}, the inequality in Proposition~\ref{prop:gradient-norm-ub} $\norm{\nabla g(X)} \le \sqrt{|X|}$, which makes the bound degree-independent. \end{remark} Proposition~\ref{prop:gradient-norm-ub} implies that, for small perturbation $\mathbf{p}$ on $\mathbf{x}$, the two evaluation values $g(\mathbf{x})$ and $g(\mathbf{x}+\mathbf{p})$ are close to each other and the difference can be bounded by the constant scaling of the magnitude of the perturbation. Later, this will be confirmed by Proposition~\ref{prop:perturbation}. However, this is not the case with coefficient normalization because the (coefficient-)unitary polynomial does not necessarily indicate a small gradient (cf.~Example~\ref{example:large-gcnorm}). Therefore, an approximately vanishing polynomial $g$ for a perturbed point $\mathbf{x}$ can be overfitting to it, and $g$ may not be well approximately vanishing for the unperturbed point $\mathbf{x}^{*} = \mathbf{x} - \mathbf{p}$, where $\mathbf{p} := \mathbf{x} - \mathbf{x}^{*}$. \section{Approximate computation of border bases with gradient-weighted normalization} We will now present a method to introduce gradient-weighted normalization into the existing approximate border basis constructions (particularly, the approximate vanishing ideal~(AVI)-family methods). Almost all the AVI-family methods rely on solving eigenvalue problems (or SVD). Gradient-weighted normalization can be introduced by simply replacing these problems by generalized eigenvalue problems. Other methods that do not rely on eigenvalue problems solve simple quadratic programs (e.g., least-squares problems). Therefore, we consider that the proposed method can be integrated with these methods as well, owing to its simplicity. To avoid an unnecessary abstract discussion, we adopted the ABM algorithm~\cite{limbeck2013computation} as an example because it is simple and offers various advantages over the AVI algorithm. \subsection{The ABM algorithm with gradient-weighted normalization}\label{sec:AMB-with-gwn} \begin{algorithm}[t] \DontPrintSemicolon \KwInput{$X, \epsilon, \sigma$} \KwOutput{$G, \mathcal{O}$} $G = \{\}, \mathcal{O} = \{1\}$\\ \For{$d=1,2,\ldots $}{ $L= \qty{ b\in \mathcal{\partial\mathcal{O}} \mid \degree{b} = d}$ \tcp*{Assuming the terms are in the ascending order w.r.t. $\sigma$} \If{$|L| = 0$}{ Return $G, \mathcal{O}$ and terminate. } \For{$b$ in $L$}{ Solve the generalized eigenvalue problem~Eq.~\eqref{eq:gep} and obtain $(\lambda_{\min}, \mathbf{v}_{\min})$. \If{$\sqrt{\lambda} \le \epsilon$}{ \tcc{$\mathcal{O}=\{o_1,o_2,\cdots, o_s\}$ and $\mathbf{v}_{\min}=(v_1,\ldots,v_{s+1})^{\top}$} $g := v_1b + v_2o_1 + \cdots +v_{s+1}o_{s}$\\ $G = G \cup \{g\}$ } \Else{ $\mathcal{O} = \mathcal{O}\cup \{b\}$ } } } \caption{\\ The ABM algorithm with gradient-weighted normalization}\label{alg:ABMGN} \end{algorithm} Given a finite set of points $X\subset\mathbb{R}^n$, an error tolerance $\epsilon\ge 0$, and a degree-compatible term ordering $\sigma$, the ABM algorithm collects the order terms and approximately vanishing polynomials from lower to higher degrees. At degree 0, $\mathcal{O} = \{1\}$ and $G=\{\}$ are prepared. At degree $d\ge 1$, the degree-$d$ terms are prepared as $L = \{b \in \partial\mathcal{O} \mid \degree{b} = d\}$. If $L$ is empty, the algorithm outputs $(\mathcal{O},G)$ and terminates; otherwise, the following steps \textbf{S1--S3} are repeated until $L$ becomes empty. \begin{itemize} \item[\textbf{S1}] Select the smallest\footnote{In the original paper~\cite{limbeck2013computation}, the largest term is selected. We consider the smallest term should be selected first because the term $b$ is a potential leading term (or border term), and thus must always be larger than the terms in the tentative $\mathcal{O}$.} $b \in L$ with respect to $\sigma$ and remove $b$ from $L$. \item[\textbf{S2}] Let $M, D$ be $M = \mqty(b(X) & O(X))$ and \begin{align} D &= \mathrm{diag}\qty(\gwnorm{b}, \gwnorm{o_1},\ldots, \gwnorm{o_s}), \end{align} where $\mathcal{O} = \{o_1,\ldots, o_s\}$, and $\mathrm{diag}(\cdots)$ denotes a diagonal matrix with the given entries in its diagonal. Solve the following generalized eigenvalue problem: \begin{align}\label{eq:gep} M^{\top}M\mathbf{v}_{\min} &= \lambda_{\min}D^2\mathbf{v}_{\min}, \end{align} where $\lambda_{\min}$ and $\mathbf{v}_{\min}$ are the smallest generalized eigenvalue and the corresponding generalized eigenvector, respectively. \item[\textbf{S3}] If $\sqrt{\lambda_{\min}} \le \epsilon$, Define a new polynomial, \begin{align}\label{eq:vanishing-polynomial} g = v_1b + v_2o_1 + v_3o_2 + \cdots + v_{s+1}o_s, \end{align} where $\mathbf{v}_{\min} = (v_1,\ldots,v_{s+1})^{\top}$ and $G$ is updated by $G = G \cup \{g\}$. Otherwise, update $\mathcal{O}$ by $\mathcal{O} = \mathcal{O} \cup \{b\}$. \end{itemize} Once $L$ becomes empty, we proceed to the next degree $d+1$ and construct a new $L$. If the new $L$ is empty, the algorithm outputs $(\mathcal{O},G)$ and terminates. \begin{remark}\label{rem:diff-from-original-ABM} The only difference from the original ABM algorithm is that a generalized eigenvalue problem of $(M^{\top}M, D^2)$ instead of the SVD of $M$ (equivalently, an eigenvalue problem of $M^{\top}M$) is solved. If $D$ is set to an identity matrix, the algorithm is reduced to the original one. Because of this minor difference, most of the analysis (including the termination) on the original ABM algorithm remains valid. The order of magnitude of time complexity of algorithms does not change either. \end{remark} \begin{proposition}\label{prop:abmgn} The following always holds true during the process of the ABM algorithm with gradient-weighted normalization. \begin{enumerate} \item Any gradient-weighted unitary polynomial $h \in \Span{\mathcal{O}}$ is not $\epsilon$-approximately vanishing for $X$. \item In Eq.~\eqref{eq:vanishing-polynomial}, $g$ is gradient-weighted unitary with a nonzero coefficient on $b$ and $\sqrt{\lambda_{\min}}$-approximately vanishing for $X$. % \end{enumerate} \end{proposition} \begin{proof} \textit{Proof of (1).} A gradient-weighted unitary polynomial in $\Span{\mathcal{O}}$ with minimal extent of vanishing can be obtained by solving a generalized eigenvalue problem $(O(X)^{\top}O(X), D^{2})$, where $D$ is a diagonal matrix with the gradient-weighted norm of the terms in $\mathcal{O}$ as the diagonal entries. However, by construction, the square root of its smallest generalized eigenvalue $\lambda_{\min}$ is larger than $\epsilon$. More specifically, during the process of the algorithm, with a tentative border term $b$ and tentative order ideal $\widetilde{\mathcal{O}}$ such that $\mathcal{O}=\{b\} \cup \widetilde{\mathcal{O}}$, the generalized eigenvalue problem of $(O(X)^{\top}O(X), D^{2})$ was already solved using Eq.~(\ref{eq:gep}). Subsequently, $\widetilde{\mathcal{O}}$ was extended to $\mathcal{O}$ because of $\sqrt{\lambda_{\min}} > \epsilon$. \textit{Proof of (2).} We prove the claim by induction. At the initialization of the algorithm, the claim holds true. Assume that the claim holds till a certain point in the process of the ABM algorithm, and we have $\mathcal{O},G, b$ at \textbf{S1}. By solving Eq.~\eqref{eq:gep} at \textbf{S2}, we obtain the coefficient vector $\mathbf{v}_{\min}$ and $g = bv_1 + v_2o_1 + v_3o_2 + \cdots + v_{s+1}o_s$. Note that solving Eq.~\eqref{eq:gep} minimizes $\norm{g(X)}^2=\mathbf{v}_{\min}^{\top}M^{\top}M\mathbf{v}_{\min}=\lambda_{\min}$ with the constraint $\gwnorm{g}^2=\mathbf{v}_{\min}^{\top}D^2\mathbf{v}_{\min}=1$. Thus, $g$ is gradient-weighted unitary and $\sqrt{\lambda_{\min}}$-approximately vanishing. From (1), no gradient-weighted unitary polynomial with support $\mathcal{O}$ is $\epsilon$-approximately vanishing. Thus, the leading coefficient $b$ in $g$ is nonzero. \end{proof} Conceptually, gradient-weighted normalization normalizes a polynomial $h = \sum_{i}v_it_i$ as $h = \sum_{i}v_i \frac{t_i}{\|\nabla t_i(X)\|}$, where $v_i\in\mathbb{R}, t_i\in\mathcal{T}_n$. Note that this presentation is inaccurate because $\|\nabla 1(X)\| = 0$, but it provides an intuition of gradient-weighted normalization. Namely, around any point $\mathbf{x}\in X$, each term $t_i(\mathbf{x}) / \|\nabla t_i(X)\|$ behaves like a linear function because the ``degree'' of the denominator is roughly $\degree{t} - 1$ (more intuitively, if $t_i$ is a univariate, $\mathrm{d}t_i(\mathbf{x})/\mathrm{d}x$ is linear). Therefore, the polynomial $h$ behaves like a linear function around the points of $X$. This intuition motivated the several important analyses in this study, including Proposition~\ref{prop:perturbation} and Theorem~\ref{thm:scaling-consistency}. The following theorem argues that the ABM algorithm with gradient-weighted normalization can benefit from the properties that are nearly identical to those of the original ABM algorithm~(Theorem~4.3.1 in~\cite{limbeck2013computation}). \begin{theorem}\label{thm:abmgn} Given a finite set of points $X\subset\mathbb{R}^n$, $\epsilon\ge 0$, and a degree-compatible term ordering $\sigma$, the ABM algorithm with gradient-weighted normalization~(Algorithm~\ref{alg:ABMGN}) computes $G\subset\mathcal{R}_n$ and $\mathcal{O}\subset\mathcal{T}_n$, which have the following properties: \begin{enumerate} \item All the polynomials in $G$ are gradient-weighted unitary and $G$ generates an $\epsilon$-approximately vanishing ideal of $X$. \item No gradient-weighted unitary polynomial that vanishes $\epsilon$-approximately on $X$ exists in $\Span{\mathcal{O}}$. \item If $\mathcal{O}$ is an order ideal of terms, then the set $\widetilde{G} = \{1/\mathrm{LC}_{\sigma}(g) g \mid g \in G\}$ is an $\mathcal{O}$-border prebasis, where $\mathrm{LC}_{\sigma}(\cdot)$ is the leading coefficient of a polynomial in the ordering $\sigma$. \item If $\epsilon = 0$, the algorithm produces the same results as the Buchberger--M\"oller algorithm for border bases with gradient-weighted normalization. \end{enumerate} \end{theorem} \begin{proof}[Proof of Theorem~\ref{thm:abmgn}] Both (1) and (2) has been proved in Proposition~\ref{prop:abmgn}. By Proposition~\ref{prop:abmgn}, the coefficient of the leading term (border term) of polynomials in $G$ is nonzero; thus, by construction in Algorithm~\ref{alg:ABMGN}, (3) holds~(refer to the proof of the original ABM algorithm;~\cite{limbeck2013computation}) As for (4), the proof follows from the original proof of the ABM algorithm by simply replacing the eigenvalue problem with the generalized eigenvalue problem~(cf. Remark~\ref{rem:diff-from-original-ABM}). \end{proof} The main difference between this theorem and the original one with coefficient normalization is as follows: in Theorem~\ref{thm:abmgn}, (i) the unitarity of polynomials is based on the gradient-weighted norm instead of the coefficient norm; and (ii) it lacks the claim that $\widetilde{G}$ is a \textit{$\delta$-approximate border basis} in terms of the gradient-weighted norm and \textit{$\eta$-approximate border basis} in terms of the coefficient norm, where $\delta, \eta$ are some constants. We have eliminated the claim because the proof is lengthy for the limitation of pages. Instead, we here demonstrate that the approximation of a border basis can be discussed with the coefficient norm, even when the basis is computed with the gradient-weighted norm. This will be a key lemma to prove the claim mentioned above. As illustrated in Examples~\ref{example:zero-gcnorm} and~\ref{example:large-gcnorm}, the gradient-weighted and coefficient norms are not generally correlated. However, we can show that the gradient-weighted norm can impose an upper bound on the coefficient norm in approximate border basis computation. We first prove a lemma. \begin{lemma}\label{lemma:gradient-norm-lb} Let $\mathcal{O}\subset\mathcal{T}_n$ be an order ideal, which is obtained by the ABM algorithm with gradient-weighted normalization for $X\subset\mathbb{R}^n$ and $\epsilon \ge 0$. Then, for any $o\in\mathcal{O}\backslash\{1\}$, it holds $\gwnorm{o} > \epsilon^{\mathrm{deg}(o)-1}\sqrt{|X|}$. \end{lemma} \begin{proof} We prove the claim by induction. At $d=1$, the claim holds because of $\|\nabla o(X)\|= \sqrt{|X|}$. Next, assume at degree $d \ge 1$, the first claim holds; that is, for any $o\in \mathcal{O}$ of degree $d$, it is $\gwnorm{o} > \epsilon^{d-1}\sqrt{|X|}$. Let $\mathfrak{i}(o)\subset \{1,\ldots ,n\}$ be the index set such that $x_k$ can divide $o$ for $k\in \mathfrak{i}(o)$. For each $o \in \mathcal{O}$ and $k\in \mathfrak{i}(o)$, let $o^{(k)}$ be the term such that $o = x_ko^{(k)}$. For any $o \in \mathcal{O}$ of degree $d+1$, we obtain \begin{align} \gwnorm{o}^2 &= \frac{1}{\sum_{k=1}^n \mathrm{deg}_k(o)^2}\sum_{k\in \mathfrak{i}(o)} \norm{\frac{\partial o}{\partial x_k}(X)}^2, \\ &= \frac{1}{\sum_{k=1}^n \mathrm{deg}_k(o)^2}\sum_{k\in \mathfrak{i}(o)} \mathrm{deg}_k(o)^2 \norm{o^{(k)}(X)}^2, \\ &= \frac{1}{\sum_{k=1}^n \mathrm{deg}_k(o)^2}\sum_{k\in \mathfrak{i}(o)} \mathrm{deg}_k(o)^2 \frac{\norm{o^{(k)}(X)}^2} {\gwnorm{o^{(k)}}^2} \gwnorm{o^{(k)}}^2, \\ &> \epsilon^{2d} |X|. \end{align} For the first equality, we used $\sum_{k=1}^n \norm{\frac{\partial o}{\partial x_k}(X)}^2 = \sum_{k\in \mathfrak{i}(o)} \norm{\frac{\partial o}{\partial x_k}(X)}^2$ because $\pdiv{o}{x_k} = 0$ for $k\notin \mathfrak{i}(o)$. For the second equality, we used $\pdiv{o}{x_k} = \mathrm{deg}_k(o)o^{(k)}$. For the last inequality, we used $\sum_{k=1}^n\degreek{k}{o}^2 = \sum_{k\in \mathfrak{i}(o)}\degreek{k}{o}^2$, $\norm{o^{(k)}(X)}/\gwnorm{o^{(k)}} > \epsilon$, and the assumption at degree $d$. Thus, for any $o\in\mathcal{O} \backslash\{1\}$, it follows that $\norm{\nabla o(X)} > \epsilon^{\mathrm{deg}(o)-1} \sqrt{|X|}$. \end{proof} Now, we upper bound the coefficient norm of an approximate vanishing polynomial by its gradient-weighted norm. \begin{proposition}\label{prop:coef-norm-ub-by-gwnorm} % Let $(\mathcal{O}, G)\subset \mathcal{T}_n\times \mathcal{R}_n$ be the output of the ABM algorithm for $X\subset \mathbb{R}^n$ and $\epsilon \ge 0$. For any $g\in G$, the following holds: \begin{align} \cnorm{g} &< \frac{\sqrt{\gwnorm{g}^2+c_0^2}}{\min\{\epsilon^{\degree{g}-1}, 1\}\sqrt{|X|}}, \end{align} where $c_0$ is the coefficient of the constant term of $g$. Furthermore, if $\mathbf{0}\in X$, then \begin{align} \cnorm{g} &< \frac{\sqrt{\gwnorm{g}^2+\epsilon^2}}{\min\{\epsilon^{\degree{g}-1}, 1\}\sqrt{|X|}}. \end{align} \end{proposition} \begin{proof} Let $g = \sum_{i=0}^{s}c_i t_i$, where $c_i \in \mathbb{R}$ and $t_0 = 1$. Let $\mathbf{c} = \qty(c_1, \ldots, c_{s})^{\top}$ and $D = \mathrm{diag}(\gwnorm{t_1}, \gwnorm{t_2}, \ldots, \gwnorm{t_{s}})$ (note that $c_{0}$ and $\gwnorm{t_0}$ are excluded). Then, \begin{align} \gwnorm{g}^2 &= \mathbf{c}^{\top}D^2\mathbf{c}, \\ &\ge \min_{i\in\{1,\ldots, s\}} \gwnorm{t_i}^2 \norm{\mathbf{c}}^2, \\ &= \min_{i\in\{1,\ldots, s\}} \gwnorm{t_i}^2 (\cnorm{g}^2 - c_0^2). \end{align} From Lemma~\ref{lemma:gradient-norm-lb}, we have $\gwnorm{t_i} > \epsilon^{\degree{t_i}-1}\sqrt{|X|}$ and obtain \begin{align} \cnorm{g} &< \frac{\sqrt{\gwnorm{g}^2+c_0^2}}{\min\{\epsilon^{\degree{g}-1}, 1\}\sqrt{|X|}} \end{align} If $\mathbf{0} \in X$, then $g$ is $\epsilon$-approximately vanishing for $\mathbf{0}$ (i.e., $|c_0| \le \epsilon$). \end{proof} \subsection{Advantages of gradient-weighted normalization} Gradient-weighted normalization has two advantages. The first one is robustness against perturbations on the input points. \begin{proposition}\label{prop:perturbation} Let $(\mathcal{O}, G)\subset \mathcal{T}_n\times \mathcal{R}_n$ be the output of the ABM algorithm for $X = \{\mathbf{x}_1,\ldots, \mathbf{x}_N\}\subset\mathbb{R}_n$ and $\epsilon \ge 0$. Let $P = \{\mathbf{p}_1,\ldots, \mathbf{p}_N\} \subset\mathbb{R}_n$ be a set of small perturbations. If $g \in G$ is gradient-weighted unitary, then, \begin{align} g(X+P) \le \epsilon + \norm{P}_{\max} \degree{g}\sqrt{|X|} + o(\norm{P}_{\max}), \end{align} where $\|P\|_{\max} = \max_{\mathbf{p}\in P} \norm{\mathbf{p}}$, and $o(\cdot)$ is the Landau's small o. \end{proposition} \begin{proof} Using the Taylor expansion and the triangle inequality, we get \begin{align} \|g(X+P)\| % % % % % &\le \norm{g(X)} + \norm{P}_{\max} \norm{\nabla g(X)} + o(\norm{P}_{\max}), \\ &\le \epsilon + \norm{P}_{\max} \degree{g}\sqrt{|X|} + o(\norm{P}_{\max}), \end{align} where, at the last inequality, we used Proposition~\ref{prop:gradient-norm-ub}. \end{proof} \begin{remark} The inequality in Proposition~\ref{prop:perturbation} becomes $g(X+P) \le \epsilon + \norm{P}_{\max}\sqrt{|X|} + o(\norm{P}_{\max})$, if we use $Z=1$ in Definition~\ref{def:gradient-norm}. \end{remark} Another advantage of using gradient-weighted normalization is that it enables the ABM algorithm to output similar bases before and after scaling input points. \begin{theorem}\label{thm:scaling-consistency} Let $X\subset\mathbb{R}^n$ be a set of points, $\epsilon > 0$, $\alpha \ne 0$, and $\sigma$ be a degree-compatible term ordering. Suppose that $(X, \epsilon, \sigma)$ and $(\alpha X, \abs{\alpha}\epsilon, \sigma)$ are given; the ABM algorithm with gradient-weighted normalization outputs $(\mathcal{O}, G)$ and $(\widehat{\mathcal{O}}, \widehat{G})$, respectively. Then, it holds that $\mathcal{O} = \widehat{\mathcal{O}}$. In addition, a one-to-one correspondence exists between $G$ and $\widehat{G}$. For the corresponding polynomials $g \in G$ and $\widehat{g} \in \widehat{G}$, the following holds: \begin{align} \widehat{g}(\alpha X) &= \alpha g(X). \end{align} Furthermore, it holds that $\mathrm{supp}(g) = \mathrm{supp}(\widehat{g})$ and the coefficients of $t \in \mathrm{supp}(g)$ in $g$ and $\widehat{g}$, say $v_t, \widehat{v}_t$, satisfy $v_t = \alpha^{\degree{t}-1} \widehat{v}_t$. \end{theorem} \begin{proof} Let us consider two processes of the ABM algorithm; one for $(X,\epsilon, \sigma)$ and the other for $(\alpha X,\abs{\alpha}\epsilon, \sigma)$. We use the notations in Algorithm~\ref{alg:ABMGN} for the former process and add $\widehat{\cdot}$ to the notations in the latter process. At the initialization, the claim holds because $\mathcal{O} = \widehat{\mathcal{O}} = \{1\}$ and $G = \widehat{G} = \{\}$. Assume that the claim holds true for several iterations, and now we are at \textbf{S1} with $\mathcal{O} = \widehat{\mathcal{O}}$ and $(G, \widehat{G})$ that satisfy the correspondence, and $L = \widehat{L}$. Note that, for any term $t\in\mathcal{T}_n$, $t(\alpha X) = \alpha^{\degree{t}}t(X)$, and $\gwnormx{t}{\alpha X} = \alpha^{\degree{t}-1}\gwnorm{t}$. Thus, $t(\alpha X)/\gwnormx{t}{\alpha X} = \alpha t(X)/\gwnormx{t}{X}$. Therefore, by defining $S=\mathrm{diag}(\alpha^{\degree{b}}, \alpha^{\degree{o_1}}, \ldots, \alpha^{\degree{o_s}})$, \begin{align} \widehat{M}^{\top}\widehat{M}\widehat{\mathbf{v}}_{\min} &= \widehat{\lambda}_{\min} \widehat{D}^2 \widehat{\mathbf{v}}_{\min},\\ % % \iff M^{\top}MS\widehat{\mathbf{v}}_{\min} &= \widehat{\lambda}_{\min} \alpha^{-2} D^2S\widehat{\mathbf{v}}_{\min}, \end{align} from which we obtain $\lambda_{\min} = \alpha^{-2} \widehat{\lambda}_{\min}$ and $\mathbf{v}_{\min}\propto S\widehat{\mathbf{v}}_{\min}$ at \textbf{S2}. This indicates that thresholding $\sqrt{\lambda_{\min}}$ by $\epsilon$ in the first process is equivalent to thresholding $\sqrt{\widehat{\lambda}_{\min}}$ by $|\alpha|\epsilon$ in the second one. Furthermore, by comparing the constraint of each generalized eigenvalue problem, $1 = \mathbf{v}_{\min}^{\top}D^2 \mathbf{v}_{\min}$ and $1 = \widehat{\mathbf{v}}_{\min}^{\top}\widehat{D}^2 \widehat{\mathbf{v}}_{\min}$, we obtain $\mathbf{v}_{\min}=\alpha^{-1} S\widehat{\mathbf{v}}_{\min}$. Thus, at \textbf{S3}, the coefficients of the $i$-th term $t_i$ of $g$ and $\widehat{g}$ are related as $v_i = \alpha^{\degree{t_i}-1}\widehat{v}_i$. In summary, if $g = v_1b + v_2o_1 + \cdots, v_{s+1}o_{s}$ is $\epsilon$-approximately vanishing for $X$, then $\widehat{g} = \widehat{v}_1\widehat{b} + \widehat{v}_2\widehat{o}_1 + \cdots, \widehat{v}_{s+1}\widehat{o}_{s}$ is $\abs{\alpha}\epsilon$-approximately vanishing for $\alpha X$, and vice versa. If $b$ is appended to $\mathcal{O}$, then it should also be appended to $\widehat{\mathcal{O}}$. Thus, $\mathcal{O} = \widehat{\mathcal{O}}$; otherwise, $g$ and $\widehat{g}$ are appended to $G$ and $\widehat{G}$, respectively. Hence, $G$ and $\widehat{G}$ maintain the correspondence. \end{proof} \begin{example}\label{example:scaling-consistency} Let $X$ be a set of six perturbed sample points from a unit circle: \begin{align} X = \{(0.39, 0.89), (-0.54, 0.93), (-0.94, -0.20), (-0.58,-0.91), (0.38,-081), (0.82,-0.01)\}. \end{align} Given $X$, $\epsilon=0.1$, and the graded reverse lexicographic order $\sigma$, the ABM algorithm with gradient normalization computes $G$, which contains a single quadratic polynomial $g$ that is close to a unit circle, two cubic polynomials, and two degree-four polynomials. For $(\alpha X, \alpha\epsilon, \sigma)$, where $\alpha = 0.1$, the ABM algorithm with gradient normalization gives $\widehat{G}$, which has the same configuration as $G$. Let $\widehat{g} \in \widehat{G}$ be the quadratic polynomial. \begin{align} g &= 0.491x^2 - 0.0322xy + 0.350y^2 + 0.0866x - 0.0165y - 0.382,\\ \widehat{g} &= 4.91x^2 - 0.322xy + 3.50y^2 + 0.0866x - 0.0165y - 0.0382. \end{align} Notably, the coefficients of the constant, linear, and quadratic terms in $g$ are $0.1^{-1}$, $0.1^{0}$, and $0.1$ times of those in $\widehat{g}$, respectively. Meanwhile, the ABM algorithm with coefficient normalization outputs the basis sets in different configurations for $(X, \epsilon, \sigma)$ and $(\alpha X, \alpha\epsilon, \sigma)$. \end{example} Theorem~\ref{thm:scaling-consistency} works even in the approximate case (i.e., $\epsilon>0$) and provides a theoretical justification for the scaling of the points at the preprocessing stage. That is, even if we scale a set of points before computing a basis, e.g., for the numerical stability, there is a corresponding basis for the set of points before the scaling, and this basis can be retrieved from the basis computed from the scaled points. This is not the case with coefficient normalization. \begin{proposition}\label{prop:coefficient-normalization-failure} Let $X \subset\mathbb{R}^n$ be a finite set of points. Let $\epsilon, \epsilon_{\alpha} > 0$ and $\alpha \ne 0$. Let $\sigma$ be a degree-compatible term ordering. Suppose the ABM algorithm with coefficient normalization receives $(X, \epsilon, \sigma), (\alpha X, \epsilon_{\alpha}, \sigma)$ and outputs $(\mathcal{O}, G), (\mathcal{O}_{\alpha}, G_{\alpha})$, respectively. If $G$ contains polynomials of different degrees, and if polynomials in $G$ are not strictly vanishing for $X$, then, there exists an $\alpha\ne 0$ such that $\mathcal{O} \ne \mathcal{O}_{\alpha}$ (consequently, $G \ne G_{\alpha}$). \end{proposition} \begin{proof} Recall Remark~\ref{rem:diff-from-original-ABM}. The ABM algorithm with coefficient normalization is Algorithm~\ref{alg:ABMGN} with an SVD of $M$ at Eq.~(\ref{eq:gep}). Now, we consider two processes of the ABM algorithm; one is for $X$ and the other is for $\alpha X$. Let $g$ be a polynomial of the lowest degree in $G$. Let $\mathcal{M}_g = \{b_g\} \cup \mathcal{O}_{g}$ be a union of the border term of $g$ and the tentative order ideal when $g$ is obtained in the process for $X$. To obtain $g$, an SVD is performed to $\mathcal{M}_g(X)$. Now, suppose that, in the process for $\alpha X$, $\epsilon_{\alpha}$ is properly set to obtain $\mathcal{O}_g$, and now $\mathcal{M}_g(\alpha X)$ is to be dealt with by an SVD. Note that if such $\epsilon_{\alpha}$ does not exist, the claim already holds true. Let $\Sigma = \text{diag}\qty(\alpha^{\degree{t_1}},\alpha^{\degree{t_2}}, \ldots, \alpha^{\degree{t_s}})$, where $\mathcal{M}_g = \{t_1, t_2, \ldots, t_s\}$. Using $\mathcal{M}_g(\alpha X) = \mathcal{M}_g(X)\Sigma$, \begin{align} \sigma_{\min}\qty(\mathcal{M}_g(\alpha X )) &\ge \sigma_{\min}\qty(\mathcal{M}_g(X))\sigma_{\min}\qty(\Sigma), \\ &= \sigma_{\min}\qty(\mathcal{M}_g(X))\min\qty{1, |\alpha|^{\tau}}, \end{align} where $\sigma_{\min}(\cdot)$ denotes the smallest singular value of matrix, and $\tau = \degree{g}$. When $|\alpha| \le 1$, we have $\sigma_{\min}\qty(\mathcal{M}_g(\alpha X )) \ge \|g(X)\||\alpha|^{\tau}$. Thus, $\epsilon_{\alpha}$ must satisfy $\epsilon_{\alpha} \ge |\alpha|^{\tau}\|g(X)\|$. Next, by the assumption, the ABM algorithm does not terminate at degree $\tau$. Let $\omega > \tau$ be the highest degree of order term $o\in \mathcal{O}$. Let $\mathcal{M}_{\omega}$ be a union of a tentative border term and tentative order ideal to obtain such $o$ through an SVD. Note that the smallest singular value of a matrix can be upper bounded by the minimum norm of the column vectors of the matrix. Thus, $\sigma_{\min}(\mathcal{M}_{\omega}(X))$ can be upper bounded by the norm of the evaluation vector of a certain degree-$\omega$ order term $o_{\omega}$. Since $\|o_{\omega}(\alpha X)\|= |\alpha|^{\omega} \|o_{\omega}(X)\|$, we have $\sigma_{\min}\qty(\mathcal{M}_{\omega}(\alpha X)) \le |\alpha|^{\omega} \|o_{\omega}(X)\|$. To summarize, $\epsilon_{\alpha}$ must satisfy \begin{align} |\alpha|^{\tau}\|g(X)\| \le \epsilon_{\alpha} < |\alpha|^{\omega}\|o_{\omega}(X)\|.\label{eq:eps-range} \end{align} In other words, if $|\alpha|^{\omega}\|o_{\omega}(X)\| \le |\alpha|^{\tau}\|g(X)\|$, i.e., if \begin{align} |\alpha| &\le \qty(\frac{\|g(X)\|}{\|o_{\omega}(X)\|})^{1/(\omega-\tau)}, \label{eq:alpha-ub} \end{align} then there exists no $\epsilon_{\alpha}$ such that $\mathcal{O}= \mathcal{O}_{\alpha}$. Note that $\|o_{\omega}(X)\| > \epsilon \ge \|g(X)\|$ and $\omega > \tau$. Thus, the upper bound is nontrivial (tighter than $|\alpha|\le 1$). \end{proof} Proposition~\ref{prop:coefficient-normalization-failure} implies that approximate computation of border basis with coefficient normalization is scale-sensitive. Particularly, the upper bound in Eq.~\eqref{eq:alpha-ub} becomes tighter when the gap of the two degrees---the highest degree of order terms and the lowest degree of basis polynomials---increases. Even one recovers from $X$ a good approximate border basis that is close to the true one, this might not be the case with $\alpha X$, and vice versa (and such $\alpha \ne 0$ always exists!). Thus, the scaling parameter $\alpha$, as well as $\epsilon$, has to be carefully selected. The importance of the choice of scaling parameter from an algebraic perspective has not been discussed in literature. In \cite{heldt2009approximate}, the scaling is discussed in the numerical experiments from a numerical perspective such as computational time and maximum mean extent of vanishing, concluding that scaling points to $[-1, 1]^n$ is good for the numerical quality of computation. The advantage of gradient-weighted normalization is that one can avoid such dependency on scaling, and a set of points can be arbitrarily scaled for numerically stable computation. \section{Numerical experiments}\label{sec:experiment} Here, we demonstrate that the scaling of data points is a crucial factor in the success of the approximate computation of border bases. First, using three datasets, we tested the ABM algorithm's ability to retrieve the target sets of polynomials from the scaled perturbed points. We observed that coefficient normalization is sensitive to scaling, whereas the gradient-weighted normalization is not owing to its scaling consistency (Theorem~\ref{thm:scaling-consistency}). Second, through a small numerical experiment, we show that the valid range of the scaling parameter follows Proposition~\ref{prop:coefficient-normalization-failure}. \subsection{Configuration retrieval test} In the approximate setting, the target polynomial system and a system calculated from the perturbed points cannot be compared directly because the number of polynomials in the two systems may be different. We performed the following simple test. \begin{definition}[configuration retrieval test] Let $G \subset\mathbb{R}[x_1,\ldots, x_n]$ be a finite set of polynomials and let $T$ be the maximum degree of polynomials in $G$. An algorithm $\mathcal{A}$, which calculates a set of polynomials $\widehat{G}\subset \mathbb{R}[x_1,\ldots, x_n]$ from a set of points $X\subset\mathbb{R}^n$, is considered to successfully retrieve the configuration of $G$ if $\forall t = 0, 1, \ldots, T, |G_t| = |\widehat{G}_t|$ is satisfied, where $G_t$ and $\widehat{G}_t$ denote the sets of degree-$t$ polynomials in $G$ and $\widehat{G}$, respectively. \end{definition} The configuration retrieval test verifies if the algorithm outputs a set of polynomials that has the same configuration as the target system up to the maximum degree of polynomials in the target system. This is a necessary condition for a good approximate basis construction. Furthermore, to circumvent choosing $\epsilon$ of the ABM algorithm, we performed a linear search. Thus, a run of the ABM algorithm is considered to have passed the configuration retrieval test if there exists a proper $\epsilon$. We considered three affine varieties. \begin{align} V_1 &= \qty{(x,y) \in \mathbb{R}^2 \mid (x^2+y^2)^3 - 4x^2y^2 = 0}, \\ V_2 &= \qty{(x, y, z) \in \mathbb{R}^3 \mid x + y - z = 0, x^3 - 9(x^2 - 3y^2) = 0}, \\ V_3 &= \qty{(x, y, z) \in \mathbb{R}^3 \mid x^2-y^2z^2+z^3 = 0}. \end{align} We calculated the Gr\"{o}bner and border bases (by the ABM algorithm with two normalization methods) and confirmed that for each dataset, all the bases had the same configuration. Using its parametric representation, fifty points (say, $X_i^{*}$) were sampled from each $V_i$. Each $X_i^{*}$ was preprocessed by subtracting the mean and scaling to make average $L_2$ norm of points unit. The sampled points were then perturbed by an additive Gaussian noise $\mathcal{N}(\mathbf{0}, \nu I)$, where $I$ denotes the identity matrix and $\nu\in \{0.01, 0.05\}$, and then recentered again. The set of such perturbed points from $X_i^{*}$ is denoted by $X_i$. Five scales $\alpha X_i, (\alpha=0.01, 0.1, 1.0, 10, 100)$ were considered. The linear search of $\epsilon$ was conducted with $[10^{-5}\alpha, \alpha)$ with a step size $10^{-3}\alpha$. We conducted 20 independent runs for each setting, changing the perturbation to $X_i^*$. Tables~\ref{table:SRT-noise01} and~\ref{table:SRT-noise05} summarize the results, corresponding to the perturbation level $\nu = 0.01, 0.05$, respectively. We first focus on Tables~\ref{table:SRT-noise01}. The success rate column displays the ratio of the successful configuration retrieval (i.e., the existence of a valid range of $\epsilon$) to 20 runs. With gradient-weighted normalization, the ABM algorithm succeeded in all datasets and scales (except $(V_2, \alpha=0.01)$), whereas with coefficient normalization, it succeeded only in specific scales (not necessarily $\alpha=1$). For numerically stable computation, the data points must be preprocessed in a certain range (in our case, mean-zero, unit average $L_2$ norm, and $\alpha=1$). However, our experiment shows that, with coefficient normalization, such preprocessing can lead the approximate border basis construction to fail. In contrast, gradient-weighted normalization provides robustness against such preprocessing. Another observation is that the valid range of $\epsilon$ and the extent of vanishing of gradient-weighted normalization both change in proportion to the scale. For example, at $V_2$, the ranges of valid $\epsilon$ changes as $(1.94, 2.17)\times 10^{-n}, (n=-3, -2, \ldots, 1)$ and the extent of vanishing changes as $1.80\times 10^{-n}, (n=-3, -2, \ldots, 1)$. This tendency is supported by the scaling consistency. From Theorem~\ref{thm:scaling-consistency}, if the configuration retrieval test is passed with $(\alpha X, |\alpha|\epsilon)$ for some nonzero $\alpha =\alpha_0$, then it can be also passed by any other $\alpha \ne 0$. Note that although the extent of vanishing appear to be large at $\alpha=100$, the signal to noise ratio remains unchanged. With coefficient normalization, the range of $\epsilon$ and the extent of vanishing change in an inconsistent way. At $V_3$, between $\alpha=0.01$ and $\alpha=1.0$, the scale of the range of $\epsilon$ differs by three order, while between $\alpha=1.0$ and $\alpha=100$ share the same order. For $\alpha=0.1$, the successful case was only $\epsilon=10^{-5}$, where the initial value and the step size of the linear search are $10^{-6}$ and $10^{-4}$, respectively. When the the perturbation level increases to $\nu=0.05$~(Table~\ref{table:SRT-noise05}), similar results were observed; gradient-weighted normalization showed more robust against scaling of points than coefficient normalization, and the range of $\epsilon$ and the extent of vanishing changed proportional to the scaling. Besides, coefficient normalization resulted in lower success rate at $V_2$ and $V_3$. For example, at $(V_2, \alpha=0.1)$, the success rate dropped from 1.00 to 0.00. In contrast, gradient-weighted normalization retained its performance. This result implies the better stability of gradient-weighted normalization against perturbation. \begin{table*} \centering \caption{Summary of the configuration retrieval test of 20 independent runs with 1 \% noise. Columns \textit{coeff.} and \textit{grad. w.} present the coefficient and gradient-weighted normalization, respectively. Column \textit{coeff. dist.} presents the distance of the normalized coefficient vectors between the systems, from 500 unperturbed and 100 perturbed points, repectively. Column \textit{e.v.} denotes the extent of vanishing at the unperturbed points. The values of the range, coefficient distance, and extent of vanishing are averaged values over 20 independent runs. As indicated by the success rate, the proposed gradient-weighted normalization approach is robust and consistent (see the proportional change in the range and the extent of vanishing) to the scaling, whereas coefficient normalization is not.}\label{table:SRT-noise01} \begin{tabular}{c|crcccc} \toprule dataset & normalization & scaling $\alpha$ & range & coeff. dist. & e.v. & success rate \\ \midrule \multirow{10}{*}{$V_1$} & \multirow{5}{*}{coeff.} & 0.01 & -- & -- & -- & 0.00 [00/20] \\ & & 0.1 & -- & -- & -- & 0.00 [00/20] \\ & & 1.0 & [2.28, 2.61] $\times 10^{-2}$ & 1.39 & 1.27 $\times 10^{-2}$ & 1.00 [20/20] \\ & & 10 & [1.80, 1.91] $\times 10^{-0}$ & 1.41 & 1.28 & 1.00 [20/20] \\ & & 100 & [1.31, 1.41] $\times 10^{-0}$ & 1.34 & 1.26 & 0.85 [17/20] \\ & \multirow{5}{*}{grad. w.} & 0.01 & -- & & -- & 0.00 [00/20] \\ & & 0.1 & [3.33, 4.20] $\times 10^{-3}$ & 1.32 & 4.91 $\times 10^{-3}$ & 1.00 [20/20] \\ & & 1.0 & [3.33, 4.20] $\times 10^{-2}$ & 1.32 & 4.91 $\times 10^{-2}$ & 1.00 [20/20] \\ & & 10 & [3.33, 4.20] $\times 10^{-1}$ & 1.41 & 4.91 $\times 10^{-1}$ & 1.00 [20/20] \\ & & 100 & [3.33, 4.20] $\times 10^{-0}$ & 1.41 & 4.91 & 1.00 [20/20] \\ \midrule \multirow{10}{*}{$V_2$} & \multirow{5}{*}{coeff.} & 0.01 & -- & -- & -- & 0.00 [00/20] \\ & & 0.1 & -- & -- & -- & 0.00 [00/20] \\ & & 1.0 & [0.69, 1.30] $\times 10^{-1}$ & 0.0121 & 3.67 $\times 10^{-2}$ & 1.00 [20/20] \\ & & 10 & [1.43, 1.63] $\times 10^{-0}$ & 0.577 & 1.28 & 1.00 [20/20] \\ & & 100 & -- & -- & -- & 0.00 [00/20] \\ % & \multirow{5}{*}{grad. w.} & 0.01 & [1.94, 2.17] $\times 10^{-3}$ & 0.612 & 1.80 $\times 10^{-3}$ & 1.00 [20/20] \\ & & 0.1 & [1.94, 2.17] $\times 10^{-2}$ & 0.518 & 1.80 $\times 10^{-2}$ & 1.00 [20/20] \\ & & 1.0 & [1.94, 2.17] $\times 10^{-1}$ & 0.104 & 1.80 $\times 10^{-1}$ & 1.00 [20/20] \\ & & 10 & [1.94, 2.17] $\times 10^{-0}$ & 0.455 & 1.80 & 1.00 [20/20] \\ & & 100 & [1.94, 2.17] $\times 10^{+1}$ & 0.681 & 1.80 $\times 10^{+1}$ & 1.00 [20/20] \\ \midrule \multirow{10}{*}{$V_3$} & \multirow{5}{*}{coeff.} & 0.01 & -- & -- & -- & 0.00 [00/20] \\ & & 0.1 & [1.00, 1.00] $\times 10^{-6}$ & 0.836 & 1.93 $\times 10^{-6}$ & 0.65 [13/20] \\ & & 1.0 & [7.06, 8.85] $\times 10^{-3}$ & 1.23 & 2.35 $\times 10^{-2}$ & 0.95 [19/20] \\ & & 10 & [1.12, 1.26] $\times 10^{-0}$ & 1.20 & 2.92 & 1.00 [20/20] \\ & & 100 & [1.68, 1.72] $\times 10^{-0}$ & 1.05 & 2.18 & 0.75 [15/20] \\ % & \multirow{5}{*}{grad. w.} & 0.01 & [1.67, 2.36] $\times 10^{-4}$ & 1.30 & 5.97 $\times 10^{-4}$ & 1.00 [20/20] \\ & & 0.1 & [1.67, 2.36] $\times 10^{-3}$ & 1.29 & 5.97 $\times 10^{-3}$ & 1.00 [20/20] \\ & & 1.0 & [1.67, 2.36] $\times 10^{-2}$ & 1.29 & 5.97 $\times 10^{-2}$ & 1.00 [20/20] \\ & & 10 & [1.67, 2.36] $\times 10^{-1}$ & 1.15 & 5.97 $\times 10^{-1}$ & 1.00 [20/20] \\ & & 100 & [1.67, 2.36] $\times 10^{-0}$ & 1.36 & 5.97 & 1.00 [20/20] \\ \bottomrule \end{tabular} \end{table*} \begin{table*} \centering \caption{Summary of the configuration retrieval test of 20 independent runs with 5\% noise. Compared to the results in Table~\ref{table:SRT-noise01}, coefficient normalization decreases the success rate at $V_2$ and $V_3$, whereas gradient-weighted normalization retains the performance. }\label{table:SRT-noise05} \begin{tabular}{c|crcccc} \toprule dataset & normalization & scaling $\alpha$ & range & coeff. dist. & e.v. & success rate \\ \midrule \multirow{10}{*}{$V_1$} & \multirow{5}{*}{coeff.} & 0.01 & -- & -- & -- & 0.00 [00/20] \\ & & 0.1 & -- & -- & -- & 0.00 [00/20] \\ & & 1.0 & [2.28, 2.61] $\times 10^{-2}$ & 1.31 & 1.14 $\times 10^{-1}$ & 1.00 [20/20] \\ & & 10 & [1.80, 1.91] $\times 10^{-0}$ & 1.41 & 4.13 & 1.00 [20/20] \\ & & 100 & [1.86, 1.91] $\times 10^{-0}$ & 1.20 & 3.34 & 0.85 [17/20] \\ & \multirow{5}{*}{grad. w.} & 0.01 & -- & & -- & 0.00 [00/20] \\ & & 0.1 & [5.07, 5.66] $\times 10^{-3}$ & 1.22 & 2.61 $\times 10^{-2}$ & 1.00 [20/20] \\ & & 1.0 & [5.07, 5.66] $\times 10^{-2}$ & 1.34 & 2.61 $\times 10^{-1}$ & 1.00 [20/20] \\ & & 10 & [5.07, 5.66] $\times 10^{-1}$ & 1.37 & 2.61 & 1.00 [20/20] \\ & & 100 & [5.07, 5.66] $\times 10^{-0}$ & 1.40 & 2.61 $\times 10^{+1}$ & 1.00 [20/20] \\ \midrule \multirow{10}{*}{$V_2$} & \multirow{5}{*}{coeff.} & 0.01 & -- & -- & -- & 0.00 [00/20] \\ & & 0.1 & -- & -- & -- & 0.00 [00/20] \\ & & 1.0 & -- & -- & -- & 0.00 [00/20] \\ & & 10 & [3.64, 4.21] $\times 10^{-0}$ & 0.693 & 3.41 & 1.00 [20/20] \\ & & 100 & -- & -- & -- & 0.00 [00/20] \\ % & \multirow{5}{*}{grad. w.} & 0.01 & [4.11, 5.42] $\times 10^{-3}$ & 0.692 & 2.16 $\times 10^{-3}$ & 1.00 [20/20] \\ & & 0.1 & [4.11, 5.42] $\times 10^{-2}$ & 0.667 & 2.16 $\times 10^{-2}$ & 1.00 [20/20] \\ & & 1.0 & [4.11, 5.42] $\times 10^{-1}$ & 0.515 & 2.16 $\times 10^{-1}$ & 1.00 [20/20] \\ & & 10 & [4.11, 5.42] $\times 10^{-0}$ & 0.565 & 2.16 & 1.00 [20/20] \\ & & 100 & [4.11, 5.42] $\times 10^{+1}$ & 0.692 & 2.16 $\times 10^{+1}$ & 1.00 [20/20] \\ \midrule \multirow{10}{*}{$V_3$} & \multirow{5}{*}{coeff.} & 0.01 & -- & -- & -- & 0.00 [00/20] \\ & & 0.1 & [1.00, 1.00] $\times 10^{-6}$ & 0.416 & 2.10 $\times 10^{-6}$ & 0.30 [06/20] \\ & & 1.0 & [0.90, 1.04] $\times 10^{-2}$ & 1.29 & 1.40 & 0.95 [19/20] \\ & & 10 & [1.32, 1.39] $\times 10^{-0}$ & 4.86 & 1.33 & 1.00 [20/20] \\ & & 100 & [1.67, 1.67] $\times 10^{-0}$ & 2.51 & 8.48 $\times 10^{-1}$ & 0.60 [12/20] \\ % & \multirow{5}{*}{grad. w.} & 0.01 & [3.13, 3.68] $\times 10^{-4}$ & 1.38 & 2.37 $\times 10^{-3}$ & 1.00 [20/20] \\ & & 0.1 & [3.13, 3.68] $\times 10^{-3}$ & 1.38 & 2.37 $\times 10^{-2}$ & 1.00 [20/20] \\ & & 1.0 & [3.13, 3.68] $\times 10^{-2}$ & 1.34 & 2.37 $\times 10^{-1}$ & 1.00 [20/20] \\ & & 10 & [3.13, 3.68] $\times 10^{-1}$ & 1.17 & 2.37 & 1.00 [20/20] \\ & & 100 & [3.13, 3.68] $\times 10^{-0}$ & 1.37 & 2.37 $\times 10^{+1}$ & 1.00 [20/20] \\ \bottomrule \end{tabular} \end{table*} \subsection{Valid range of scaling parameter at coefficient normalization} Let $(G, \mathcal{O})$ and $(G_{\alpha}, \mathcal{O}_{\alpha})$ be the outputs of the ABM algorithm with coefficient normalization given $(X, \epsilon)$ and $(X_{\alpha}, \epsilon_{\alpha})$. We are interested in the range of $\alpha$ a valid range of $\epsilon_{\alpha}$, which yields $\mathcal{O} = \mathcal{O}_{\alpha}$. Equation~\eqref{eq:alpha-ub} in Proposition~\ref{prop:coefficient-normalization-failure} argues that the valid range of $\epsilon_{\alpha}$ is lower bounded by a certain quantity (say, $\xi$). Here, we test how tight this bound is as well as confirm the scale-sensitivity of coefficient normalization again. We used $V_2$ from the previous experiment, and points are sampled, prepossessed, and perturbed by 1\% noise to obtain $X_2$ in the same way. From Table~\ref{table:SRT-noise01}, the ABM algorithm with coefficient normalization succeeds with $\alpha = 1.0, 10$. \footnote{Note that, strictly speaking, we are not solving the same problem. In the previous experiment, a \textit{success} means that similar bases are obtained between unperturbed and perturbed points, whereas here, it means that the same order ideal (up to a certain degree) is obtained between nonscaled and scaled points.} Thus, we now work with $\widehat{X}_2 = \alpha X_2, (\alpha=1.0, 5.0, 10)$. We then calculate the range of $\beta$ such that given $\beta\widehat{X}_2$, the algorithm outputs the same order ideal as the one from $\widehat{X}_2$ up to a certain degree as in the configuration retrieval test. To obtain the range, linear search was performed with $\beta \in (0, 1.0]$ with step size 0.01. The results are shown in Fig.~\ref{fig:coeff-failure}. We can actually observe that the successful regions (shady parts) are lower bounded by $\xi$. Since coefficient normalization mainly works with $\alpha \in [1.0, 10]$, the bound $\epsilon$ has relatively large value at $\alpha = 1.0$, which indicates a larger failure region below $\alpha$. Since Eq.~\eqref{eq:alpha-ub} only provides a sufficient condition for nonexistence, the bound cannot be said very tight; however, the validity of the bound is confirmed. \begin{figure*}[t] \includegraphics[width=\linewidth]{coef-failure.pdf} \caption{Theoretical lower bound $\xi$~(dashed line) for $\beta$ with which one can retrieve the same order ideal of the non-scaled case (i.e., $\beta=1$). Valid range (shaded region) of $\beta$ is found by a linear search. (a), (b), and~(c) corresponds to $\alpha=1.0, 5.0, 10$. The shaded regions are at the right side of bound as Proposition~\ref{prop:coefficient-normalization-failure} predicts.} \label{fig:coeff-failure} \end{figure*} \section{Conclusion} In this study, we proposed gradient-weighted normalization for the approximate border basis computation of vanishing ideals. We showed its validity in the border basis computation by proving that the gradient-weighted norm always takes nonzero values for order terms and border basis polynomials. The introduction of gradient-weighted normalization is compatible with the existing analysis of approximate border bases and the computation algorithms. The time complexity does not change either. The data-dependent nature of gradient-weighted normalization provides several important properties (stability against perturbation and scaling consistency) to basis computation algorithms. In particular, through theory and numerical experiments, we highlighted the critical effect of the scaling of points on the success of approximate basis computation. We consider that the present study provides a new perspective and ingredients to analyze the border basis computation in the approximate setting, where perturbed points should be dealt with and stable computation is required. \section*{Acknowledgement} We would like to thank Yuichi Ike for helpful discussions. This work was supported by JST, ACT-X Grant Number JPMJAX200F, Japan. \bibliographystyle{ACM-Reference-Format}
{'timestamp': '2022-07-04T02:05:20', 'yymm': '2101', 'arxiv_id': '2101.00401', 'language': 'en', 'url': 'https://arxiv.org/abs/2101.00401'}
arxiv
\section{Introduction and related work} Models of epidemic propagation are especially useful when they provide key insights while retaining simplicity and generality. For example, in mathematical epidemiology the SIR model reveals in very simple terms the fundamental role of the basic reproduction number ($R_0$) which governs the macroscopic, long-term evolution of the outbreak in a homogeneous population. The vast majority of models developed for the novel SARS-CoV-2 are extensions to the classic SIR, along the standard approach of introducing additional compartments to describe different phases of the infection, the presence of asymptomatic, symptomatic or pauci-symptomatic individuals, the set of quarantined, hospitalized people, and so on. Such models lead to a system of coupled ODE's with fixed or time-varying coefficients to be estimated from traces. A very incomplete list of modeling efforts pursued in this direction, early applied to COVID-19, includes the SEIR models in \cite{Fang2020,KUCHARSKI2020553,columbia,ucla,Miller}, the SIRD models in \cite{Anastassopoulou,CALAFIORE}, the SEPIA model in \cite{gatto}, the SIDHARTE model in \cite{Giordano2020}. In this paper we develop a slightly more sophisticated model that allows a more accurate representation of native characteristics of a specific virus, such as actual distributions of the duration of incubation, pre-symptomatic and symptomatic phases, for various categories of infected. This level of detail is important when the intensity of applied countermeasures varies significantly over time-scales comparable to that of an individual infection, and we believe it is essential to address fundamental questions such as: i) when and to what extent can we expect to see the effect of specific mobility restrictions introduced by a national government at a given point in time? ii) what is the impact of hard vs partial lockdowns enforced for given numbers of days? when can restrictions be safely released to restart economic and social activities while still keeping the epidemic under control? Specifically, we propose {\color{black} and analyse} a novel, modulated version of the {\color{black} marked} Hawkes process, a self-exciting stochastic point process with roots in geophysics and finance \cite{hawkes}. In a nutshell, in the standard {\color{black} marked Hawkes process each event $i$ with mark $m_i$, occurring at time $t_i$, generates new events with stochastic intensity $\nu(t-t_i, m_i)$, where $\nu( \cdot, m_i)$ is a generic kernel. The process unfolds through successive generations of events, starting from so-called immigrants (generation zero). } In our model events represent individual infections, and a modulating function $\mu(t)$, which scales the overall intensity of the process at real time $t$, allows us to take into account the impact of time-varying mobility restrictions and social distance limitations. In addition, we model the transition of infected, undetected individuals to a quarantined state at inhomogeneous rate $\rho(t)$, to describe the time-varying effectiveness of contact tracing and mass testing. We mention that branching processes of various kind, including Hawkes processes, have been proposed in various biological contexts \cite{harris,mei,Kim401,xu17}. In \cite{akian2020probabilistic}, a probabilistic extension of (deterministic) discrete-time SEIR models, based on multi-type branching processes, has been recently applied to COVID-19 to capture the impact of detailed distributions of the time spent in different phases, together with mobility restrictions and contact tracing. In parallel to us, authors of \cite{chiang} have proposed a Hawkes process with spatio-temporal \lq\lq covariates" for modeling COVID-19 in the US, together with an EM algorithm for parameter inference. The work in \cite{chiang} is somehow orthogonal to us, since they focus on spatial and demographic features, aiming at predicting the trend of confirmed cases and deaths in each county. In contrast, we introduce marks and stages to natively model the course of an infection for different categories of individuals, with the fundamental distinction between real and detected cases. Moreover, we take into account the impact of time-varying detection efforts and contact tracing. At last, we obtain analytical expressions for the first two moments of the number of individuals who have been infected within a given time. We demonstrate the applicability of our model to the novel COVID-19 pandemic by considering real traces related to the first and second wave of coronavirus in Italy. Our fitting exercise, though largely preliminary and based on incomplete information, suggests that our approach has good potential and can be effectively used both for planning counter-measures and to provide an a-posteriori explanation of observed epidemiological curves. The paper is organized as follows. In Section \ref{sec:model} we provide the mathematical formulation of the proposed modulated Hawkes process to describe the temporal evolution of the epidemic. In Section \ref{sec:compsir} we motivate our approach by comparing it to the standard SIR model. Some mathematical results related to the moment generating function of our process are presented in Section \ref{sec:moments}. In Section \ref{sec:covidmodel} we describe our COVID-19 model based on the proposed approach. We separately fit our model to the first and second wave of COVID-19 in Italy in Sections \ref{sec:firstwave} and \ref{sec:secondwave}, respectively, offering hopefully interesting insights about what happened in this country (and similarly in other European countries) during the recent pandemic. We conclude in Section \ref{sec:conclusions}. \section{Mathematical formulation of modulated Hawkes process}\label{sec:model} We first briefly recall the classic Hawkes process restricted to the temporal dimension (the spatio-temporal formulation is similar, but we focus in this work on the purely temporal version). Events of the process (or points) occur at times $T=\{T_i\}_{i\geq 1}$, which are $\mathbb{R}$-valued random variables. A subset $I$ of these points, called immigrants, are produced by an inhomogeneous Poisson process of given intensity $\sigma(t)$. Each immigrant, independently of others, is the originator of a progeny (or cluster) of other points, dispersed in the future through a self-similar branching structure: a first generation of points is produced with intensity \mbox{$\nu(t-T_j)$}, where $T_j$ is the occurrence time of immigrant $j$, and \mbox{$\nu: \mathbb{R}^+ \rightarrow \mathbb{R}^+$} is a kernel function. Each point of the first generation, in turn, generates new offsprings in a similar fashion, creating the second generation of points, and so on. The above process can be easily extended to account for different types of points with type-specific kernel functions. Types are denoted by marks $M=\{M_i\}_{i\geq 1}$, which are assumed to be i.i.d. random variables with values on an arbitrary measurable space $(\mathrm{M},\mathcal{M})$, with a probability distribution $\mathbb{Q}$. Let $N(t,m)$ be the counting process associated to the marked points $N=\{(T_i,M_i)\}_{i\geq 1}$. The (conditional) stochastic intensity $\lambda(t)$ of the overall process is then given by: \begin{eqnarray*}\label{eq:haw} \lambda(t) = \sigma(t) + \int_{0}^t \nu(t-s,m) N({\rm\,d} s, {\rm\,d} m) = \sigma(t) + \sum_{{T_k} \cap (0,t) } \nu(t-T_k,M_k) \end{eqnarray*} where $\nu: \mathbb{R}^+ \times \mathrm{M} \rightarrow \mathbb{R}^+$ is a type-dependent kernel function. In the following we assume $\overline{\nu}(t):=\mathbb{E}[\nu(t,M_1)]$ to be summable,. i.e. \begin{equation}\label{hp:integrability} R_0 = \int_0^\infty\overline{\nu}(t)\mathrm{d}t<\infty \end{equation} Note that $R_0$ is the average number of offsprings generated by each point, which is usually referred to as basic reproduction number in epidemiology. The process is called subcritical if $R_0 < 1$, supercritical if $R_0 > 1$. Our main modification to the above classic marked Hawkes process $N$ is to modulate the instantaneous generation rate of offsprings $N'=N\setminus I$ by a positive, bounded function $\mu(t): \mathbb{R}^+ \rightarrow \mathbb{R}^+$, representing the impact of mobility restriction countermeasures. By so doing, we obtain the modified stochastic intensity of the process: \begin{align}\label{eq:modhaw} \lambda(t) &= \sigma(t) + \mu(t)\left[\int_{0}^t \nu(t-s,m) N({\rm\,d} s, {\rm\,d} m) \right] \nonumber \\ &= \sigma(t)+\mu(t)\left[\sum_{{T_k} \cap (0,t) } \nu(t-T_k,M_k) \right] \end{align} Note that, when $\mu(t) = \mu$ is constant, we re-obtain a classic Hawkes process with modified kernel $\mu\,\nu()$. In general, the obtained process is no longer self-similar. In particular, the average number of offsprings generated by a point becomes a function of time: \begin{equation}\label{eq:Rt} R(t) = \int_0^\infty \mu(t+\tau) \overline{\nu}(\tau) {\rm\,d} \tau \end{equation} which provides the infamous real-time reproduction number usually referred to on the media as \lq Rt index'. We emphasize that the process can initially start in the supercritical regime, and then it can become subcritical for effect of a decreasing function $\mu()$, a case of special interest in our application to waves of COVID-19. We mention that the great bulk of literature related to the Hawkes process and its applications to geophysics and finance focuses on the subcritical regime, whereas our formulation applies also to the supercritical regime, which is more germane to epidemics. The conditional intensity \equaref{modhaw} can be easily de-conditioned with respect to $N$, obtaining the \lq average' stochastic intensity $\overline{\lambda}(t):=\mathbb{E}[\lambda(t)]$: \begin{align}\label{eq:barlambda} \overline{\lambda}(t)&=\sigma(t)+\mu(t)\mathbb{E}\left[\int_{(0,t)\times\mathrm{M}}\nu(t-s,m)N(\mathrm{d}s,\mathrm{d}m)\right]\nonumber\\ &=\sigma(t)+\mu(t)\mathbb{E}\left[\int_{(0,t)\times\mathrm{M}}\nu(t-s,m)\lambda(s)\,\mathrm{d}s\mathbb{Q}(\mathrm{d}m)\right]\nonumber\\ &=\sigma(t)+\mu(t)\mathbb{E}\left[\int_{0}^{t}\overline{\nu}(t-s)\lambda(s)\mathrm{d}s\right]\nonumber\\ &=\sigma(t)+\mu(t)\int_{0}^{t}\overline{\nu}(t-s)\overline{\lambda}(s)\mathrm{d}s. \end{align} where we recall that $\overline{\nu}(t)= \mathbb{E}[\nu(t,M_1)]$. We observe that \equaref{barlambda} is a linear Volterra equation of the second kind, which can be efficiently solved numerically.\footnote{For example, the standard trapezoidal rule allows obtaining a discretized version of $\overline{\lambda}(t)$ by a matrix inversion.} In the special case of constant modulating function, \equaref{barlambda} reduces to a convolution equation which can be analyzed and solved by means of Laplace transform techniques (see \ref{app:explicit}). At last we introduce the total number of points up to time $t$, $N(t)$ (regardless of their associated marks), and its average: \begin{equation}\label{eq:barN} \overline{N}(t) = \int_0^t \overline{\lambda}(\tau) {\rm\,d} \tau \end{equation} \section{Comparison with SIR model}\label{sec:compsir} When the kernel function has an exponential shape, i.e., $\nu(t) = K e^{-\gamma t}$, it is possible to establish a simple connection between the Hawkes process and the classic SIR model \cite{australiani}. Specifically, consider a stochastic SIR model with an infinite population of susceptible individuals, where each infected generates new infections at rate $\beta$, and recovers at rate $\gamma$ (i.e., after an exponentially distributed amount of time of mean $1/\gamma$). Then the average intensity of the process generated by this stochastic SIR, averaging out the times at which nodes recover, has exactly the (conditional) intensity of a Hawkes process starting with the same number of initially infected nodes, no further immigrants, and $\nu(t) = \beta e^{-\gamma t}$ \cite{australiani}. This can be intuitively understood by considering that in SIR the average, effective rate with which an infected individual generates new infections after time $t$ since it became infected equals $\beta$ times the probability that the node has not yet recovered, which is $e^{-\gamma t}$. We remark that in \cite{australiani} authors push this equivalence a bit further, by showing that a SIR model with {\em finite} population $N_0$ is equivalent to a modulated Hawkes process similar to \equaref{modhaw}, where $\mu(t) = 1-N(t)/N_0$. In our model and its application to COVID-19, we do not consider the impact of finite population size, and assume an infinite population of susceptible individuals\footnote{This assumption is largely acceptable at the beginning of an epidemic.}. Therefore, we do not need the \lq correction factor' $1-N(t)/N_0$, and instead use the modulating function $\mu(t)$ to model the (process-independent) effect of mobility restrictions. A similar effect due to mobility restrictions can be incorporated into the SIR model, by applying factor $\mu(t)$ to the infection rate $\beta$. Given the above connection between a (possibly modulated) Hawkes process and the traditional SIR, one might ask what is the benefit of our approach with respect to SIR-like models. In contrast to SIR, the Hawkes process allows us to choose an arbitrary kernel $\nu(t)$, not necessarily exponential. With this freedom, can we observe dynamics significantly different from those that can be obtained by a properly chosen exponential shape? We answer this question in the positive with the help of an illustrative scenario. Consider an epidemic starting at time zero with $I_0=1000$ infected individuals.\footnote{Note that in our model the number of immigrants has a Poisson distribution with mean $\int_0^{\infty} \sigma(t) {\rm\,d} t$. However to reduce the variance we have preferred to start simulations with the same {\em deterministic} number of infected. Further, note that analytical results for the mean trajectory of infected nodes are not affected by this choice.} We fix to $g = 10$ (days) the average generation time, which is the mean temporal separation between a new infection belonging to generation $i$ and its parent in generation $i-1$. Note that the above constraint implies that $\int_0^{\infty} t\,\nu(t) {\rm\,d} t = g$. We also normalize $\int_0^{\infty} \nu(t) {\rm\,d} t = 1$, since we can use $\mu(t)$ to scale the infection rate, in addition to considering time-varying effects due to mobility restriction. Note that in SIR we can only satisfy the above constraints by choosing the exponential kernel $\nu(t) = \frac{1}{g} e^{-\frac{t}{g}}$, $t > 0$. Instead, in our Hawkes model we have much more freedom. \begin{figure}[htb] \centering \includegraphics[width=0.9\columnwidth]{mucost.pdf} \caption{Evolution of mean number of infected for different kernel shapes, in the case of constant $\mu = 1.2$ (supercritical) or constant $\mu = 0.9$ (subcritical), with $I_0 = 1000$, $g = 10$.\label{fig:mucost}} \end{figure} First, we consider a scenario in which $\mu(t)$ is constant, equal to either 1.2 (supercritical case) or 0.9 (subcritical case). In Fig. \ref{fig:mucost} we show the temporal evolution of the mean number of infected $\overline{N}(t)$, for three kernel shapes that allows for an explicit solution of \equaref{barlambda},\equaref{barN} using Laplace transform (\ref{app:explicit}). The {\em delta} shape corresponds to the kernel function $\overline{\nu}(t) = \delta(t-g)$, where $\delta(\cdot)$ is Dirac's delta function, for which \begin{equation}\label{eq:barNdelta} \overline{N}_{\rm delta}(t) = I_0 \frac{\mu^{\lfloor t/g \rfloor + 1}-1}{\mu - 1} \end{equation} The {\em exp} shape corresponds to the exponential kernel $\overline{\nu}(t) = \frac{1}{g} e^{-\frac{t}{g}}$ (SIR model), for which \begin{equation}\label{eq:barNexp} \overline{N}_{\rm exp}(t) = I_0 \left[ 1+\frac{\mu}{\mu-1}\left(e^{t (\mu-1)/g} -1\right) \right] \end{equation} The {\em hyper} shape corresponds to the hyper-exponential kernel: \\ \mbox{$\overline{\nu}(t) = p_1 \alpha_1 e^{-\alpha_1 t} + p_2 \alpha_2 e^{-\alpha_2 t}$}, where $0 \leq p_1 \leq 1$, $p_2 = 1 - p_1$, $p_1/\alpha_1 + p_2/\alpha_2 = g$, which also permits obtaining an explicit, though lengthy expression of $\overline{N}(t)$ that we omit here. Specifically, the \lq hyper' curve on Fig. \ref{fig:mucost} corresponds to the case $1/\alpha_1 = 3$, $1/\alpha_2 = 30$. We observe that, in the subcritical case ($\mu = 0.9$), the mean number of infected saturates to the same value, irrespective of the kernel shape; this can be explained by the fact that the final size of the epidemics is described by the same branching process for all kernel shapes (i.e., a branching process in which the offspring distribution is Poisson with mean 0.9). In the supercritical case ($\mu = 1.2$), instead, the mean number of infected grows exponentially as $\Theta(e^{\eta t})$ (as $t$ grows large), where, interestingly, $\eta > 1$ depends on the particular shape (notice the log $y$ axes on Fig. \ref{fig:mucost}). In particular, the hyper-exponential kernel can produce arbitrarily large $\eta$ (\ref{app:explicit}). We conclude that, even when we fix the average generation time $g$, different kernels can produce largely different (in order sense) evolutions of $\overline{N}(t)$. Note that, by introducing compartments, SIR-like models can match higher-order moments of the generation time, but our results suggest that $\overline{N}(t)$ depends on {\em all} moments of it, i.e., on the precise shape of the kernel. Moreover, recall that some shapes are difficult to approximate by a phase-type approximation (e.g., the rectangular shape, or more in general, kernels with finite support). The strong impact of the specific kernel shape becomes even more evident when we consider a time-varying $\mu(t)$, as in our modulated Hawkes process. As an example, consider the COVID-inspired scenario in which the modulating function $\mu(t)$ corresponds to the black curve in Fig. \ref{fig:covcum}: during the first 30 days, $\mu(t)$ decreases linearly from 3 to 0.3; it stays constant at 0.3 for the next 60 days; and it goes back linearly to 3 during the next 30 days, after which it stays constant at $3$. \begin{figure}[htb] \centering \includegraphics[width=0.9\columnwidth]{covcum.pdf} \caption{Evolution of mean number of infected (left y axes) in the COVID-like scenario, for different kernel shapes. Shaded areas denote $95\%-$level confidence intervals obtained by 100 simulation runs. The right y axes refers to modulating function $\mu(t)$ (black curve).\label{fig:covcum}} \end{figure} In Fig. \ref{fig:covcum} we show the mean number of infected estimated by simulation (averaging 100 independent runs), for the three kernel shapes {\em exp}, {\em delta}, and {\em uniform}, where {\em uniform} corresponds to the kernel $\overline{\nu}(t) = \frac{1}{2 g}$, $t \in (0,2g)$, while the shapes {\em exp}, {\em delta} have been already introduced above. Shaded areas around each curve denote $95\%-$level confidence intervals. We observe huge discrepancies among the trajectories of $\overline{N}(t)$ obtained under the three kernels. In particular, after the first \lq wave' of 30 days, the {\em exp} kernel produces about four times more infections than those produced by the {\em delta} kernel. This can be explained by the fact that $\mu(t)$ varies significantly on a time window (30 days) comparable to the average generation time (10 days). It is also interesting to compare what happens on the second wave starting at day 90, after all 3 curves have settled down to an almost constant value: now discrepancies are even more dramatic: although we observe a very fast resurgence of the epidemic in all cases, this happens with significant delays from one curve to another. This is due to the fact that the number of individuals who are still infectious after the subcritical period (when $\mu < 1$) is largely different, especially considering that both the {\em uniform} and {\em delta} kernels have finite support (20 and 10 days, respectively) much smaller than the duration of the subcritical period, whereas the {\em exp} shape has infinite support: this implies that under the {\em uniform} and {\em delta} kernels the virus survives the subcritical period only through chains of infections belonging to successive generations, whereas under the {\em exp} shape in principle the epidemic can restart just thanks to the original immigrants at time 0, who are still weakly infectious when we re-enter the supercritical regime (around day 100). Actually, in our experiment, under the {\em delta} kernel the epidemic died out in 68 out of 100 simulation runs, which explains the large confidence intervals obtained in this case at end of the observation window. Under the {\em uniform} kernel, the epidemic died only in 3 out of 100 runs, while it always survived under the {\em exp} kernel. We conclude that, even while fixing the mean generation time, the precise shape of the kernel function can play an important role in predicting the process dynamics and the impact of countermeasures, especially when the time-scale of control is comparable to the time-scale of an individual contagion. One might obtain a good fitting with measured data also by using an exponential shape, and a properly chosen modulating function $\mu(t)$, but this is undesirable, since the required $\mu(t)$ would no longer reflect the actual evolution of mobility and interpersonal contact restrictions. In the case of COVID-19, several researchers have actually attempted to incorporate into analytical models detailed information about people mobility, using for example data provided by cellular network operators or smartphone apps \cite{googleapp,appleapp}. \section{Moment generating function}\label{sec:moments} Our modulated Hawkes process is stochastic in nature, hence it is important to characterize how realizations of the process are concentrated around the mean trajectory derived in Sec. \ref{sec:model}. This characterization is instrumental, for example, in designing simulation campaigns with proper number of runs. Moreover, note that it is entirely possible that the epidemic gets extinct at its early stages, or in between two successive waves, as we have seen in the scenario in Fig. \ref{fig:covcum}. Actually, an epidemic could die out even when starting in the supercritical regime (consider the case of a single immigrant at time $t$, who does not generate any offspring with probability $e^{-R(t)}$), something that is not captured by deterministic mean-field approaches. Therefore, it is interesting to understand the variability of the process at any time. Under mild assumptions an expression for the moment generating function of the number of points in $[0,t)$ can be given, and an iterative procedure can be applied to compute the moment of any order $n$ in terms of moments of smaller order, though with increasing combinatorial complexity. In this section we limit ourselves to reporting the main results on this moments' characterization, without their mathematical proofs, to keep the paper focused on the application to COVID-19 and its control measures. Hereon, we shall assume \begin{equation}\label{hp:boundedh} K_1:=\sup_{(t,m)\in (0,\infty)\times\mathrm{M}}\nu(t,m)\in (0,\infty),\quad K_2:=\sup_{t\in (0,\infty)}\mu(t)\in (0,\infty). \end{equation} Also, we fix a horizon $\tau\in (0,\infty)$, and, for $t\in (0,\tau)$, we denote with $S_{t,\tau}$ the number of points, up to time $\tau$, in the cluster generated by an immigrant at $t$ (including the immigrant). We denote with $|\cdot|$ the modulus of a complex number. We are interested in $N(\tau)$, i.e., the total number of points generated up to time $\tau$, irrespective of their mark. \begin{theorem}[Moment generating function of $N(\tau)$] \label{thm:LaplaceTransf} Assume \eqref{hp:integrability} and \eqref{hp:boundedh}. Then there exists $\theta_c>0$ such that, for any $z\in\Theta_c$, \[ \Theta_c:=\{z\in\mathbb C:\,\,\mathrm{Re}z<\theta_c\}, \] we have \begin{equation}\label{eq:LaplaceTransf} \mathbb{E}[\mathrm{e}^{z N(\tau)}]=\exp\left(\int_{0}^{\tau}(G(t,z)-1)\,\sigma(t)\mathrm{d}t\right) \end{equation} and \begin{equation}\label{eq:LaplaceBound} \sup_{z\in\Theta_c}|\mathbb{E}[\mathrm{e}^{zN (\tau)}]|<\infty. \end{equation} Here \begin{equation}\label{eq:H} G(t,z):=\mathbb{E}[\mathrm{e}^{z S_{t,\tau}}], \end{equation} is the solution of the following functional equation. \begin{equation}\label{eq:G} G(t,z)=\mathrm{e}^{z}\mathbb{E}\left[\mathrm{e}^{\int_{0}^{\tau}(G(v,z)-1)\mu(v)\nu(v-t,M_1)\,\mathrm{d}v}\right], \quad (t,z)\in (0,\tau)\times\Theta_c. \end{equation} \end{theorem} From the moment generating function we can obtain an expression for the first and second moment of $N(\tau)$ (the first moment can also be obtained directly from the average stochastic intensity, as we have done in Sec. \ref{sec:model}.). \begin{theorem}[The first two moments of $N(\tau)$]\label{thm:law} Assume \eqref{hp:integrability} and \eqref{hp:boundedh}. Then \begin{align} \mathbb{E}[N(\tau)]=\overline{N}(\tau)={\int_{0}^{\tau} \overline{ \lambda}(t) \,\mathrm{d}t} = {\int_{0}^{\tau}E_{1}(t)\sigma(t)\,\mathrm{d}t} \label{eq:1mom} \end{align} and \begin{align} \mathbb{E}[N(\tau)^{2}] = {\int_{0}^{\tau}E_{2}(t)\sigma(t)\,\mathrm{d}t}+ {\left(\int_{0}^{\tau}E_{1}(t)\sigma(t)\,\mathrm{d}t\right)^2}, \label{eq:2mom} \end{align} with \begin{align}\label{E2} E_2(t)&=G''(t,0)=\mathbb{E}[S^2_{t,\tau}]= 1+ \int_{t}^{\tau} E_2(v) \mu(v) \overline{\nu}(v-t)\,\mathrm{d}v \,+ \nonumber \\ & + {2}\int_{t}^{\tau}E_{1}(v) \mu(v) \overline{\nu}(v-t)\,\mathrm{d}v + \left(\int_{t}^{\tau} E_{1}(v) \mu(v)\overline{\nu}(v-t) \mathrm{d}v\right)^2 \end{align} \begin{equation}\label{eq:E1} E_1(t)=G'(t,0)=\mathbb{E}[S_{t,\tau}]=1+\int_{t}^{\tau}\overline{\lambda^{(t)}}(v)\,\mathrm{d}v \end{equation} and \begin{equation}\label{eq:lambdabar} \overline{\lambda^{(t)}}(v)=\mu(v)\overline{\nu}(v-t)+ \mu(v)\int_{t}^{v}\overline{\nu}(v-u)\overline{\lambda^{(t)}}(u)\,\mathrm{d}u. \end{equation} \end{theorem} Note that \eqref{E2} and \eqref{eq:lambdabar} are second-type inhomogeneous Volterra equations. In the particular case in which $\mu()$ is constant, solutions for \eqref{E2} and \eqref{eq:lambdabar} can be found by applying a standard Laplace transform methodology. \section{COVID-19 Model}\label{sec:covidmodel} Now we describe how we applied the modulated Hawkes process introduced before to model the propagation dynamics of COVID-19. The proposed model could actually be used to represent the dynamics of other similar viruses as well. First, we take advantage of the fact that we do not need to consider a unique kernel function for all infected. Indeed, the presence of marks allows us to introduce different classes of infectious individuals with specific kernel functions. Specifically, we have considered three classes of infectious: {\em symptomatic}, \emph{asymptomatic} and \emph{superspreader}, denoted by symbols $\{s,a,h\}$. We assume that, when a person gets infected, it is assigned a random class $C \in \{s,a,h\}$ with probabilities $p_s,p_a,p_h$, respectively, $p_s + p_a + p_h = 1$, $0 \leq p_s \leq 1$, $0 \leq p_a \leq 1$, $0 \leq p_u \leq 1$. As the name suggests, {\em symptomatic} people are those who will develop evident symptoms of infection, and we assume that because of that they will be effectively quarantined at home or hospitalized at the onset of symptoms. On the contrary, the \emph{asymptomatic} mark is given to individuals who will not develop strong enough symptoms to be quarantined. Therefore, they will be able to infect other people for the entire duration of the disease, though at low infection rate (unless they get scrutinized by mass testing, as explained later). At last, \emph{superspreaders} are individuals who exert a high infection rate but do not get quarantined due to several possible reasons (unless they get scrutinized by mass testing). This class also includes people with mild symptoms, who become highly contagious because of their mobility pattern (e.g., participation to \lq superspreading events'). Though the above classification of infectious individuals is a simplified one, a properly chosen mix of the three considered classes can represent a wide range of different scenarios. Irrespective of their class, we will assume that all infectious people go through the following sequence of stages: first, there is a random incubation time, denoted by r.v. $I$, with given cdf $F_I()$. During this time we assume the all infected exert a low infection rate $\lambda_{\rm low}$. Then, there is a crucial pre-symptomatic period, during which infected in classes $\{s,h\}$ already exert a high infection rate $\lambda_{\rm high}$, while infected in class $a$ still exert low infection rate $\lambda_{\rm low}$. For simplicity, we have assumed the presymptomatic phase to have constant duration $w$. The following evolution of the infection rate of an individual depends on the class: since we assume that {\em symptomatic} people get effectively quarantined, they no longer infect other individuals after the onset of symptoms. We model this fact introducing a {\em quarantined} class of people (denoted by $q$), and deterministically moving all infected in class $s$ to class $q$ after time $I+w$. People in classes $\{a,h\}$ continue to be infectious during a disease period of random duration $D$, with given cdf $F_D()$. The difference between these two classes is that infectious in class $a$ ($h$) exert, during the disease period, infection rate $\lambda_{\rm low}$ ($\lambda_{\rm high}$), respectively. At last, we assume that people in classes $\{a,h\}$ enter a residual period of random duration $E$, with cdf $F_E()$, during which all of them exert infection rate $\lambda_{\rm low}$. We introduced this additional phase because some people who recovered from COVID-19 where found to be still contagious several days (even weeks) after the end of the disease period. Note that durations $I,D,E$ are assumed to be independent, and that the complete mark associated to an infected is the tuple $M=(C,I,D,E)$. \begin{figure}[htb] \centering \includegraphics[width=0.9\columnwidth]{fert.pdf} \caption{Kernel functions for classes $s,a,h$ (from top to bottom), for given durations $I,D,E$ of stages. \label{fig:fert}} \end{figure} An illustration of the three class-dependent kernels $\nu(t,s),\nu(t,a),\nu(t,h)$, conditioned on the durations $(I,D,E)$, is reported in Fig. \ref{fig:fert}. \begin{remark} We emphasize that our model of COVID-19 is targeted at predicting the process of new infections, rather than the current number of people hosting the virus in various conditions. In particular, we do not explicitly describe the dynamics of symptomatic but quarantined people and their exit process (i.e., recovery or, in the worst case, death), since such dynamics have no effect on the spreading process (under the assumption of perfect quarantine). However, if desired, one could describe through appropriate probabilities and time distributions how quarantined people split between those isolated at home and those who get hospitalized, the fraction going to intensive care, and those who unfortunately die. \end{remark} \begin{table}[tbhp] \centering \begin{tabular}{|c|c|c|} \hline Parameter & symbol & COVID-19 fitted value \\ \hline \hline incubation period & I & tri([2,12], mean 6) \\ \hline pre-symptoms period & w & 2 \\ \hline disease period & D & unif([2,12])\\ \hline residual period & E & exp(10) \\ \hline low infection rate & $\lambda_{\rm low}$ & 0.05 \\ \hline high infection rate & $\lambda_{\rm high}$ & 1\\ \hline symptomatic probability & $p_s$ & 0.06 \\ \hline asymptomatic probability & $p_a$ & 0.91\\ \hline super-spreader probability & $p_h$ & 0.03\\ \hline \end{tabular} \caption{Virus-specific parameters.\label{tab1}} \end{table} The parameters introduced so far, summarized in Table \ref{tab1}, are related to specific characteristics of the virus. We now model properties of the specific environment where the virus spreads, taking into account the impact of countermeasures. First, we need to specify the immigration process $\sigma(t)$. To keep the model as simple as possible, we have assumed that the system starts at a given time with $I_0$ new infections, i.e., immigrants arrive as a single burst concentrated at one specific instant. The impact of countermeasures is taken into account in the model in two different ways. First, modulating function $\mu(t)$ can be used to model the instantaneous reduction of the infection rate at time $t$ due to the current mobility restrictions, and, more in general, changes in the environment which affect the ability of the virus to propagate in the susceptible population (such as seasonal effects). Typically, $\mu(t)$ is a decreasing function in the initial part of the epidemics, in response to new regulations introduced by the government, while it goes up again when mobility restrictions are progressively released. Second, we assume that any infected not already found to be positive is tested (e.g., by means of massive swab campaigns) at individual, instantaneous rate $\rho(t)$, which reflects both the amount of resources employed by the health service to discover the infected population, and the effectiveness of tracking. Recall that, when an infected is found positive, we assume it transits to the quarantined state $q$ and stops infecting other people. \begin{figure}[htb] \centering \includegraphics[width=0.9\columnwidth]{mark.pdf} \caption{State transitions of an infected individual.\label{fig:mark}} \end{figure} Fig. \ref{fig:mark} shows the resulting transitions that can occur for the different classes. Note that class $q$ collects all cases known to the health authorities at a given time $t$, and thus coincides with the set of detected cases. Infected in classes $s,a,h$ are still unknown to the health service (but they are detectable). When they stop to be positive, people in classes $a,h$ transit to a class $u$ (undetected), which collects all infected who remain unknown to the health service. Environment-related parameters are summarized in Table \ref{tab2}. \begin{table}[tbhp] \centering \begin{tabular}{|c|c|c|} \hline Parameter & symbol & fitted value for first wave in Italy \\ \hline \hline initial day & $-\Delta t$ & -20 \\ \hline initial number of infected & $I_0$ & 370 \\ \hline modulating function & $\mu(t)$ & $T_a = -3$, $\mu_a = 3.71$ \hspace{19mm} \\ & & $T_b = 30$, $\mu_b = 0.31$, (see Fig. \ref{fig:muitaly}) \\ \hline detection rate & $\rho(t)$ & $\rho(t) = 0.000115 \,t$, \quad (see Fig. \ref{fig:muitaly}) \\ \hline \end{tabular} \vspace{5mm} \caption{Environment-specific parameters.\label{tab2}} \end{table} \begin{remark} We emphasize that the model described so far does not explicitly model spatial effects and sub-populations. As such, it is more suitable to describe a homogeneous scenario, where its environmental parameters (including modulating functions $\mu(t)$ and detection rate $\rho(t)$) can be reasonably assumed to apply to all individuals of the population irrespective of their spatial location. The natural candidate of such scenario is a single nation or just a sub-region of it. By so doing, we can assume that common national regulations are applied, as well as common health-care practices. However, our approach based on Hawkes processes could be extended to incorporate spatial effects, by considering spatio-temporal kernel functions $\nu({\bm x},t)$, where ${\bm x}$ is a spatial vector originated at the point at which a new infection occurs. {\color{black} Another possibility would be to consider a multivariate temporal Hawkes process, where each component represents a homogeneous region, and the different regional processes can interact with each other.} \end{remark} \subsection{Computation of the real-time reproduction number $R(t)$} From our model, it is possible to compute in a native way the average number of infections caused by an individual who gets infected at time $t$, i.e., the real-time reproduction number $R(t)$. To compute $R(t)$, we condition on the duration $x$ of the incubation time, on the duration $y$ of the disease time, on the duration $z$ of the residual time, and on the class assigned to the node getting infected at time $t$ (note that they are all independent of each other): \begin{multline}\label{eq:Rt2} R(t) = \int_x \int_y \int_z \Bigg( \lambda_{\rm low} \int_{0}^{x} \mu(t+\tau) u(t,\tau) {\rm\,d} \tau + p_a \lambda_{\rm low} \int_{x}^{x+w+y+z} \mu(t+\tau) u(t,\tau) {\rm\,d} \tau + \\ (p_s+p_h) \lambda_{\rm high} \int_{x}^{x+w} \mu(t+\tau) u(t,\tau) {\rm\,d} \tau + p_h \lambda_{\rm high} \int_{x+w}^{x+w+y} \mu(t+\tau) u(t,\tau) {\rm\,d} \tau + \\ p_h \lambda_{\rm low} \int_{x+w+y}^{x+w+y+z} \mu(t+\tau) u(t,\tau) {\rm\,d} \tau \Bigg) {\rm\,d} F_E(z) {\rm\,d} F_D(y) {\rm\,d} F_I(x) \end{multline} where $$ u(t,\tau) = e^{-\int_t^{t+\tau} \rho(s) {\rm\,d} s} $$ is the probability that a node which gets infected at time $t$ is still undetected at time $t+\tau$. \section{Model fitting for the first wave of COVID-19 in Italy}\label{sec:firstwave} We fit the model to real data related to the spread of COVID-19 in Italy, publicly available on GitHub \cite{ministero}. Italy was the country where the epidemics first spread outside of China into Europe, causing about 34600 deaths at the end of June 2020 during the first wave. Our main goal was to match the evolution of the number of detected cases, represented in the model by individuals in class $q$. The actual count is provided by the Italian government on a daily basis since February 24th 2020. We take this date as our reference day zero. However, it is largely believed that the epidemics started well before the end of February. Indeed, it became soon clear that detected cases were just the top of a much bigger iceberg, as the prevalence of asymptomatic infection was initially largely unknown, which significantly complicated the first modeling efforts to forecast the epidemic evolution. During June-July 2020, a blood-test campaign (aimed at detecting IgG antibodies) was conducted on a representative population of 64660 people to understand the actual diffusion of the first wave of COVID-19 in Italy \cite{serologico}. As a main result, it has been estimated that 1 482 000 people have been infected. This figure provides a fundamental hint to properly fit our model, and indeed while exploring the parameter space we decided to impose that the total number of predicted cases at the end of June (day 120) is roughly 1 500 000. For the durations $I$,$w$,$D$,$E$ of the different stages of an infection, we have tried to follow estimates in the medical literature. In particular, the duration of the incubation period is believed to range between 2 and 12 days, with a sort of bell shape around about 5 days \cite{incubation,jcm9020538,Qineabc1202}, which we have approximated, for simplicity, by a (asymmetric) triangular distribution with support $[2,12]$ and mean 6. Moreover, we have fixed the duration of the pre-symptomatic phase to 2 days. For the duration of the disease period we have taken a uniform distribution on $[2,12]$, while the residual time is modeled by an exponential distribution with mean 10 days \cite{Byrne2020}. The other virus-related parameters have been set as reported in the third column of Table \ref{tab1}. Note that, since we further apply the external modulating function $\mu(t)$, we could arbitrarily normalize to 1 the value of $\lambda_{\rm high}$, while we set $\lambda_{\rm low} = 0.05$. For what concerns environment-related parameters (see Table \ref{tab2}), a first problem was to choose a proper initial day $-\Delta t$ (recall that day zero is the first day of the trace) at which to start the process with $I_0$ initially infected individuals. While different pairs $(\Delta t, I_0)$ are essentially equivalent, we decided not to start the process with too few cases and too much in advance with respect to day 0, to limit the variance of a single simulation run. We ended up setting $\Delta t = 20$, while $I_0 = 370$ was selected as explained later. \begin{figure}[htb] \centering \includegraphics[width=0.9\columnwidth]{muitaly.pdf} \caption{Chosen profiles and parameters of functions $\mu(t)$ and $\rho(t)$ for the first wave of COVID-19 in Italy.\label{fig:muitaly}} \end{figure} Mobility restrictions in Italy were progressively enforced by national laws starting a few days before day 0, first limited to red zones in Lombardy, and soon extended to the entire country through a series of increasingly restrictive regulations, introduced over the next 30 days. Instead of trying the capture the step-wise nature of such restrictions, we assume $\mu(t)$ to take the simpler profile depicted in Figure \ref{fig:muitaly}, i.e., a high initial value $\mu_a$ before time $T_a$, a low final value $\mu_b$ after time $T_b$, and a linear segment connecting point $(T_a,\mu_a)$ to point $(T_b,\mu_b)$. We decided to set $T_a = -3$ and $T_b = 30$ to reflect the time window in which mobility restriction were introduced. In Fig. \ref{fig:muitaly} we also show our choice for the profile of detection rate $\rho(t)$, i.e., a linear increase starting from day 0, with coefficient $\alpha$, $\rho(t) = \max\{0,\alpha t\}$. This profile is justified by the fact that the first wave caught Italy totally unprepared ($\rho = 0$ before day zero), while massive swabs were only gradually deployed over time after day zero. The critical parameters $I_0,\mu_a,\mu_b,\alpha$ were fitted by a minimum mean square error (MMSE) estimation technique based on the curve of detected cases in the time window $[0-120]$ days, after all other parameters were manually selected as detailed above. \myfig{10}{deteconf}{Evolution of the number of detected cases according to model and real data. Cumulative number (left y axes) and its daily variation (right y axes).} \myfig{10}{totconf}{Evolution of the actual number of cases according to model only. Cumulative number (left y axes) and its daily variation (right y axes).} Fig. \ref{fig:deteconf} shows the final outcome of our fitting, comparing the evolution of the number of detected cases according to model and real data. We show both the cumulative number (left $y$ axes) and its daily increment (right $y$ axes). Analytical predictions for the mean trajectory of detected cases were obtained by averaging 100 simulation runs. The shaded region around analytical curves (barely visible) shows 95\%-level confidence intervals computed for each of the 120 days. We emphasize that a similar good match could be possibly obtained by other sets of parameters. Our purpose here was not to compute the best possible fit in the entire parameter space (which would be nearly impossible), but to show that the model is rich enough to capture the behavior observed on the real trace after a reasonable choice of most of its parameters, driven by their physical meaning. Fig. \ref{fig:totconf} shows instead the evolution of the real number of cases (both the cumulative number and its daily variation) according to the model only, in the absence of data. Note however that we have constrained ourselves to obtain a total number of about 1 500 000 cases on day 120, as suggested by the serological test \cite{serologico}. Interestingly, by looking at the values of $\mu_a$ and $\mu_b$ computed by our MMSE, it appears that the national lockdown was able to reduce the spreading ability of the virus within the Italian population by a factor of about 12 (from 3.71 to 0.31). We will see later on in Fig. \ref{fig:reverse} that our fitting of $\mu(t)$ for the first wave is consistent with mobility trends estimated from the usage of the Apple maps application \cite{appleapp}. \myfig{10}{Rtconf}{Real-time reproduction number computed by the model, compared to its estimation based on the trace of detected case, according to the Wallinga-Teunis method (with 95\% confidence interval denoted as shared region).} In Fig. \ref{fig:Rtconf} we show the real-time reproduction number computed by \equaref{Rt2}. We also applied the classic method of Wallinga-Teunis \cite{wallinga}, implemented as in the R0 package \cite{Obadia2012}, to estimate $R(t)$ from the trace of detected cases. To apply their method, we used a generation time obtained from a Gamma distribution with mean 6.6 (shape 1.87, scale 0.28), which has been proposed for the first wave of COVID-19 in Italy \cite{cereda2020early}. Interestingly, though both estimates of $R(t)$ exhibit qualitatively the same behavior, the model-based value of $R(t)$, which considers also undetected cases, tends to be smaller. \subsection{What-if scenarios} Having fitted the model to the available trace, we proceed to exploit the model to examine interesting what-if scenarios. First, we investigate what would have happened (according to the fitted model) if lockdown restrictions were shifted in time by an amount of days $\delta$. This means that we keep all parameters the same, except that we translate horizontally in time the profile of $\mu(t)$ depicted in Fig. \ref{fig:muitaly}. In Figure \ref{fig:whatif1} we show the total number of cases that would have occurred for values of $\delta \in \{-7,-3,0,3,7\}$. \myfig{10}{whatif1}{What-if scenario: total number of cases if restrictions were shifted in time by $\delta$ days.} We observe that a shift of just 3 days corresponds to a factor of roughly 2 in the number of cases. This translates, dramatically, into an equivalent impact on the number of deaths, if we assume that the mortality rate would have stayed the same\footnote{This is somehow optimistic, since mortality also depends on the saturation level of intensive therapy facilities.} (i.e., $34600/1500000 \sim 2.3\%$). In other words, a postponement (anticipation) of lockdown restrictions by just 3 days wold have caused twice (half) the number of deaths, which is a rather impressive result. \myfig{10}{whatif2}{What-if scenario: impact of detection rate $\rho(t) = \alpha t$ on the real and detected number of cases, varying $\alpha$.} In Figure \ref{fig:whatif2} we investigate instead the impact of detection rate $\rho(t)$, by changing its slope $\alpha$ (recall Fig. \ref{fig:muitaly}). We report both the number of real cases and the number of detected cases predicted by the model, when all other fitted parameters are kept the same. We consider what would have occurred with $\alpha = 0$ (which means that infectious people are never tested), and by doubling the intensity of the detection rate (a tracking system twice more efficient). As expected, with $\alpha = 0$ only symptomatic cases ($p_s = 6\%$) are eventually detected. This time the effect on the final number of cases (or deaths) is not as dramatic as in the previous what-if scenario. This suggests that the impact of mass testing in Italy during the first wave was marginal, and doubling the efforts would not have produced significant changes in the final outcome. \section{Model fitting for the second wave of COVID-19 in Italy}\label{sec:secondwave} The second wave of COVID-19 hit Italy in late summer 2020, as in many other European countries, mainly as en effect of relaxed mobility in July/August and possibly other seasonal effects. It is interesting to compare the second wave with the first wave, by looking at the daily increments of detected cases and deaths, see Fig. \ref{fig:backfromdeath}. \myfig{12}{backfromdeath}{Daily increment of the number of deaths (black curve, right $y$-axes), daily increment of the number of detected (red curve, left $y$ axes), and estimated daily increment of real cases projected back from the curve of deaths (green curve, left $y$-axes).} We observe that the number of daily deaths is similar between the two waves. The daily increment of detected cases, instead, is very different (around 5000 at the peak of the first wave, around 35000 at the peak of the second wave, a 7-fold increase). This can be explained by the much larger capacity of the health service to perform swabs and track down the infected, built on the experience gained from the first wave. It also suggests that, differently from the first wave, the impact of $\rho(t)$ (the individual rate at which an infectious is detected) is expected to be much more important during the second wave than in the first wave, requiring a careful treatment of it in the model. We have indeed tried to fit our model to the second wave in Italy, keeping all parameters related to the virus (previously fitted for the first wave) unchanged (Table \ref{tab1}), and adapting only environment-specific parameters (Table \ref{tab2}). A major difficulty that we had to face was the unknown (at the time of writing) actual diffusion of the virus in the population during the second wave. Recall that, for the first wave, we exploited a blood-test campaign to get a reference for the total number of real cases at the end of the first wave. For the second wave we employed instead a different approach based on a projection back in the past of the increment of deaths. A similar idea has been adopted in \cite{Flaxman2020} to estimate the time-varying reproduction number in different European country at the onset of the first wave. Specifically, we got from \cite{deathstat} the indication of the median (11 days) and IQR (6-18 days) of the amount of time from symptoms onset to death during Oct-Dec 2020, that we fitted by a Gamma distribution (shape 1.65, scale 8.45). By convolving such Gamma distribution with the distribution of incubation time, and the pre-symptoms period, we obtained a distribution of the total time from infection to death, that we used to estimate the time in the past at which each dead person was initially infected. By amplifying the number of infections leading to death by the inverse of the mortality rate we eventually obtained an estimate of the daily increment of real cases, as reported in Fig. \ref{fig:backfromdeath} (green curve, left $y$-axes). We chose August 1st (day 160 on Fig. \ref{fig:backfromdeath}) as starting date of the new infection process producing the second wave in Italy. This time, instead of manually searching for suitable profiles of $\mu(t)$ and $\rho(t)$ generating the expected curves of real and detected cases, we adopted a novel \lq\lq reverse-engineering" approach: we took the daily increments of real and detected cases as input to the model, and computed the functions $\mu(t)$ and $\rho(t)$ that would exactly produce in the model the given numbers of real and detected cases, on each day\footnote{Discretized values of functions $\mu(t)$ and $\rho(t)$ are uniquely determined in the model, once we constrain ourselves to produce a given number of real and detected cases at each time instant.}. \myfig{10}{reverse}{Modulating functions $\mu(t)$ for the first wave (black, fitted) and second wave (blue, reversed), and average mobility according to Apple maps application.} In Fig. \ref{fig:reverse} we show the obtained \lq reversed' $\mu(t)$ (blue curve), starting from day 0 (August 1st) of the time reference adopted for the second wave. We also report the average mobility measured in Italy by the Apple maps application \cite{appleapp}, where we have given equal weight (1/3) to driving, transit and walking mobility. We observe that the \lq reversed' $\mu(t)$ qualitatively follows the same behavior of mobility measured on the maps application, with a gradual increase during the month of August followed by a gradual decrease as people (and the government) started to react to the incipient second wave. For completeness, we have also reported on Fig. \ref{fig:reverse} the fitted $\mu(t)$ for the first wave (black curve). We observe that, during the first wave, the quick introduction of hard lockdown caused an abrupt decay of both measured mobility and fitted $\mu(t)$, characterized by a bigger reduction in a shorter time. The second wave, instead, was characterized by a smoother transition, due to the different choice of applying just partial lockdowns and progressive restrictions more diluted over time\footnote{The fact that, during the second wave, mobility values similar to those of the first wave do not translate into equally similar values of $\mu(t)$ can be attributed to increased awareness of people during the second wave.}. In Fig. \ref{fig:rho} we show instead the \lq reversed' function $\rho(t)$, focusing on the second wave. We also report on the same plot the daily increments of real and detected cases, which allow us to better understand the obtained profile of $\rho(t)$, highlighting an interesting phenomenon occurred around day 30. Indeed, we observe that, during the first month, the epidemic was closely tracked by the national health system, but at some point, around day 30, the curve of detected cases stops increasing, and stays roughly constant during the entire second month, lagging more and more behind the otherwise exploding curve of real cases (time window 30-60). As consequence, function $\rho(t)$, which describes the effectiveness of individual tracking, falls down to a minimum reached at around day 60. This behavior can be interpreted as an effect of the saturation of the capacity to perform swabs, resulting in a progressive collapse of the tracking system, as actually experienced by many people during those days. \myfig{10}{rho}{Reverse detection rate $\rho(t)$ for the second wave (left y-axes), and daily increase of real and detected cases (right y-axes).} Our analysis shows that, in contrast to what might be believed by just looking at the curve of detected cases, September (days 30-60) was, perhaps, the most critical period for the outbreak of the second wave of COVID-19 in Italy. During this period, the detection capacity of the national health system was saturated, and could not keep the pace with the rapid growth of real cases, giving instead the illusion of maintaining the epidemic under control. Our reverse-engineering approach can thus shed some light on what actually happened at the onset of the second wave, and {\em quantitatively} assess the collapse of the tracking system. \section{Conclusions}\label{sec:conclusions} We have proposed a time-modulated version of the Hawkes process to describe the temporal evolution of an epidemic within an infinite population of susceptible individuals. Our approach allows us to take into account precise distributions for the time spent in different stages of the infection, which is of paramount importance when the intensity of countermeasures (mobility restrictions, testing and tracing) varies significantly on time-scales comparable to that of an individual infection. We have applied the model to the spread of COVID-19 in Italy, either by a direct fit of its parameter (first wave), or by a novel reverse fit (second wave) which allows us, in retrospect, to understand from data the time-varying effectiveness of applied countermeasures. Future work will extend the model to overcome some of its current limitations, like the impact of spatial effects and other sources of heterogeneity in the population, such as age groups. We think the proposed approach is promising and could be usefully applied to explain the epidemic progress and forecast/assess the impact of control/mitigation measures.
{'timestamp': '2021-01-05T02:14:45', 'yymm': '2101', 'arxiv_id': '2101.00405', 'language': 'en', 'url': 'https://arxiv.org/abs/2101.00405'}
arxiv
\section{Introduction} \subsection{Overview and Objectives}\label{sec:overview} Cluster randomized trials (CRTs) are pragmatic clinical trials that test interventions applied to groups or clusters \citep{Hayes2009}. Methodology for designing, conducting and analyzing CRTs has been rigorously developed over decades \citep{Turner2017a,Turner2017b}. A principal, but not the sole reason why CRTs are considered is that the intervention has one or more components defined at the cluster level. Increasingly, CRTs employ stepped wedge (SW) designs, which are one-way crossover designs where all clusters start out in the control condition and switch to the intervention at randomly assigned time points \citep{Hussey2007}. Logistical considerations such as the need to deliver the intervention in stages and the desire to eventually implement the intervention in all clusters are key factors involved in the decision to adopt a SW-CRT. Given the increasing popularity of these designs, the development of statistical methods and computational tools for valid analysis is critically important. For the past decade, the design and analysis of SW-CRTs have mostly been based on linear mixed models \citep{LiReview2020}. Particularly, a major direction of research has been to study these methods under different random effects structures whose choice induces a marginal covariance structure \citep{Hooper2016,Kasza2017}. While not as frequently studied in the SW-CRT literature, generalized linear mixed models (GLMM) are a broad class of cluster-specific models to analyze clustered binary outcomes. However, their application carries a couple of caveats. First, with few exceptions (e.g., identity link), the interpretation of the intervention effect changes according to different specifications of the latent random-effects structure. Second, while GLMMs are flexible insofar as accounting for the dependence of observations within clusters via random effects, they may not adequately describe the pattern and magnitude of intraclass correlation structures on the natural measurement scale of the outcomes. This is because exact expressions for the marginal mean and correlation are generally lacking for GLMMs with a non-identity link function \citep{Zeger1988}. Perhaps for this reason, while GLMMs are used in the analysis of SW-CRTs with binary outcomes, they are seldom used as the basis for planning SW-CRTs, with an exception in \citet{Zhou2020} who developed a numerical approach for power calculation using the random-intercept linear probability model. Motivated by the Washington State Expedited Partner Therapy (EPT) trial \citep{Golden2015}, we consider marginal model based analyses of SW-CRTs with binary outcomes and flexible choice of link functions. Marginal models separately specify the mean and the intraclass correlation structures, with the interpretation of the marginal mean parameters remaining the same regardless of correlation specification \citep{Liang1986,Zeger1988}. Further, the marginal modeling approach may be more robust because misspecification of the correlation structure does not affect the consistency of the regression parameter estimator in the marginal mean model. Finally, the marginal modeling framework permits direct estimation of intraclass correlation coefficients (ICCs) and assessing their uncertainty on the natural measurement scale of the outcomes. Such information is particularly useful as input parameters for sample size determination in cluster trials, generally \citep{Preisser2003}, and in SW-CRTs, specifically \citep{LiTurnerPreisser2018}. Accurate reporting of the intraclass correlation structures has been long advocated in parallel CRTs \citep{Preisser2007} and aligns with item 17a of the recent CONSORT extension to SW-CRTs, which recommends reporting of various intraclass correlation estimates to facilitate the planning of future trials \citep{Hemming2018}. \subsection{Motivating Study: The Washington State EPT Trial}\label{sec:EPT} The Washington State EPT trial is a SW-CRT that evaluates the population effect of an expedited patient-delivered partner notification strategy versus the standard partner notification for the treatment of Chlamydia and Gonorrhea infection \citep{Golden2015}. The intervention includes the promotion of patient-delivered partner therapy through commercial pharmacies and targeted provision of public health partner services, and was designed to increase treatment adoption for sex partners of individual heterosexual patients. The randomization is carried out at the level of local health jurisdiction (LHJ), namely the administrative unit corresponding to a single county. Each LHJ is a cluster, and a total of 23 LHJs were randomized from 2007 to 2010 over four waves until the intervention had been disseminated in all LHJs. Cross-sectional surveys were conducted based on sentinel women aged 14 to 25 years in each LHJ at baseline and in between waves to measure the prevalence of Chlamydia and Gonorrhea. Due to the cross-sectional design, different women are included in different periods. Following \citet{Golden2015}, we restrict the analysis to the $22$ LHJs that provide individual-level data on the Chlamydia outcome. Define $Y_{ijk}$ as the binary Chlamydia infection status for sentinel woman $k=1,\ldots,n_{ij}$ surveyed during period $j=1,\ldots,J$ in LHJ $i=1,\ldots,I$; the value of $Y_{ijk}$ equals $1$ if the sentinel woman reports Chlamydia and $0$ otherwise. \citet{LiTurnerPreisser2018} and \citet{Li2020} specified the following marginal mean model for SW-CRTs \begin{equation}\label{eq:mm} g(\mu_{ijk})=\beta_j+X_{ij}\delta, \end{equation} where $\mu_{ijk}$ is the mean of $Y_{ijk}$, $g$ is the link function, $\beta_j$ is the $j$th period effect, $X_{ij}$ is the intervention indicator, and $\delta$ is the time-adjusted average intervention effect on the link function scale. Because it is also of interest to report the within-period and between-period correlations, \citet{LiTurnerPreisser2018} proposed a paired estimating equations approach to simultaneously estimate the intervention effect and correlation parameters. However, in many cross-sectional SW-CRTs, the cluster-period sizes $n_{ij}$'s are large and highly variable. In the EPT trial design, for example, the cluster-by-period diagram in Figure \ref{fig:Fig1} shows that the cluster size $n_{i+}=\sum_{j=1}^J n_{ij}$ ranges from $277$ to $5393$. As the correlation estimating equations can involve as many as ${5393\choose 2}\approx 14.5$ million residual cross-product terms in one cluster, the estimation of correlations via individual-level analysis quickly becomes computationally burdensome or infeasible. With these considerations in mind, this article develops a computationally convenient marginal modeling approach to estimate the intervention effect, the ICCs and their respective sampling variances in SW-CRTs with large and variable cluster sizes. While binary outcomes are the focus of the methods development, application and evaluation of statistical properties of the proposed method, extensions to continuous and count outcomes are discussed in the Supplementary Material (SM). In what follows, we reformulate the estimating equations based on individual-level analysis to ones based on cluster-period means to alleviate the computational challenge without compromising the ability to estimate individual-level ICCs. We allow flexible link functions for the marginal mean and consider the estimation and inference for two multilevel correlation structures appropriate for cross-sectional SW designs. \section{Modeling Cluster-Period means in Cross-Sectional Designs}\label{sec:GEE} Because marginal mean model \eqref{eq:mm} is a function of both period and intervention, we consider collapsing the individual-level outcomes to cluster-period means $\overline{\bm{Y}}_i=(\overline{Y}_{i1},\ldots,\overline{Y}_{iJ})^T=(Y_{i1+}/n_{i1},\ldots,Y_{iJ+}/n_{iJ})^T$, where $Y_{ij+}=\sum_{k=1}^{n_{ij}}Y_{ijk}$ is the cluster-period total, and $n_{ij}$ the cluster-period size. We assume that the cluster-period sizes are variable, which is almost always the case with cross-sectional SW-CRTs. Let the mean of $\overline{\bm{Y}}_i$ be $\bm{\mu}_i=(\mu_{i1},\ldots,\mu_{iJ})^T$, where for a binary outcome $\mu_{ij}=E(Y_{ij+})/n_{ij}$ is the prevalence in the $(i,j)$th cluster-period. Because the right hand side of marginal model \eqref{eq:mm} depends only on cluster and period, aggregating over cluster-periods implies the same marginal model, $g(\mu_{ij})=\beta_j+X_{ij}\delta$. Writing $\bm{\theta}=(\beta_1,\ldots,\beta_J,\delta)^T$, the generalized estimating equations \citep[GEE;][]{Liang1986} for $\bm{\theta}$ are \begin{equation}\label{eq:gee} \sum_{i=1}^I \bm{D}_{1i}^T\bm{V}_{1i}^{-1}(\overline{\bm{Y}}_i-\bm{\mu}_i)=0, \end{equation} where $\bm{D}_{1i}=\partial\bm{\mu}_i/\partial\bm{\theta}^T$ and $\bm{V}_{1i}=\text{cov}(\overline{\bm{Y}}_i)$ is the working covariance matrix parameterized by the individual-level variances and pairwise correlations. This is the usual GEE applied to correlated binomial data, and our novel contribution is to enable the estimation of individual-level ICCs that parameterize the cluster-period mean covariance $\bm{V}_{1i}$. Several prior efforts collapsed individual-level observations for analyzing SW-CRTs. \citet{Hussey2007} suggested a linear mixed model based on cluster-period means with a random intercept. For binary outcomes, their approach only estimates the treatment effect on the risk difference scale and does not estimate valid ICCs defined from the individual-level model under variable cluster sizes (see SM Appendix A for details). \citet{Thompson2018} proposed a permutation test based on cluster-period means. However, their approach assumed working independence and ignored the estimation of correlation structures. Our approach distinguishes from these two earlier efforts by allowing arbitrary link functions in the marginal mean model for binary outcomes as well as by enabling valid estimation and inference for ICC structures. In cross-sectional designs, distinct sets of participants are included in each period, and require modeling both the within-period and between-period correlations for each pair of individual-level outcomes. We consider two multilevel correlation structures: the nested exchangeable and the exponential decay structures. The nested exchangeable correlation structure \citep{LiTurnerPreisser2018} differentiates between the within-period and between-period ICCs. Specifically, this structure assumes a constant correlation $\alpha_0$ between two individual outcomes from the same cluster within the same period, and a constant correlation $\alpha_1$ between two individual outcomes from the same cluster across two periods. Equating $\alpha_1$ with $\alpha_0$ leads to the simple exchangeable structure as in standard GEE analyses \citep{Hussey2007}. The exponential decay correlation structure was recently introduced in the context of linear mixed models \citep{Kasza2017,LiReview2020}. While this structure assumes a constant correlation $\alpha_0$ between two individual outcomes from the same cluster within the same period, it allows the between-period correlation to decay at an exponential rate. Mathematically, the correlation between two outcomes measured in the $j$th and $l$th periods ($1\leq j,l\leq J$) is $\alpha_0\rho^{|j-l|}$ ($0\leq \rho\leq 1$). In the absence of decay ($\rho=1$), the exponential decay structure also reduces to the simple exchangeable structure. Example matrix forms of these correlation structures are provided in STable 1 in the SM. In the following two sections, we develop estimation and inference strategies under each of these correlation structures. \subsection{Nested Exchangeable Correlation Structure}\label{sec:nex} The individual-level correlation structure informs the specification of covariances for cluster-period means. Under the nested exchangeable correlation structure, the diagonal element of $\bm{V}_{1i}$ is \begin{equation}\label{eq:sii} \sigma_{ijj}=\text{var}(\overline{Y}_{ij+})=\frac{\nu_{ij}}{n_{ij}} \left\{1+(n_{ij}-1)\alpha_0\right\}, \end{equation} where $\nu_{ij}=\mu_{ij}(1-\mu_{ij})$ is the binomial variance. The design effect, $1+(n_{ij}-1)\alpha_0$, is the classic variance inflation factor for over-dispersed binomial outcomes. The off-diagonal element of $\bm{V}_{1i}$ is \begin{equation} \sigma_{ijl}=\text{cov}(\overline{Y}_{ij+},\overline{Y}_{il+}) =\sqrt{\nu_{ij}\nu_{il}}\alpha_1. \end{equation} When all $n_{ij}\rightarrow\infty$, $\text{var}(\overline{Y}_{ij+})\rightarrow \nu_{ij}\alpha_0$ and the pairwise cluster-period mean correlation $\text{corr}(\overline{Y}_{ij+},\overline{Y}_{il+})\rightarrow {\alpha_1}/{\alpha_0}$, which is identical to the cluster autocorrelation defined in \citet{Hooper2016} and \citet{LiReview2020} based on linear mixed models. This also suggests that the cluster-period means are approximately exchangeable when all $n_{ij}$'s are large, but such an approximation may be crude in cases such as the motivating study where the $n_{ij}$'s vary from $19$ to $1553$. Define $\bm{\alpha}=(\alpha_0,\alpha_1)^T$, we specify the covariance estimating equations \citep{Zhao1990} to estimate $\bm{\alpha}$ \begin{equation}\label{eq:gamma} \sum_{i=1}^I \bm{D}_{2i}^T\bm{V}_{2i}^{-1}(\bm{S}_i-\bm{\eta}_i)=0, \end{equation} where $\bm{\eta}_i=(\sigma_{i11},\sigma_{i12},\ldots,\sigma_{i22},\ldots)^T$, $\bm{S}_i=(s_{i11},s_{i12},\ldots,s_{i22},\ldots)^T$, $s_{ijl}=(\overline{Y}_{ij+}-\hat{\mu}_{ij})(\overline{Y}_{il+}-\hat{\mu}_{il})$ is the residual cross-product, $\bm{D}_{2i}=\partial \bm{\eta}_i/\partial\bm{\alpha}^T$ and $\bm{V}_{2i}$ is the working variance for $\bm{S}_i$. Parametric specification of working covariances $\bm{V}_{2i}$ requires the joint distributions of within-cluster triplets and quartets, which are not provided from the specification of marginal mean and covariances. Henceforth, a practical strategy is to set $\bm{V}_{i2}$ as identity matrix \citep{Sharples1992}. In this case, the following closed-form updates are implied from \eqref{eq:gamma} \begin{align}\label{eq:solution} \hat{\alpha}_0=\frac{\sum_{i=1}^I\sum_{j=1}^{J}\left(\frac{n_{ij}-1}{n_{ij}}\right)\hat{\nu}_{ij} \left(s_{ijj}-\frac{\hat{\nu}_{ij}}{n_{ij}}\right)} {\sum_{i=1}^I\sum_{j=1}^{J}\left(\frac{n_{ij}-1}{n_{ij}}\right)^2\hat{\nu}_{ij}^2}, ~~~~\hat{\alpha}_1=\frac{\sum_{i=1}^I\sum_{j\neq l}s_{ijl}\sqrt{\hat{\nu}_{ij}\hat{\nu}_{il}}}{\sum_{i=1}^I\sum_{j\neq l} \hat{\nu}_{ij}\hat{\nu}_{il}}. \end{align} Noticeably, even though the cluster-period sizes $n_{ij}$ could be large and pose a computational challenge for individual-level paired estimating equations, cluster-period aggregation reduces the effective cluster sizes to $J$, the number of periods, which rarely exceeds $10$ \citep{Grayling2017b}. On the other hand, because SW-CRTs often involve a limited number of clusters (fewer than $30$), the residual vector $\overline{\bm{Y}}_i-\hat{\bm{\mu}}_i$ could be biased towards zero due to overfitting, leading to finite-sample bias in the estimation of correlation parameters. Here we extend the multiplicative adjustment of \citet{Preisser2008} to the covariance estimating equations \eqref{eq:gamma} by the following argument. Because $E[(\overline{\bm{Y}}_{i}-\hat{\bm{\mu}}_i)(\overline{\bm{Y}}_{i}-\hat{\bm{\mu}}_i)^T]\approx (\bm{I}-\bm{H}_{1i})\text{cov}(\overline{\bm{Y}}_i)$, where $\bm{H}_{1i}=\bm{D}_{1i}(\sum_{i=1}^I\bm{D}_{1i}\bm{V}_{1i}^{-1}\bm{D}_{1i})^{-1}\bm{D}_{1i}^T\bm{V}_{1i}$ is the cluster leverage, a bias-adjusted, and hence more accurate estimator for the covariance of $\overline{\bm{Y}}_i$ is obtained as \begin{equation}\label{eq:correction} \widetilde{\text{cov}}(\overline{\bm{Y}}_i)=(\bm{I}-\bm{H}_{1i})^{-1}(\overline{\bm{Y}}_{i}-\hat{\bm{\mu}}_i)(\overline{\bm{Y}}_{i}-\hat{\bm{\mu}}_i)^T, \end{equation} where $\bm{H}_{1i}$ is evaluated at $\hat{\bm{\theta}}$. Improved estimation of correlation parameters may then be achieved by replacing $\bm{S}_i$ in \eqref{eq:gamma} with $\widetilde{\bm{S}}_i=(\tilde{s}_{i11},\tilde{s}_{i12},\ldots,\tilde{s}_{i22},\ldots)$, where $\tilde{s}_{ijl}$ is the $(j,l)$th element of the bias-adjusted covariance $\widetilde{\text{cov}}(\overline{\bm{Y}}_i)$. We will similarly define the cluster leverage for the covariance estimating equations as $\bm{H}_{2i}=\bm{D}_{2i}(\sum_{i=1}^I\bm{D}_{2i}\bm{V}_{2i}^{-1}\bm{D}_{2i})^{-1}\bm{D}_{2i}^T\bm{V}_{2i}$, which is evaluated at $\hat{\bm{\theta}}$ and $\hat{\bm{\alpha}}$. When the number of clusters $I$ is large, the joint distribution of $I^{1/2}(\hat{\bm{\theta}}-\bm{\theta})$, $I^{1/2}(\hat{\bm{\alpha}}-\bm{\alpha})$ is Gaussian with mean zero and covariances estimated by \begin{equation}\label{eq:cov} I\times \left( \begin{array}{cc} \bm{\Omega} & \bm{0} \\ \bm{Q} & \bm{P} \\ \end{array} \right)\left( \begin{array}{cc} \bm{\Lambda}_{11} & \bm{\Lambda}_{12} \\ \bm{\Lambda}_{12}^T & \bm{\Lambda}_{22} \\ \end{array} \right)\left( \begin{array}{cc} \bm{\Omega} & \bm{Q}^T \\ \bm{0} & \bm{P} \\ \end{array} \right), \end{equation} where $\bm{\Omega}=\left\{\sum_{i=1}^I\bm{D}^T_{1i}\bm{V}_{1i}^{-1}\bm{D}_{1i}\right\}^{-1}$, $\bm{P}=\left\{\sum_{i=1}^I\bm{D}^T_{2i}\bm{V}_{2i}^{-1}\bm{D}_{2i}\right\}^{-1}$, $\bm{Q}=\bm{P}\left\{\sum_{i=1}^I \bm{D}^T_{2i}\bm{V}_{2i}^{-1}\frac{\partial \bm{S}_i}{\partial\bm{\theta}^T}\right\}\bm{\Omega}$, \begin{align*} \bm{\Lambda}_{11}&=\sum_{i=1}^I \bm{C}_{1i}\bm{D}_{1i}^T\bm{V}_{1i}^{-1}\bm{B}_{1i}(\overline{\bm{Y}}_i-\hat{\bm{\mu}}_i) (\overline{\bm{Y}}_i-\hat{\bm{\mu}}_i)^T\bm{B}_{1i}^T\bm{V}_{1i}^{-1}\bm{D}_{1i}\bm{C}_{1i}^T\\ \bm{\Lambda}_{12}&=\sum_{i=1}^I \bm{C}_{1i}\bm{D}_{1i}^T\bm{V}_{1i}^{-1}\bm{B}_{1i}(\overline{\bm{Y}}_i-\hat{\bm{\mu}}_i) (\tilde{\bm{S}}_i-\hat{\bm{\eta}}_i)^T\bm{B}_{2i}^T\bm{V}_{2i}^{-1}\bm{D}_{2i}\bm{C}_{2i}^T\\ \bm{\Lambda}_{22}&=\sum_{i=1}^I \bm{C}_{2i}\bm{D}_{2i}^T\bm{V}_{2i}^{-1}\bm{B}_{2i}(\tilde{\bm{S}}_i-\hat{\bm{\eta}}_i) (\tilde{\bm{S}}_i-\hat{\bm{\eta}}_i)^T\bm{B}_{2i}^T\bm{V}_{2i}^{-1}\bm{D}_{2i}\bm{C}_{2i}^T, \end{align*} where we will discuss the choice of $\{\bm{C}_{1i},\bm{C}_{2i}\}$ and $\{\bm{B}_{1i},\bm{B}_{2i}\}$ in the following. If we set $\bm{C}_{1i}=\bm{I}_{\text{dim}(\bm{\theta})}$, $\bm{C}_{2i}=\bm{I}_{\text{dim}(\bm{\alpha})}$, $\bm{B}_{1i}=\bm{I}_{\text{dim}(\overline{\bm{Y}}_i)}$, $\bm{B}_{2i}=\bm{I}_{\text{dim}(\tilde{\bm{S}}_i)}$, equation \eqref{eq:cov} becomes the robust sandwich variance in the spirit of \citet{Zhao1990}, or BC0. Because the number of clusters included in SW-CRTs are frequently less than $30$, the following finite-sample bias corrections could provide improved inference for $\bm{\theta}$ and $\bm{\alpha}$. Specifically, setting $\bm{C}_{1i}$, $\bm{C}_{2i}$ as identity but $\bm{B}_{1i}=(\bm{I}_{\text{dim}(\overline{\bm{Y}}_i)}-\bm{H}_{1i})^{-1/2}$, $\bm{B}_{2i}=(\bm{I}_{\text{dim}(\tilde{\bm{S}}_i)}-\bm{H}_{2i})^{-1/2}$ results in the bias-corrected covariance that extends \citet{Kauermann2001}, or BC1. Setting $\bm{C}_{1i}$, $\bm{C}_{2i}$ as identity but $\bm{B}_{1i}=(\bm{I}_{\text{dim}(\overline{\bm{Y}}_i)}-\bm{H}_{1i})^{-1}$, $\bm{B}_{2i}=(\bm{I}_{\text{dim}(\tilde{\bm{S}}_i)}-\bm{H}_{2i})^{-1}$ results in the bias-corrected covariance that extends \citet{Mancl2001}, or BC2. Finally, setting $\bm{B}_{1i}$, $\bm{B}_{2i}$ as identity but $\bm{C}_{1i}=\text{diag}\{(1-\min\{\zeta_1,[\bm{D}_{1i}^T\bm{V}_{1i}^{-1}\bm{D}_{1i}]_{jj}\bm{\Omega}\})^{-1/2}\}$, $\bm{C}_{2i}=\text{diag}\{(1-\min\{\zeta_2,[\bm{D}_{2i}^T\bm{V}_{2i}^{-1}\bm{D}_{2i}]_{jj}\bm{P}\})^{-1/2}\}$ extends \citet{Fay2001}, or BC3. Usually we set $\zeta_1=\zeta_2=0.75$ to ensure that multiplicative bias correction is no larger than 2 fold. When $I$ is smaller than 30, each of these bias-corrections could inflate the variance relative to BC0 and potentially improve the finite-sample behaviour of the sandwich variance. \subsection{Exponential Decay Correlation Structure}\label{sec:ed} Under the exponential decay correlation structure, the covariances for cluster-period means $\bm{V}_{1i}$ include diagonal element $\sigma_{ijj}$ defined in equation \eqref{eq:sii}, and off-diagonal element becomes $\sigma_{ijl}=\text{cov}(\overline{Y}_{ij+},\overline{Y}_{il+}) =\sqrt{\nu_{ij}\nu_{il}}\alpha_0\rho^{|j-l|}$. When all $n_{ij}\rightarrow\infty$, the pairwise cluster-period mean correlation $\text{corr}(\overline{Y}_{ij+},\overline{Y}_{il+})\rightarrow\rho^{|j-l|}$, which corresponds to a first-order auto-regressive structure. Again, such an approximation may not be accurate in the Washington State EPT trial because the cluster-period sizes could occasionally be small and quite variable. Unlike the expression obtained under the nested exchangeable correlation structure, $\sigma_{ijl}$ obtained under the exponential decay structure is nonlinear in the decay parameter $\rho$. Based on estimating equations \eqref{eq:gamma} and the bias-adjusted covariance $\widetilde{\bm{S}}_i$, we can show that each update of $(\alpha_0,\rho)$ joint solves the following system of equations \begin{align} &\hat{\alpha}_0=\frac{\sum_{i=1}^I\sum_{j=1}^J \left(\frac{n_{ij}-1}{n_{ij}}\right)\left(\tilde{s}_{ijj}\hat{\nu}_{ij}-\frac{\hat{\nu}^2_{ij}}{n_{ij}}\right) +\sum_{i=1}^I\sum_{j\neq l}\tilde{s}_{ijl}\sqrt{\hat{\nu}_{ij}\hat{\nu}_{il}}\hat{\rho}^{|j-l|}} {\sum_{i=1}^I\sum_{j=1}^{J}\left(\frac{n_{ij}-1}{n_{ij}}\right)^2\hat{\nu}_{ij}^2 +\sum_{i=1}^I\sum_{j\neq l}\hat{\nu}_{ij}\hat{\nu}_{il}\hat{\rho}^{2|j-l|}} \label{eq:eea0}\\ &\sum_{i=1}^I\sum_{j\neq l}|j-l|\tilde{s}_{ijl}\sqrt{\hat{\nu}_{ij}\hat{\nu}_{il}}\hat{\rho}^{|j-l|-1} -\sum_{i=1}^I\sum_{j\neq l}|j-l|\hat{\nu}_{ij}\hat{\nu}_{il}\hat{\alpha}_0\hat{\rho}^{2|j-l|-1}=0.\label{eq:eerho} \end{align} In particular, we observe that the second equation is a polynomial function of $\rho$ to the order of $2|J-1|-1$, and so one can use root-finding algorithms to search for the zero-value within the unit interval. Given each update of the marginal mean parameters, an update of the exponential decay correlation structure can be obtained by iterating between \eqref{eq:eea0} and \eqref{eq:eerho}. The variance estimators for both $\bm{\theta}$ and $\bm{\alpha}$ with finite-sample corrections can be obtained by following the approach in Section \ref{sec:nex}. Extensions of the proposed cluster-period marginal modeling approach for continuous and count outcomes are presented in the SM Appendix B. \section{Considerations on Asymptotic Efficiency}\label{sec:eff} We assess the asymptotic efficiency in estimating the intervention effect $\delta$ based on estimating equations defined for cluster-period means. In the same context, \citet{LiTurnerPreisser2018} provided a paired estimating equations for individual-level outcomes, which in principle serves as the efficiency gold-standard. However, the computational burdens of that approach in analyzing the motivating trial are twofold: those associated with repeatedly inverting a large correlation matrix for marginal mean estimation and those associated with enumerating all pairwise residual cross-products for correlation estimation. These computational disadvantages prohibit the application of individual-level GEE to analyze SW-CRTs with large cluster-period sizes, especially when the correlation model includes more than one parameter. In contrast, the cluster-period GEE converges in seconds because the induced correlation matrix is of dimension $J\times J$ and only $J\choose 2$ pairwise residual products need to be enumerated in each cluster. It is then of interest to study whether the cluster-period GEE compromises efficiency in estimating the intervention effect $\delta$. To proceed, we observe that both the nested exchangeable and exponential decay correlation structures are special cases of the block Toeplitz structure defined in SM Appendix C. In SM Appendix D, we show that, as long as the working correlation model for individual-level data is block Toeplitz, the marginal mean estimating equations for cluster-period means are equivalent to those for individual-level outcomes. Specifically, we define the individual-level estimating equations for $\bm{\theta}$ as $\sum_{i=1}^I \bm{E}_{1i}^T\bm{M}_{1i}^{-1}(\bm{Y}_i-\bm{\vartheta}_i)=\bm{0}$, where $\bm{Y}_i=(Y_{i11},Y_{i12},\ldots,Y_{i21},\ldots)^T$, $\bm{\vartheta}_i=(\mu_{i1}\bm{1}_{n_{i1}}^T,\ldots,\mu_{iJ}\bm{1}_{n_{iJ}}^T)^T$, $\bm{M}_{1i}=\text{cov}(\bm{Y}_i)$, and $\bm{E}_{1i}=\partial\bm{\vartheta}_i/\partial\bm{\theta}^T$, and the following result holds. \begin{theorem}\label{thm:same} Assuming marginal mean model is \eqref{eq:mm} and the individual-level working correlation is block Toeplitz, the quasi-score defined from the cluster-period means and the induced cluster-period mean covariance structure is identical to the quasi-score defined from the individual-level outcomes. That is, $\bm{D}_{1i}^T\bm{V}_{1i}^{-1}(\overline{\bm{Y}}_i-\bm{\mu})=\bm{E}_{1i}^T\bm{M}_{1i}^{-1}(\bm{Y}_i-\bm{\vartheta}_i) $ for each cluster $i$. Similarly, $\bm{D}_{1i}^T\bm{V}_{1i}^{-1}\bm{D}_{1i}=\bm{E}_{1i}^T\bm{M}_{1i}^{-1}\bm{E}_{1i}$. \end{theorem} To establish the above general result under variable cluster-period sizes, a mathematical induction argument (SM Appendix D) is necessary because an analytical inverse cannot be easily obtained for the block Toeplitz matrix. Theorem \ref{thm:same} indicates that there is no loss of asymptotic efficiency for estimating the intervention effect that results from cluster-period aggregation, as long as the induced cluster-period mean correlation matrix is properly specified. Particularly, assuming equal cluster-period sizes and a linear mixed model with Gaussian outcomes, \citet{Grantham2019} suggested that the linear mixed model based on the cluster-period summary results in no loss of information for estimating the treatment effect in SW-CRTs as long as the within-period observations are exchangeable. Theorem \ref{thm:same} generalizes their finding to GEE with arbitrary specification of link and variance functions and further relaxes their equal cluster-period size assumption. Theorem \ref{thm:same} also provides a convenient device to numerically evaluate the asymptotic relative efficiency (ARE) between accurately modeling the cluster-period mean correlations versus using a working independence structure. To further support the application of the proposed approach versus using working independence in analyzing the motivating study, we calculate the ARE in estimating $\delta$ between these two approaches. To do so, we assume a SW-CRT with $22$ clusters and $5$ periods, where the randomization follows the cluster-by-period diagram in Figure \ref{fig:Fig1}. We set the true marginal mean model as equation \eqref{eq:mm} with a logit link. The period effect $\beta_j$'s are specified so that the outcome prevalence decreases from $25\%$ to $20\%$ in the absence of intervention, and the intervention effect corresponds to an odds ratio of $e^\delta=0.75$. To account for variable cluster-period sizes, we resample the cluster-period sizes from the motivating study and obtain $1000$ bootstrap replicates. For the $k$th bootstrap replicate, we obtain \begin{equation*}\label{eq:RE} \tau_k=\frac{\left[(\sum_{i=1}^I \bm{D}_{1i}^T\bm{\Psi}_{1i}^{-1}\bm{D}_{1i})^{-1} (\sum_{i=1}^I \bm{D}_{1i}^T\bm{\Psi}_{1i}^{-1}\bm{V}_{1i}\bm{\Psi}_{1i}^{-1}\bm{D}_{1i}) (\sum_{i=1}^I \bm{D}_{1i}^T\bm{\Psi}_{1i}^{-1}\bm{D}_{1i})^{-1}\right]_{(J+1,J+1)}}{\left[(\sum_{i=1}^I \bm{D}_{1i}^T\bm{V}_{1i}^{-1}\bm{D}_{1i})^{-1}\right]_{(J+1,J+1)}}, \end{equation*} where $\bm{\Psi}_{1i}$ is a $J\times J$ diagonal matrix with the $j$th element as $\nu_{ij}/n_{ij}$ (i.e. working independence covariance model), and all parameters evaluated at the truth. The ARE is then estimated as $\sum_{k=1}^{1000} \tau_k/1000$. Table \ref{tb:MRE} presents the ARE under different true correlation models. It is evident that the efficiency gain from properly modeling the correlations is maximum ($\text{ARE}\approx 44$ when $\alpha_0=\alpha_1=0.1$) when the within-period ICC and between-period ICC are identical, assuming the latter does not exceed the former. The ARE decreases when the within-period ICC decreases, and also when the between-period ICC deviates from the within-period ICC. In the scenario where $\alpha_0=0.02$ and $\alpha_1=0.001$, modeling the correlations is still $60\%$ more efficient than ignoring the correlation structure in estimating $\delta$. These observations highlight the importance of correlation specification in SW-CRTs when the cluster-period sizes are highly variable. \section{Simulation Studies}\label{sec:sim} We conduct two sets of simulation experiments to assess the finite-sample operating characteristics of the cluster-period GEE for analyzing correlated binary outcomes in cross-sectional SW-CRTs. In the first simulation experiment, we focus on a limited number of clusters $I\in\{12,24,36\}$ with treatment sequences randomized across $J=5$ periods. We assume all clusters receive the control condition during the first period $J=1$, and an equal number of clusters cross over to intervention at each wave. We use the \citet{Qaqish2003} method to generate correlated individual-level binary outcomes. The true marginal mean model is given by \eqref{eq:mm}, where $g$ is a logit link and the effect size $\delta=\log(0.5)$. We assume the baseline prevalence of the outcome is $35\%$ and a gently decreasing time trend with $\beta_{j}-\beta_{j+1}=0.1\times (0.5)^j$ for $j\geq 1$. Both the nested exchangeable and the exponential decay correlation structures are considered in simulating the data. When the true correlation is nested exchangeable, we consider $(\alpha_0,\alpha_1)\in\{(0.03,0.015), (0.1,0.05)\}$, representing small to moderate within-period and between-period correlations previously reported \citep{Martin2016b}. When the true correlation is exponential decay, we consider $(\alpha_0,\rho)\in\{(0.03,0.8),(0.1,0.5)\}$ in accordance with values assumed in previous simulations for cohort stepped wedge designs \citep{Li2020}. In this first simulation experiment, we consider relatively large but more variable cluster-period sizes, randomly drawn from DiscreteUniform$(50,150)$. Here, the maximum total number of observations in each cluster is allowed to be $750$, and the individual-level GEE described in \citet{LiTurnerPreisser2018} becomes computationally burdensome to fit due to (1) the enumeration of a maximum of ${750\choose 2}=280,875$ pairwise residual cross-products in each cluster and (2) numerical inversion of a large correlation matrix in each modified Fisher-scoring update. We therefore only consider analyzing the simulated data via the cluster-period GEE with the correct specification of the marginal mean and induced correlation structure. {We simulate $3000$ data replicates, and study the percent relative bias and coverage probability in estimating the marginal intervention effect and correlation parameters.} The comparisons are made between the uncorrected estimating equations (UEE), namely equation \eqref{eq:gamma}, and the matrix-adjusted estimating equations (MAEE), namely equation \eqref{eq:gamma} but now with the bias-adjusted cross-products $\widetilde{\bm{S}}_i$. Table \ref{tb:bias} summarizes the percent relative bias results. Overall, the bias of the intervention effect remains insensitive to bias corrections of the correlation estimating equations, corroborating the findings of \citet{Lu2007} for individual-level GEE. However, when the true correlation structure is nested exchangeable, MAEE substantially reduces the negative bias of UEE in estimating $\alpha_0$ and $\alpha_1$. When the true correlation structure is exponential decay, MAEE similarly reduces the negative bias of UEE in estimating the within-period correlation $\alpha_0$, but comes at a cost of slightly inflating the negative bias in estimating the decay parameter $\rho$, especially when $I=12$. This is because $\alpha_0$ and $\rho$ enter the polynomial estimating equation \eqref{eq:eerho} in a multiplicative fashion, while the updates for $\alpha_0$ and $\alpha_1$ under the nested exchangeable structure are nearly orthogonal. As the number of clusters increase to $I=24$ or $36$, both MAEE and UEE have negligible bias in estimating $\rho$, but MAEE still has notably smaller bias in estimating $\alpha_0$. STable 2 in the SM summarizes the coverage probability for $\delta$. The confidence intervals (CIs) are constructed based on the $t_{I-2}$ quantiles as this approach has been shown to provide robust small-sample behaviour in previous simulations with individual-level GEE \citep{Li2020,ford2020maintaining}. In addition to the model-based variance and the usual sandwich variance, we examine three bias-corrected variances introduced in Section \ref{sec:nex}. {Based on a binomial model with $3000$ replicates, we consider the empirical coverage between $94.2\%$ and $95.8\%$ as close to nominal. STable 2 indicates that the CIs for $\delta$ constructed with the model-based variance or any of the bias-corrected variances generally provide close to nominal coverage, while those based on BC0 frequently lead to under coverage. STable 3 and 4 summarize the coverage probability of the correlation parameters (interval constructed based on the same $t_{I-2}$ distribution). Given the limited number of clusters and variable cluster sizes, the coverage of correlation parameters is frequently below nominal. However, MAEE can substantially improve the coverage of the correlations parameters. Throughout, the CIs constructed based on BC2 provide the best coverage for correlations, a finding that echoes \citet{Perin2017} with alternating logistic regressions.} To further investigate the coverage probability of the correlation parameters with a larger number of clusters, we consider a second set of experiments, with the same simulation design except for smaller cluster-period sizes. Specifically, the cluster-period sizes are randomly drawn from DiscreteUniform$(25,50)$, and the number of clusters $I$ is varied from $12$ to $120$. The coverage results for the intervention effect parameter $\delta$ are largely consistent with those from the first simulation experiment, and are presented in SFigure 1 and 2 in the SM. {However, the results further indicate that the model-based variance and BC2 may lead to over coverage with $I=12$ and $I=24$, and that BC1 seems to have the most robust performance.} Next, Figure \ref{fig:nex1cov} presents the coverage for the nested exchangeable correlation structure when $\alpha_0=0.03$ and $\alpha_1=0.015$. Similar results for $\alpha_0=0.1$ and $\alpha_1=0.05$ are in SFigure 3. These figures indicate that MAEE coupled with BC2 leads to higher and closer to nominal coverage for $\alpha_0$ and $\alpha_1$ compared to UEE. Likewise, MAEE also improves the empirical coverage for $\alpha_0$ and $\rho$ under the exponential decay correlation structure, and the results are presented in SFigure 4 and 5. \section{Analysis of the Washington State EPT Trial} We apply the cluster-period GEE to analyze cluster-period proportions in the Washington State EPT trial. The focus of this analysis is on estimating the intervention effect and the intraclass correlation structure with respect to the Chlamydia outcomes. We consider the marginal model for cluster-period means $\text{logit}(\mu_{ij})=\beta_j+\delta X_{ij}$, where $\beta_j$ $(j=1,\ldots,5)$ is the period effect and $\exp(\delta)$ is the population-averaged odds ratio. To model the within-cluster correlations, we consider the simple exchangeable structure, as well as the nested exchangeable and exponential decay structures. Of note, the simple exchangeable structure is obtained when we enforce $\alpha_1=\alpha_0$ in the nested exchangeable structure or $\rho=1$ in the exponential decay structure. We do not consider the working independence assumption, because reporting ICCs is considered good practice per the CONSORT extension and useful for planning future SW-CRTs \citep{Hemming2018}. Table \ref{tb:overall} summarizes the point estimates and bias-corrected standard errors of the marginal mean and correlation parameters from the analysis of all sentinel women. Informed by the simulation study in Section \ref{sec:sim}, we report the BC1 standard error estimates for all marginal mean parameters and the BC2 standard error estimates for all correlation parameters. The estimated odds ratios due to the EPT intervention are $0.868$, $0.867$ and $0.883$, under the simple exchangeable, nested exchangeable and exponential decay correlation models. All 95\% confidence intervals include one. Because the prevalence of Chlamydia is around 6\% and is considered rare, the odds ratio approximates the relative risk. Therefore, interpreting the odds ratio as a relative risk, we conclude that the EPT intervention results in an approximately $12\%$ reduction in Chlamydial infection among women aged between 14 and 25. This finding is consistent with that in \citet{Golden2015} based on generalized linear mixed models. We additionally report the intraclass correlation estimates and their estimated precisions for the Chlamydia outcome on the natural scale of the measurement. The within-period correlation $\hat{\alpha}_0\approx 0.007$, as estimated from both the nested exchangeable and exponential decay model. Under the nested exchangeable model, the between-period correlation $\hat{\alpha}_1\approx 0.004$, which is approximately one half of within-period correlation. The standard error of the between-period correlation is also much smaller than that of the within-period correlation. Under the exponential decay model, the decay parameter is estimated to be $\hat{\rho}\approx 0.7$, suggesting a moderate degree of between-period correlation decay over five periods. {As an exploratory analysis, we adapt the Correlation Information Criteria \citep[CIC;][]{Hin2009} for the cluster-period GEE and compare the fit of the correlation structures.} Specifically, we define \begin{equation}\label{eq:cic} \text{CIC}_{\text{cp}}=\text{trace}\left[\left(\sum_{i=1}^I \bm{D}_{1i}^T\bm{\Psi}_{1i}^{-1}\bm{D}_{1i}\right)\bm{\Omega}\bm{\Lambda}_{11} \bm{\Omega}\given[\Big]_{\bm{\theta}=\hat{\bm{\theta}}(\bm{R}_i),\bm{\alpha}=\hat{\bm{\alpha}}(\bm{R}_i)}\right], \end{equation} where $\bm{\Psi}_{1i}$ is a $J\times J$ working independence covariance, $\bm{\Omega}\bm{\Lambda}_{11}\bm{\Omega}$ is the bias-corrected sandwich variance of the marginal mean (BC1), and all parameters are evaluated at the estimates under the assumed correlation structure. According to Theorem \ref{thm:same}, as $I\rightarrow\infty$, the limit of \eqref{eq:cic} is identical to the limit of the usual CIC defined for individual-level GEE in \citet{Hin2009} under the marginal mean model \eqref{eq:mm}, providing some justification for using this metric. {From Table \ref{tb:overall}, while the smallest $\text{CIC}_{\text{cp}}$ corresponds to and favors the exponential decay correlation, the $\text{CIC}_{\text{cp}}$ of the simple exchangeable correlation structure is only larger by a small amount. Future simulation studies are needed to better assess the operating characteristics of $\text{CIC}_{\text{cp}}$ for selecting the optimal correlation structures based on cluster-period GEE analysis of SW-CRTs.} To explore treatment effect among subgroups, we perform the cluster-period GEE analyses for adolescent girls (aged between 14 and 19) and adult women (aged greater than 19), and present the results in STable 5 and 6. From STable 5, the intervention leads to a more pronounced reduction of Chlamydia infection among adolescent girls compared to the overall analysis. Under the nested exchangeable correlation model, the intervention effect in odds ratio is estimated as $0.780$, and its 95\% CI $(0.625, 0.972)$ excludes one. In other words, the EPT intervention results in $22\%$ reduction in Chlamydia infection among adolescents. Given that adolescents are at high risk for acquiring sexually transmitted diseases and that research on effectiveness of EPT among this population is limited \citep{Gannon-Loew2017}, our subgroup analysis may provide new evidence. For brevity, the comparison between correlation structures among the adolescent population and the analysis of the adult women subgroup are presented in the SM Appendix E. \section{Discussion} In the analysis of SW-CRTs with binary outcomes, statistical methods are seldom used to simultaneously obtain point and interval estimates for the intervention effect and the ICCs. An exception is the paired estimating equations approach studied in \citet{LiTurnerPreisser2018}. However, that approach is computationally infeasible with large cluster sizes, which are typically seen in cross-sectional SW-CRTs. To address this limitation, we propose a simple and efficient estimating equations approach based on cluster-period means, which resolves the computational burden of the approach based on individual-level observations. {In practice, one could first attempt an individual-level GEE analysis with an appropriate correlation structure. However, if that procedure becomes computationally intensive, the proposed cluster-period GEE provides a valid workaround. Because standard software could only provide valid intervention effect estimates with cluster-period means in SW-CRTs, we have developed an R package \verb"geeCRT" to implement both the individual-level GEE studied in \citet{LiTurnerPreisser2018} and the cluster-period GEE proposed in this article.} {Although individual-level analysis has usually been considered more efficient than cluster-level analysis in CRTs, we have shown in Theorem \ref{thm:same} that the cluster-period GEE and individual-level GEE are asymptotically equally efficient in estimating the treatment effect parameter in cross-sectional SW-CRTs}. The full efficiency of the cluster-period analysis depends on the induced correlation structure, defined in Section \ref{sec:nex} and \ref{sec:ed}. On the other hand, cluster-period analysis of SW-CRTs assuming working independence suffers from statistical inefficiency \citep{Thompson2018}. The numerical study in Section \ref{sec:eff} emphasizes the necessity of carefully characterizing the induced cluster-period correlation when performing a cluster-period analysis. {Finally, the proposed approach enables fast estimation and inference for the correlation parameters, which aligns with the current recommendation in the CONSORT extension to SW-CRTs \citep{Hemming2018}.} The estimating equations method also produces standard errors of the estimated correlations, which can be used to construct interval estimates to further improve planning of future trials. {Our simulations indicate that the cluster-period GEE can estimate the intervention effect with negligible bias, regardless of bias-corrections to the correlation estimating equations via MAEE. However, MAEE substantially reduces the bias of the ICC estimates. On the other hand, while the bias-corrected sandwich variances can provide nominal coverage for $\delta$ even when $I=12$, inference for ICC parameters appears more challenging (see SM Appendix F for a concise summary of findings). We suggest that $30$ to $40$ clusters may be sufficient for the cluster-period MAEE to provide nominal coverage for $\alpha_0$, which generally agrees with \citet{Preisser2008} using individual-level MAEE. In SW-CRTs, a larger number of clusters may be needed to achieve nominal coverage for the between-period correlation ($\alpha_1$ or $\rho$), which differs from findings in \citet{Preisser2008} for parallel CRTs. This difference highlights the requirement for accurate ICC inference can depend on randomization design (parallel versus stepped wedge). A further reason underlying such a difference is that we have simulated unequal cluster-period sizes, under which the sandwich variance becomes more variable \citep{Kauermann2001}. Fortunately, compared to UEE, the use of cluster-period MAEE can substantially mitigate, if not eliminate, the under-coverage of ICC parameters in small samples.} {A reviewer has raised the issue of performing cluster-period analysis using GLMMs in cross-sectional SW-CRTs. As explained in SM Appendix G, with binary outcomes, a rigorous cluster-period analysis using GLMMS may proceed with the cluster-period totals, $\sum_{k=1}^{n_{ij}}Y_{ijk}$, which follows a Binomial distribution. The likelihood principle then directly suggests such cluster-period aggregation leads to the same inference of GLMM parameters. However, the interpretation of the treatment effect parameter in GLMMs is conditional on the latent random effects, and therefore applies only to each cluster, or, strictly speaking, to the population with the same value of the unobserved random effects. In contrast, the treatment effect $\delta$ is averaged over all clusters, and has been argued to bear a more straightforward population-averaged interpretation \citep{Preisser2003,LiTurnerPreisser2018}.} Although the proposed approach is motivated by cross-sectional SW-CRTs, it is equally applicable to parallel cross-sectional longitudinal cluster randomized trials (L-CRTs). In parallel L-CRTs, the intervention effect is parameterized either by the time-adjusted main effect or the treatment-by-time interaction. For both estimands, because cluster-period aggregation implies the same marginal mean model, the proposed GEE approach is valid and can be useful. {Another direction for future research is to extend the proposed approach to analyze closed-cohort SW-CRTs \citep{copas2015designing,LiTurnerPreisser2018,Li2020} and SW-CRTs with continuous recruitment \citep{Grantham2019,hooper2019stepped}. These more recent variants of SW-CRTs have more complex intraclass correlation structures and therefore requires additional considerations in cluster-period analysis.} {One potential limitation of the current study is that we have only considered a marginal mean model without individual-level covariates. Such an unadjusted mean model originates from \citet{Hussey2007} and has been widely applied for planning and analyzing SW-CRTs; see, for example, the recent review in \citet{LiReview2020}. More often than not, the intraclass correlation structures are also defined with respect to the unadjusted mean models in SW-CRTs \citep{Kasza2017,LiTurnerPreisser2018,Li2020,LiReview2020}. However, covariate adjustment may potentially improve the efficiency in estimating the treatment effect. We plan to carry out future work to integrate individual-level covariates into the cluster-period GEE approach, along the lines of the two-stage framework as in \citet{yasui2004evaluation}.} \section{Software} \label{sec5} An R package for our method, \verb"geeCRT", is available online at CRAN. Sample R code, together with a simulated data example is also available from the corresponding author's GitHub page at \url{https://github.com/lifanfrank/clusterperiod_GEE}. \section{Supplementary Material} \label{sec6} Supplementary material is available online at \url{http://biostatistics.oxfordjournals.org}. \section*{Acknowledgments} Research in this article was partially funded through a Patient-Centered Outcomes Research Institute\textsuperscript{\textregistered} (PCORI\textsuperscript{\textregistered} Award ME-2019C1-16196). The statements presented in this article are solely the responsibility of the authors and do not necessarily represent the views of PCORI\textsuperscript{\textregistered}, its Board of Governors or Methodology Committee. Dr. Preisser has received a stipend for service as a merit reviewer from PCORI\textsuperscript{\textregistered}. Dr. Preisser did not serve on the Merit Review panel that reviewed his project. The authors thank Dr. James P. Hughes for sharing the Washington State EPT study data, and Xueqi Wang for discussions and computational assistance. The authors are also grateful to the Associate Editor and two anonymous reviewers for constructive comments. \bibliographystyle{biorefs}
{'timestamp': '2021-01-05T02:19:01', 'yymm': '2101', 'arxiv_id': '2101.00484', 'language': 'en', 'url': 'https://arxiv.org/abs/2101.00484'}
arxiv
\section{Experiments} \subsection{Action Classification} Table.~\ref{tab:action_class} shows action classification performance of our approach in comaprison with other state-of-the-arts in THUMOS14 and ActivityNet1.2 dataset. We use classification mean average precision (mAP) for evaluation. We see that the classification performance of our approach is very competitive with the SOTAs, specially in THUMOS14 we achieve 7.2\% mAP improvement over 3C-Net~\cite{narayan20193cnet}. We also achieve very competitive performance in ActivityNet dataset. Although our approach has not been designed for video action recognition task, it's high performance in action classification reveals the robustness of our method. \begin{table*}[tbp] \centering \begin{tabular}{c|c|c} \hline Methods & THUMOS14 & ActivityNet1.2 \\ \hline iDT+FV~\cite{wang2013action} & 63.1 & 66.5 \\ C3D~\cite{c3d} & - & 74.1 \\ TSN~\cite{Wang2016TemporalSN} & 67.7 & 88.8 \\ W-TALC~\cite{wtalc} & 85.6 & \bf93.2 \\ 3C-Net~\cite{narayan20193cnet} & 86.9 & 92.4 \\ Ours & \bf94.1 & 90.3 \\ \hline \end{tabular} \caption{Action Classification performance of our method with state-of-the-arts methods on THUMOS14 and ActivityNet1.2 dataset in terms of classification mAP. } \label{tab:action_class} \end{table*} \subsection{Detailed Performance on ActivityNet1.2} Table.~\ref{tab:anet_result_details} shows detailed performance of our approach on ActivityNet1.2 dataset in terms of localization mAP for different IoU thresholds. \begin{table*}[htbp] \fontsize{8}{10}\selectfont \centering \begin{tabular}{c|c||r r r r r r r r r r | r} \hline \multirow{2}{*}{\bf Supervision} & \multirow{2}{*}{\bf Method} & \multicolumn{11}{c}{\bf IoU}\\ && \bf0.5 & \bf0.55 & \bf0.6 & \bf0.65 & \bf0.7 & \bf0.75 & \bf0.8 & \bf0.85 & \bf0.9 & \bf0.95 & \bf{AVG} \\ \hline \hline \bf Full & SSN \cite{ssn} & 41.3 & 38.8 & 35.9 & 32.9 & 30.4 & 27.0 & 22.2 & 18.2 & 13.2 & 6.1 & 26.6 \\ \hline \multirow{11}{*}{\bf Weak} & UntrimmedNets \cite{wang2017untrimmednets} & 7.4 & 6.1 & 5.2 & 4.5 & 3.9 & 3.2 & 2.5 & 1.8 & 1.2 & 0.7 & 3.6 \\ & AutoLoc \cite{shou2018autoloc} & 27.3 & 24.9 & 22.5 & 19.9 & 17.5 & 15.1 & 13.0 & 10.0 & 6.8 & 3.3 & 16.0 \\ & W-TALC \cite{wtalc} & 37.0 & 33.5 & 30.4 & 25.7 & 14.6 & 12.7 & 10.0 & 7.0 & 4.2 & 1.5 & 18.0 \\ & TSM~\cite{yu2019weaktsm} & 28.3 & 26.0 & 23.6 & 21.2 & 18.9 & 17.0 & 14.0 & 11.1 & 7.5 & 3.5 & 17.1 \\ & 3C-Net~\cite{narayan20193cnet} & 35.4 & - & - & - & 22.9 & - & - & - & 8.5 & - & 21.1 \\ & CleanNet~\cite{liu2019weaklycleannet} & 37.1 & 33.4 & 29.9 & 26.7 & 23.4 & 20.3 & 17.2 & 13.9 & 9.2 & 5.0 & 21.6 \\ & Liu \emph{et~al}~\cite{liu2019completeness} & 36.8 & - & - & - & - & 22.0 & - & - & - & 5.6 & 22.4 \\ & Islam \emph{et~al}~\cite{islam2020weakly} & 35.2 & - & - & - & 16.3 & - & - & - & - & - & - \\ & BaS-Net~\cite{lee2020backgroundbasnet} & 34.5 & - & - & - & - & 22.5 & - & - & - & 4.9 & 22.2 \\ & DGAM~\cite{shi2020weaklysupervisedgam} & \bf41.0 & 37.5 & 33.5 & 30.1 & 26.9 & 23.5 & 19.8 & 15.5 & \bf10.8 & \bf5.3 & 24.4\\ & \bf{Ours} & \bf41.0 & \bf37.9 & \bf34.6 & \bf31.3 & \bf28.1 & \bf24.8 & \bf21.1 & \bf16.0 & \bf10.8 & \bf5.3 & \bf25.1 \\ \hline \end{tabular} \caption{Comparison of our algorithm with other state-of-the-art methods on the ActivityNet1.2 validation set for temporal action localization.} \label{tab:anet_result_details} \end{table*} \section{More Ablation} Fir.~\ref{fig:ablation_more} shows ablation studies on the hyper-parameters $\alpha$, $\beta$, and drop threshold $\gamma$ on THUMOS14 dataset. AVG mAP is the mean mAP value from IoU threshold 0.1 to 0.7 incremented by 0.1. Fig.~\ref{fig:abl_alpha} shows the performance for different weights on sparsity loss. Without sparsity loss, the model hardly learns any localization. As $\alpha$ increases, localization performance increases as well, and we get the best score for $\alpha=0.8$. Fig.~\ref{fig:abl_beta} reveals the performance improvement for different weights on guide loss. We empirically find that $\beta=0.8$ gives the best performance. In Fig.~\ref{fig:abl_drop}, we see the mAP performance for different values of dropping threshold $\gamma$. Fig.~\ref{fig:abl_seg_th} and Fig.~\ref{fig:abl_seg_anet} show the effect of video length during training for THUMOS14 and ActivityNet respectively. Note that THUMOS14 contains more denser videos with a large number of activities per video. Hence we observe that the performance increase for larger video length for THUMOS14, whereas, ActivityNet performs best for 80 length segments. Also, note that the number of segments are chosen randomly only during training. We use all segments during evaluation. \begin{figure*}[!htbp] \begin{center} \begin{subfigure}{0.3\textwidth} \includegraphics[width=0.9\linewidth]{figures/ablation/alpha.pdf} \caption{} \label{fig:abl_alpha} \end{subfigure} \begin{subfigure}{0.3\textwidth} \includegraphics[width=0.9\linewidth]{figures/ablation/beta.pdf} \caption{} \label{fig:abl_beta} \end{subfigure} \begin{subfigure}{0.3\textwidth} \includegraphics[width=0.9\linewidth]{figures/ablation/gamma.pdf} \caption{} \label{fig:abl_drop} \end{subfigure} \begin{subfigure}{0.3\textwidth} \includegraphics[width=0.9\linewidth]{figures/ablation/number_of_segments_THUMOS.pdf} \caption{} \label{fig:abl_seg_th} \end{subfigure} \begin{subfigure}{0.3\textwidth} \includegraphics[width=0.9\linewidth]{figures/ablation/number_of_segments_ActivityNet.pdf} \caption{} \label{fig:abl_seg_anet} \end{subfigure} \end{center} \caption{(a) Ablation on the weight of sparsity loss. (b) Ablation on the weight of guide loss. (c) Ablation on the drop-threshold for dropping snippets in the HAD module. (d) and (e) Ablation on the number of segments for a video during training.} \label{fig:ablation_more} \end{figure*} \section{More Qualitative Examples} We show more qualitative examples in Fig.~\ref{fig:qual_more}. In Fig.~\ref{fig:444polevaule}, there are several occurrences of Pole Vault activity, and our method can capture most of them. We show some failure examples in Figure.~\ref{fig:188highjump} and Fig.~\ref{fig:85diving}. In Fig.~\ref{fig:188highjump}, our model erroneously captures some activities as high jump. In those erroneous segments, we observe that the person tends to do a high jump activity but restrain in the end without completing the full action. The same goes for Fig.~\ref{fig:85diving}. Previous WTAL approaches~\cite{islam2020weakly, wtalc} have also shown similar issues as an inherent limitation of WTAL methods. Because of the weakly-supervised nature, we infer that some errors related to incomplete activities are inevitable. \begin{figure*}[htbp] \label{fig:qual} \begin{center} \begin{subfigure}[b]{0.8\textwidth} \includegraphics[width=\textwidth]{figures/visual/444PoleVault.pdf} \caption{Pole Vault} \label{fig:444polevaule} \end{subfigure} \begin{subfigure}[b]{0.8\textwidth} \includegraphics[width=\textwidth]{figures/visual/188HighJump.pdf} \caption{High Jump} \label{fig:188highjump} \end{subfigure} \begin{subfigure}[b]{0.8\textwidth} \includegraphics[width=\textwidth]{figures/visual/85Diving.pdf} \caption{Diving} \label{fig:85diving} \end{subfigure} \end{center} \caption{Qualitative results on THUMOS14. The horizontal axis denotes time. On the vertical axis, we sequentially plot the ground truth, our predicted localization, and our prediction score. (b) and (c) represent failure examples of our approach. } \label{fig:qual_more} \end{figure*} \section{Introduction} \label{sec:intro} Temporal action localization refers to the task of predicting the start and end times of all action instances in a video. There has been remarkable progress in fully-supervised temporal action localization \cite{Tran2018ACL, ssn, frcnn, lin2018bsn, xu2019gtad}. However, annotating the precise temporal ranges of all action instances in a video dataset is expensive, time-consuming, and error-prone. On the contrary, weakly supervised temporal action localization (WTAL) can greatly simplify the data collection and annotation cost. \begin{figure}[!ht] \centering \includegraphics[width=0.47\textwidth]{figures/introduction.pdf} \caption{The existing MIL framework does not necessarily capture the full extent of an action instance. In this example of a diving activity. (a) shows the ground-truth localization, and (b) shows the prediction from an MIL-based WTAL framework. The MIL framework only captures the most discriminative part of the diving activity, ignoring the beginning and ending parts of the full action.} \label{fig:intro} \vspace{-0.4cm} \end{figure} WTAL aims at localizing and classifying all action instances in a video given only video-level category label during training stage. Most existing WTAL methods rely on the multiple instance learning (MIL) paradigm \cite{wtalc, liu2019completeness, islam2020weakly}. In this paradigm, a video consists of several snippets; snippet-level class scores, commonly known as Class Activation Sequences (CAS), are calculated and then temporally pooled to obtain video-level class scores. The action proposals are generated by thresholding the snippet-level class scores. However, this framework has a major issue: it does not necessarily capture the full extent of an action instance. As training is performed to minimize the video-level classification loss, the network predicts higher CAS values for the discriminative parts of actions, ignoring the less discriminative parts. For example, an action might consist of several sub-actions \cite{hou2017real}. In the MIL paradigm, only a particular sub-action might be detected, ignoring the other parts of the action. An illustrative example of a diving activity is presented in Figure \ref{fig:intro}. We observe that only the most discriminative location of the full diving activity is captured by the MIL framework. Capturing only the most distinctive part of an action is sufficient to produce a high video-level classification accuracy, but does not necessarily result in good temporal localization performance. Another issue with the existing framework is modeling the background activity effectively so that background frames are not included in the temporal localization prediction. It has been shown previously that background activity plays an important role in action localization \cite{lee2020backgroundbasnet}. Without differentiating the background frames from the foreground ones, the network might include the background frames to minimize foreground classification loss, resulting in many false positive localization predictions. In this paper, we propose a new WTAL framework named HAM-Net with a hybrid attention mechanism to solve the above-mentioned issues. Attention mechanism has been used in successfully used in deep learning \cite{Islam_2020_DOAGAN, vaswani2017attention, Shi_2020_CVPR_attention_modeling}. HAM-Net produces soft, semi-soft and hard attentions to detect the full temporal span of action instances and to model background activity, as illustrated in Figure~\ref{fig:full_model}. Our framework consists of (1) a classification branch that predicts class activation scores for all action instances including background activity, and (2) an attention branch that predicts the ``action-ness'' scores of a video snippet. The snippet-level class activation scores are also modulated by three snippet-level attention scores, and temporally pooled to produce video-level class scores. To capture the full action instance, we drop the more discriminative parts of the video, and focus on the less discriminative parts. We achieve this by calculating semi-soft attention scores and hard attention scores for all snippets in the video. The semi-soft attention scores drop the more discriminative portions of the video by assigning zero value to the snippets that have soft-attention score greater than a threshold, and the scores for the other portions remain the same as the soft-attention scores. The video-level classification scores guided by the semi-soft attentions contain only foreground classes. On the other hand, the hard-attention score drops the more discriminative parts of the video, and assigns the attention scores of the less discriminative parts to one, which ensures that video-level class scores guided by this hard attention contain both foreground and background classes. Both the semi-soft and hard attentions encourage the model to learn the full temporal boundary of an action in the video. To summarize, our contributions are threefold: (1) we propose a novel framework with a hybrid attention mechanism to model an action in its entirety; (2) we present a background modeling strategy by attention scores guided using an auxiliary background class; and (3) we achieve state-of-the-art performance on both the THUMOS14 \cite{THUMOS14} and ActivityNet \cite{activitynet} datasets. Specifically, we outperform state-of-the-art methods by 2.2\% mAP at IoU threshold 0.5 on the THUMOS14 dataset, and 1.3\% mAP at IoU threshold 0.75 on the ActivityNet1.2 dataset. \section{Related Work} \label{sec:related_work} \subsubsection{Action Analysis with Full Supervision} Due to the representation capability of deep learning based models, and the availability of large scale datasets \cite{THUMOS14, activitynet, charades, AVA, kinetics}, significant progress has been made in the domain of video action recognition. To design motion cues, the two-stream network \cite{simonyan2014two} incorporated optical flow \cite{horn1981opticalflow} as a separate stream along with RGB frames. 3D convolutional networks have demonstrated better representations for video \cite{i3d, c3d, Tran2018ACL}. For fully-supervised temporal action localization, several recent methods adopt a two-stage strategy \cite{Tran2018ACL, ssn, frcnn, lin2018bsn}. \subsubsection{Weakly Supervised Temporal Action Localization} In terms of exisiting WTAL methods, UntrimmedNets \cite{wang2017untrimmednets} introduced a classification module for predicting a classification score for each snippet, and a selection module to select relevant video segments. On top of that, STPN \cite{stpn} added a sparsity loss and class-specific proposals. AutoLoc \cite{shou2018autoloc} introduced the outer-inner contrastive loss to effectively predict the temporal boundaries. W-TALC \cite{wtalc} and Islam and Radke \cite{islam2020weakly} incorporated distance metric learning strategies. MAAN \cite{yuan2018maan} proposed a novel marginalized average aggregation module and latent discriminative probabilities to reduce the difference between the most salient regions and the others. TSM \cite{yu2019weaktsm} modeled each action instance as a multi-phase process to effectively characterize action instances. WSGN \cite{fernando2020weaklywsgn} assigns a weight to each frame prediction based on both local and global statistics. DGAM \cite{Shi_2020_CVPR_attention_modeling} used a conditional Variational Auto-Encoder (VAE) to separate the attention, action, and non-action frames. CleanNet \cite{liu2019weaklycleannet} introduced an action proposal evaluator that provides pseudo-supervision by leveraging the temporal contrast in snippets. 3C-Net \cite{narayan20193cnet} adopted three loss terms to ensure the separability, to enhance discriminability, and to delineate adjacent action sequences. Moreover, BaS-Net \cite{lee2020backgroundbasnet} and Nguyen \emph{et~al} \cite{nguyen2019weaklybackgroundmodeling} modeled background activity by introducing an auxiliary background class. However, none of these approaches explicitly resolve the issue of modeling an action instance in its entirety. To model action completeness, Hide-and-Seek \cite{Singh2017HideandSeekFA} hid part of the video to discover other relevant parts, and Liu \emph{et~al} \cite{liu2019completeness} proposed a multi-branch network where each branch predicts distinctive action parts. Our approach has similar motivation, but differs in that we hide the most discriminative parts of the video instead of random parts. \section{Proposed Method} \label{sec:proposed_method} \begin{figure*}[!ht] \centering \includegraphics[width=1\textwidth]{figures/model.pdf} \caption{Overview of our proposed framework HAM-Net. Snippet-level features of both RGB and flow frames are extracted and separately fed into a classification branch and an attention branch with a hybrid attention mechanism. Three attention scores are calculated: soft attention, semi-soft attention, and hard attention, which are multiplied with snippet-level classification scores to obtain attention-guided class scores. The network is trained using four attention-guided losses: base classification loss (BCL), soft attention loss (SAL), semi-soft attention loss (SSAL), and hard attention loss (HAL), as well as sparsity loss and guide loss. } \label{fig:full_model} \end{figure*} \subsection{Problem Formulation} Assume a training video $V$ containing activity instances chosen from $n_c$ activity classes. A particular activity can occur in the video multiple times. Only the video-level action instances are given. Denote the video-level activity instances as $\mathbf{y} \in \{0,1\}^{n_c}$, where $y_{j}=1$ only if there is at least one instance of the $j$-th action class in the video, and $y_{j}=0$ if there is no instance of the $j$-th activity. Note that neither the frequency nor the order of the action instances in the video is provided. Our goal is to create a model that is trained only with video-level action classes, and predicts temporal location of activity instances during evaluation, {\em i.e.}, for a testing video it outputs a set of tuples $(t_s, t_e, \psi, c)$ where $t_s$ and $t_e$ are the start and end frames of an action, $c$ is the action label, and $\psi$ is the activity score. \subsection{Snippet-Level Classification} In our proposed HAM-Net, as illustrated in Figure~\ref{fig:full_model}, for each video, we first divide it into non-overlapping snippets to extract snippet-level features. Using a snippet-level representation rather than a frame-level representation allows us to use existing 3D convolutional features extractors that can effectively model temporal dependencies in the video. Following the two-stream strategy \cite{i3d, feichtenhofer2016convolutional} for action recognition, we extract snippet-level features for both the RGB and flow streams, denoted as ${{\bf x}_{i}^{\text{RGB}} \in \mathbb{R}^D}$ and ${{\bf x}_{i}^{\text{Flow}} \in \mathbb{R}^D}$ respectively. We concatenate both streams to obtain full snippet features ${{\bf x}_{i} \in \mathbb{R}^{2D}}$ for the $i$-th snippet, resulting in a high-level representation of the snippet feature that contains both appearance and motion cues. To determine the temporal locations of all activities in the video, we calculate the snippet-level classification scores from classification branch, which is a convolutional neural network that outputs the class logits commonly known as Class Activation Sequences (CAS) \cite{shou2018autoloc}. We denote the snippet level CAS for all classes for the $i$-th snippet as $\mathbf{s}_i \in \mathbb{R}^{c+1}$. Here, the $c+1$-th class is the background class. Since we only have the video-level class scores as ground truth, we need to pool the snippet-level scores $\mathbf{s}_i$ to obtain video-level class scores. There are several pooling strategies in the literature to obtain video-level scores from snippet level scores. We adopt the top-k strategy \cite{islam2020weakly, wtalc} in our setting. Specifically, the temporal pooling is performed by aggregating the top-k values from the temporal dimension for each class: \begin{equation}\label{eq:tpool} v_j = \max_{\substack{ l \subset \{1,2,\ldots,T \} \\ |l| = k }} \frac{1}{k} \sum_{i \in l} \mathbf{s}_{i}(j) \end{equation} Next, we calculate the video-level class scores by applying softmax operations along the class dimension: \begin{equation}\label{eq:vid_score} p_j = \frac{\exp(v_j)}{\sum_{j'=1}^{c+1} \exp(v_j')} \end{equation} where $j=1,2,\ldots,c+1$. The base classification loss is calculated as the cross entropy loss between the ground-truth video-level class scores $\mathbf{y}$ and the predicted scores $\mathbf{p}$: \begin{equation}\label{eq:L_base_fb} \mathcal{L}_{\text{BCL}} = -\sum_{j=1}^{c+1} y_j \log(p_j) \end{equation} Note that every untrimmed video contains some background portions where there are no actions occurring. These background portions are modeled as a separate class in the classification branch. Hence, the ground-truth background class $y_{c+1}=1$ in Eqn.~\ref{eq:L_base_fb}. One major issue of this approach is that there are no negative samples for the background class, and the model cannot learn background activity by only optimizing with positive samples. To overcome this issue, we propose a hybrid attention mechanism in the attention branch to further explore the ``action-ness'' score of each segment. \subsection{A Hybrid Attention Mechanism for Weak Supervision} To suppress background classes from the video, we incorporate an attention module to differentiate foreground and background actions following the background modeling strategy in several weakly-supervised action detection papers \cite{nguyen2019weaklybackgroundmodeling, lee2020backgroundbasnet, liu2019weaklycleannet}. The goal is to predict an attention score for each snippet that is lower in the frames where there is no activity instance (i.e.,~background activity) and higher for other regions. Although the classification branch predicts the probability of background action in the snippets, a separate attention module is more effective to differentiate between the foreground and background classes for several reasons. First, most of the actions in a video occur in regions where there are high motion cues; the attention branch can initially detect the background region only from motion features. Second, it is easier for a network to learn two classes (foreground vs.~background) rather than a large number of classes with weak supervision. \subsubsection{Soft Attention Score} The input to the attention module is the snippet-level feature $x_i$, and it returns a single foreground attention score $a_i$: \begin{equation} a_i = g({\bf x}_i; \Theta), \end{equation} where $a_i \in [0, 1]$, and $g(\cdot; \Theta)$ is a function with parameters $\Theta$ that is designed with two temporal convolution layers followed by a sigmoid activation layer. To create negative samples for the background class, we multiply the snippet level class logit (i.e.,~CAS) $s_i(j)$ for each class $j$ with the snippet-level attention score $a_i$ for the $i$-th snippet, and obtain attention-guided snippet-level class scores $s^{\text{attn}}_{i}(j) = s_i(j) \otimes a_i$, where $\otimes$ is the element-wise product. $s^{\text{attn}}$ serves as a set of snippets without any background activity, which can be considered as negative samples for the background class. Following Eqns.~\ref{eq:tpool} and ~\ref{eq:vid_score}, we obtain video level attention-guided class scores $p^{\text{attn}}_{j}$ for class label $j$: \begin{equation v^{\text{attn}}_{j} = \max_{\substack{ l \subset \{1,2,\ldots,T \} \\ |l| = k }} \frac{1}{k} \sum_{i \in l} \mathbf{s}^{\text{attn}}_{ i}(j) \end{equation} \begin{equation p^{\text{attn}}_j = \frac{\exp(v^{\text{attn}}_{j})}{\sum_{j'=1}^{c+1} \exp(v^{\text{attn}}_{j'})} \end{equation} where $j=1,2,\ldots,c+1$. Note that $p^{\text{attn}}_j$ does not contain any background class, since the background class has been suppressed by the attention score $a_i$. From $p^{\text{attn}}_j$, we calculate the soft attention-guided loss (SAL) function \begin{equation}\label{eq:L_base_f} \mathcal{L}_{\text{SAL}} = -\sum_{j=1}^{c+1} y_{j}^f \log(p_j ) \end{equation} Here, $y^f_{j}$ contains only the foreground activities, i.e., the background class $y_{c+1}^f=0$, since the attention score suppresses the background activity. \subsubsection{Semi-Soft Attention Score} Given the snippet-level class score $s_i$ and soft-attention score $a_i$ for the $i$-th snippet, we calculate the semi-soft attention scores by thresholding the soft attention $a_i$ by a particular value $\gamma \in [0,1]$, \begin{align*} {a}^{\text{semi-soft}}_{i} &= \begin{cases} a_i, & \text{if} \ a_i < \gamma \\ 0, & \text{otherwise} \end{cases} \end{align*} Note that the semi-soft attention ${a}^{\text{semi-soft}}_{i}$ both drops the most discriminative regions and attends to the foreground snippets only; hence, the semi-soft attention guided video-level class scores will only contain foreground activities. This design helps to better model the background, as discussed in the ablation studies section. Denote the video-level class scores associated with semi-soft attention as $p^{\text{semi-soft}}_{ j}$, where $j=1,2,\ldots,c+1$. We calculate the semi-soft attention loss: \begin{equation} \label{eq:L_drop_fb} \mathcal{L}_{\text{SSAL}} = -\sum_{j=1}^{c+1} y_j^f \log(p^{\text{semi-soft}}_{ j}) \end{equation} where $y^f$ is the ground truth label without background activity, i.e., $y^f_{c+1}=0$, since the semi-soft attention suppresses the background snippets along with removing the most discriminative regions. \subsubsection{Hard Attention Score} In contrast to semi-soft attention, hard attention score is calculated by \begin{align*} {a}^{\text{hard}}_{i} = \begin{cases} 1, & \text{if} \ a_i < \gamma \\ 0, & \text{otherwise} \end{cases} \end{align*} With hard attention score, we obtain another set of video-level class scores by multiplying them with the original snippet-level logit $s_i(j)$ and temporally pooling the scores following Eqn.~\ref{eq:tpool} and Eqn.~\ref{eq:vid_score}. We obtain the hard-attention loss: \begin{equation} \label{eq:L_drop_f} \mathcal{L}_{\text{HAL}} = -\sum_{j=1}^{c+1} y_j \log(p^{\text{hard}}_{ j}) \end{equation} where $y$ is the ground truth label with background activity, i.e., $y_{c+1}=1$, since the hard attention does not suppress the background snippets, rather, it only removes the more discriminative regions of a video. \subsubsection{Loss Functions} Finally, we train our proposed HAM-Net using the following joint loss function: \begin{equation} \begin{split} \mathcal{L} &= \lambda_0 \mathcal{L}_{\text{BCL}} + \lambda_1 \mathcal{L}_{\text{SAL}} + \lambda_2 \mathcal{L}_{\text{SSAL}} + \lambda_3 \mathcal{L}_{\text{HAL}} \\ &+ \alpha \mathcal{L}_{\text{sparse}} + \beta \mathcal{L}_{\text{guide}} \end{split} \end{equation} where $\mathcal{L}_{\text{sparse}}$ is sparse loss, $\mathcal{L}_{\text{guide}}$ is guide loss, and $\lambda_0$, $\lambda_1$, $\lambda_2$, $\lambda_3$, $\alpha$, and $\beta$ are hyper-parameters. The sparsity loss $\mathcal{L}_{\text{sparse}}$ is based on the assumption that an action is recognizable from a sparse subset of the video segments \cite{stpn}. The sparsity loss is calculated as the L1-norm of the soft-attention scores: \begin{equation} \mathcal{L}_{\text{sparse}} = \sum_{i=1}^{T} |a_i| \end{equation} Regarding the guide loss $\mathcal{L}_{\text{guide}}$, we consider the soft-attention score $a_i$ as a form of binary classification score for each snippet, where there are only two classes, foreground and background, the probabilities of which are captured by $a_i$ and $1-a_i$ . Hence, $1-a_i$ can be considered as the probability of the $i$-th snippet containing background activity. On the other hand, the background class is also captured by the class activation logits $\mathbf{s}_i (\cdot) \in \mathbb{R}^{c+1}$. To guide the background class activation to follow the background attention, we first calculate the probability of a particular segment being background activity, \begin{equation} \bar{s}_{c+1} = \frac{\exp(s_{c+1})} {\sum_{j=1}^c \exp(s_j)} \end{equation} and then add a guide loss so that the absolute difference between the background class probability and the background attention is minimized: \begin{equation} \mathcal{L}_{\text{guide}} = \sum_{i=1}^T |1 - a_i - \bar{s}_{c+1}| \end{equation} \iffalse \subsubsection{Hard Attention Drop (HAD) Module.} In weakly-supervised learning, the network focuses too much on the most discriminative parts of the input data, ignoring less discriminative regions. To overcome this problem, we design a Hard Attention Drop (HAD) Module that drops the most discriminative parts of the video to focus on other less discriminative parts. This strategy models the action completeness, which helps the network to detect the full action instance. We measure the most discriminative regions as the snippets where the action-ness scores or soft-attention scores are higher. We show the architecture of the HAD branch in Figure~\ref{fig:full_model}. Given the snippet-level class score $s_i$ and soft-attention score $a_i$ for the $i$-th snippet, we calculate two attention scores: \textbf{semi-soft attention} and \textbf{hard attention}, by thresholding the soft attention $a_i$ by a particular value $\gamma \in [0,1]$, \begin{align*} {a}^{\text{semi-soft}}_{i} &= \begin{cases} a_i, & \text{if} \ a_i > \gamma \\ 0, & \text{otherwise} \end{cases} \\ {a}^{\text{hard}}_{i} &= \begin{cases} 1, & \text{if} \ a_i > \gamma \\ 0, & \text{otherwise} \end{cases} \end{align*} Both ${a}^{\text{hard}}_{i}$ and ${a}^{\text{semi-soft}}_{i}$ drop the regions with high probability of foreground activity, and, as a result, the network can focus on regions with lower attention scores. To clarify the motivation behind these two attentions, hard attention ${a}^{\text{hard}}_{i}$ only drops the most discriminative snippets, but keeps the others including both foreground and background. Hence, the video-level class score guided by this hard attention will contain both foreground and background classes. On the other hand, the semi-soft attention ${a}^{\text{semi-soft}}_{i}$ both drops the most discriminative regions and attends to the foreground snippets only; hence, the semi-soft attention guided video-level class scores will only contain foreground activities. This design helps to better model the background, as discussed in the ablation studies section. From these two attentions, we obtain two sets of video-level class scores by multiplying them with the original snippet-level logit $s_i(j)$ and temporally pooling the scores following Eqn.~\ref{eq:tpool} and Eqn.~\ref{eq:vid_score}. Denote the video-level class scores as $p^{\text{semi-soft}}_{ j}$ and $p^{\text{hard}}_{ j}$, where $j=1,2,\ldots,c+1$. We calculate two loss functions from the semi-soft and hard attention: \begin{equation} \label{eq:L_drop_fb} \mathcal{L}_{\text{SSAL}} = -\sum_{j=1}^{c+1} y_j \log(p^{\text{semi-soft}}_{ j}) \end{equation} where $y$ is the ground truth label with background activity, i.e., $y_{c+1}=1$, since the hard attention does not suppress the background snippets; rather, it only removes the most discriminative regions, and \begin{equation} \label{eq:L_drop_f} \mathcal{L}_{\text{HAL}} = -\sum_{j=1}^{c+1} y_j^f \log(p^{\text{hard}}_{ j}) \end{equation} where $y^f$ is the ground truth label without background activity, i.e., $y^f_{c+1}=0$, since the semi-soft attention suppresses the background snippets along with removing the most discriminative regions. We add $\mathcal{L}_{\text{SSAL}}$ and $\mathcal{L}_{\text{HAL}}$ to obtain the attention-guided classification loss \begin{equation} \mathcal{L}_{\text{AL}} = \mathcal{L}_{\text{SSAL}} + \mathcal{L}_{\text{HAL}} \end{equation} \subsubsection{Sparsity loss.} The sparsity loss $\mathcal{L}_{\text{sparse}}$ is based on the assumption that an action is recognizable from a sparse subset of the video segments \cite{stpn}. The sparsity loss is calculated as the L1-norm of the soft-attention scores: \begin{equation} \mathcal{L}_{\text{sparse}} = \sum_{i=1}^{T} |a_i| \end{equation} \subsubsection{Guide loss.} We can consider the soft-attention score $a_i$ as a form of binary classification score for each snippet, where there are only two classes, foreground and background, the probabilities of which are captured by $a_i$ and $1-a_i$ . Hence, $1-a_i$ can be considered as the probability of the $i$-th snippet containing background activity. On the other hand, the background class is also captured by the class activation logits $\mathbf{s}_i (\cdot) \in \mathbb{R}^{c+1}$. To guide the background class activation to follow the background attention, we calculate the probability of a particular segment being background activity from CAS, \begin{equation} \bar{s}_{c+1} = \frac{\exp(s_{c+1})} {\sum_{j=1}^c \exp(s_j)} \end{equation} and then add a guide loss so that the absolute difference between the background class probability and the background attention is lower: \begin{equation} \mathcal{L}_{\text{guide}} = \sum_{i=1}^T |1 - a_i - \bar{s}_{c+1}| \end{equation} \subsubsection{Total loss.} Finally, the joint loss function is denoted as \begin{equation} \mathcal{L} = \lambda_1 \mathcal{L}_{\text{MIL}} + \lambda_2 \mathcal{L}_{\text{AL}} + \alpha \mathcal{L}_{\text{sparse}} + \beta \mathcal{L}_{\text{guide}} \end{equation} where $\lambda_1$, $\lambda_2$, $\alpha$, and $\beta$ are hyper-parameters. \fi \subsection{Temporal Action Localization} For temporal localization, we first discard classes which have video-level class score less than a particular threshold (set to $0.1$ in our experiments). For the remaining classes, we first discard the background snippets by thresholding the soft attention scores $a_i$ for all snippets $i$, and obtain class-agnostic action proposals by selecting the one-dimensional connected components of the remaining snippets. Denote the candidate action locations as $\{(t_s, t_e, \psi, c)\}$, where $t_s$ is the start time, $t_e$ is the end time, and $\psi$ is the classification score for class $c$. We calculate the classification score following the outer-inner score of AutoLoc \cite{shou2018autoloc}. Note that for calculating class-specific scores, we use the attention-guided class logits $s^{\text{attn}}_{c}$, \begin{align} & \psi = \psi_{\text{inner}} - \psi_{\text{outer}} + \zeta p_c^{\text{attn}} \\ & \psi_{\text{inner}} = \text{Avg}({s}^{\text{attn}}_{c}(t_s: t_e)) \\ & \psi_{\text{outer}} = \text{Avg}({s}^{\text{attn}}_{c}(t_s-l_m: t_s) + {s}^{\text{attn}}_{c}(t_e: t_e+l_m)) \end{align} where $\zeta$ is a hyper-parameter, $l_m = (t_e-t_s)/4$, $p_c^{\text{attn}}$ is the video-level score for class $c$, and ${s}^{\text{attn}}_{c}(\cdot)$ is the snippet-level class logit for class $c$. We apply different thresholds for obtaining action proposals, and remove the overlapping segments with non-maximum suppression. \section{Experiments} \label{sec:experiments} \subsection{Experimental Settings} \subsubsection{Datasets} We evaluate our approach on two popular action localization datasets: THUMOS14 \cite{THUMOS14} and ActivityNet1.2 \cite{activitynet}. \textbf{THUMOS14} contains 200 validation videos for training and 213 testing videos for testing with 20 action categories. This is a challenging dataset with around 15.5 activity segments and 71\% background activity per video. \textbf{ActivityNet1.2} dataset contains 4,819 videos for training and 2,382 videos for testing with 200 action classes. It contains around 1.5 activity instances (10 times sparser than THUMOS14) and 36\% background activity per video. \subsubsection{Evaluation Metrics} For evaluation, we use the standard protocol and report mean Average Precision (mAP) at various intersection over union (IoU) thresholds. The evaluation code provided by ActivityNet \cite{activitynet} is used to calculate the evaluation metrics. \subsubsection{Implementation Details} For feature extraction, we sample the video streams into non-overlapping 16 frame chunks for both the RGB and the flow stream. Flow streams are created using the TV-L1 algorithm \cite{TVL1}. We use the I3D network \cite{i3d} pretrained on the Kinetics dataset \cite{kinetics} to extract both RGB and flow features, and concatenate them to obtain 2048-dimensional snippet-level features. During training we randomly sample 500 snippets for THUMOS14 and 80 snippets for ActivityNet, and during evaluation we take all the snippets. The classification branch is designed as two temporal convolution layers with kernel size 3, each followed by LeakyReLU activation, and a final linear fully-connected layer for predicting class logits. The attention branch consists of two temporal convolution layers with kernel size 3 followed by a sigmoid layer to predict attention scores between 0 and 1. We use the Adam \cite{Kingma2015AdamAM} optimizer with learning rate 0.00001, and train for 100 epochs for THUMOS14 and 20 epochs for ActivityNet. For THUMOS14, we set $\lambda_0=\lambda_1=0.8$, $\lambda_2=\lambda_3=0.2$, $\alpha=\beta=0.8$, $\gamma=0.2$, and $k=50$ for top-k temporal pooling. For ActivityNet, we set $\alpha=0.5$, $\beta=0.1$, $\lambda_0=\lambda_1=\lambda_2=\lambda_3=0.5$, and $k=4$, and apply additional average pooling to post-process the final CAS. All the hyperparameters are determined from grid search. For action localization, we set the thresholds from 0.1 to 0.9 with a step of 0.05, and perform non-maximum suppression to remove overlapping segments. \subsection{Ablation Studies}\label{subsec:ablation} We conduct a set of ablation studies on the THUMOS14 dataset to analyze the performance contribution of each component of our proposed HAM-Net. Table \ref{tab:ablation} shows the performance of our method with respect to different loss terms. We use ``AVG mAP" for the performance metric, which is the average of mAP values for different IoU thresholds (0.1:0.1:0.7). The first five experiments are trained without SSAL or HAL loss, i.e., without any temporal dropping mechanism, which we denote as ``{MIL-only mode}'', and the remaining experiments trained with those losses are denoted as ``{MIL and Drop mode}''. Figure~\ref{fig:vis_abl_loss} shows the localization prediction of different experiments on a representative video. Our analysis shows that all the loss components are required to achieve the maximum performance. \begin{table}[ht] \fontsize{9}{9}\selectfont \centering \begin{tabular}{c c c c c c c c c c} \hline \multirow{2}{*}{$\mathcal{L}_{\text{BCL}}$}& \multirow{2}{*}{$\mathcal{L}_{\text{SAL}}$}& \multirow{2}{*}{$\mathcal{L}_{\text{HAL}}$}& \multirow{2}{*}{$\mathcal{L}_{\text{SSAL}}$}& \multirow{2}{*}{$\mathcal{L}_{\text{sparse}}$} & \multirow{2}{*}{$\mathcal{L}_{\text{guide}}$} & {AVG}\\ &&&&&& mAP \\ \hline \hline 1) \text{\ding{51}} & - & - & - & - & - & 24.6 \\ 2) \text{\ding{51}} & \text{\ding{51}}& - & - & - & - & 30.8 \\ 3) \text{\ding{51}} & \text{\ding{51}}& - & - & - & \text{\ding{51}} & 28.9 \\ 4) \text{\ding{51}} & \text{\ding{51}}& - & - & \text{\ding{51}} & - & 30.9 \\ 5) \text{\ding{51}} & \text{\ding{51}}& - & - & \text{\ding{51}} & \text{\ding{51}} & \bf34.8 \\ \hline 6) \text{\ding{51}} & \text{\ding{51}} & \text{\ding{51}} & \text{\ding{51}} &- & - & 30.9 \\ 7) \text{\ding{51}} & \text{\ding{51}} & \text{\ding{51}} & \text{\ding{51}} & - & \text{\ding{51}} & 31.1 \\ 8) \text{\ding{51}} & \text{\ding{51}} & \text{\ding{51}} & \text{\ding{51}} & \text{\ding{51}} & - & 37.9 \\ 9) \text{\ding{51}} & \text{\ding{51}} & \text{\ding{51}} & - & \text{\ding{51}} & \text{\ding{51}} & 36.6 \\ 10) \text{\ding{51}} & \text{\ding{51}} & - & \text{\ding{51}} & \text{\ding{51}} & \text{\ding{51}} & 38.1 \\ 11) \text{\ding{51}} & \text{\ding{51}} & \text{\ding{51}} & \text{\ding{51}} & \text{\ding{51}} & \text{\ding{51}} & \bf39.8 \\ \hline \end{tabular} \caption{Ablation study on the effectiveness of different combination of loss functions in the localization performance on THUMOS14 in terms of mAP. Here, AVG mAP means the average of mAP values from IoU thresholds 0.1 to 0.7. Adding ${\mathcal{L}_{\text{AL}}}$ in the total loss function improves the mAP from 34.8 to 39.8.} \label{tab:ablation} \end{table} \begin{figure}[htbp] \centering \includegraphics[width=0.47\textwidth]{figures/abl_losses.png} \caption{Visualization of the effects of different loss functions on the final localization for a video containing the Long Jump activity. (a) is the ground-truth action location. (b) represents only MIL loss, which predicts many false positives. After adding sparsity and guide loss, in (d) we get rid of those false positives, but still cannot capture full temporal boundaries. (e) shows results from our approach which captures full action boundaries.} \label{fig:vis_abl_loss} \vspace{-0.2cm} \end{figure} \subsubsection{Importance of sparsity and guide loss} Table~\ref{tab:ablation} shows that both sparsity and guide loss are important to acheive better performance. Specifically, in ``MIL-only mode'', adding both sparsity and guide loss provides 4\% mAP gain, and in ``MIL and Drop mode'', the mAP gain is 9\%, suggesting that these losses are more important in ``MIL and Drop mode''. Note that for SSAL and HAL, the discriminativeness of a snippet is measured by the soft-attention scores that are learned by sparsity and guide loss. Without sparsity loss, the majority of the soft-attention scores remain close to 1, making the snippet dropping strategy ineffective. Moreover, the guide loss itself does not increase the localization performance significantly without the sparsity loss (experiment 3 and experiment 7 in Table~\ref{tab:ablation}); however, combined with sparsity loss it shows the best performance improvement (experiment 5 and experiment 11 in Table~\ref{tab:ablation}). \subsubsection{Importance of attention losses} We observe that the attention losses can significantly improve the performance. Table~\ref{tab:ablation} shows that only incorporating $\mathcal{L}_{\text{SAL}}$ achieves 6.2\% average mAP gain over the BCL-only model. From experiment-9 and experiment-10 in Table~\ref{tab:ablation}, we see that both HAL and SSAL individually improve the performance, and we get the best performance when we combine them. Specifically, the combination of HAL and SSAL improves the performance by 5\% over the best score in ``MIL-only mode''. Figure \ref{fig:qual_examples} shows visualization examples of the effectiveness of the losses on a representative video. We can observe that the MIL-only model fails to capture several parts of a full action instance (i.e.~, Long Jump). Incorporating attention losses helps to capture the action in its entirety. \subsubsection{Importance of dropping snippets by selective thresholding} For calculating the HAL loss and the SSAL loss, we drop the more discriminative parts of the video and train on the less discriminative parts, assuming that focusing on less discriminative parts will help the model to learn the completeness of actions. To confirm our assumption here, we create two baselines: ``\textbf{ours with random drop}'' where we randomly drop video snippets, similar to Hide-and-Seek \cite{Singh2017HideandSeekFA}, and ``\textbf{ours with inverse drop}'', where we drop the less discriminative parts instead of dropping the most discriminative parts. We show the performance comparison between these models in Figure~\ref{fig:sub_base}. Results show that randomly dropping snippets is slightly more effective than the baseline, and dropping the less discriminative parts decreases the localization performance. Our approach performs much better than randomly dropping snippets or dropping less discriminative snippets, which proves the efficacy of selectively dropping more discriminative foreground snippets. \begin{figure}[h!] \begin{center} \begin{subfigure}{0.23\textwidth} \includegraphics[width=0.98\linewidth]{figures/ablation/ablation_baselines.pdf} \vspace{-0.2cm} \caption{} \label{fig:sub_base} \end{subfigure} \begin{subfigure}{0.23\textwidth} \includegraphics[width=0.98\linewidth]{figures/ablation/weight_for_attention.pdf} \vspace{-0.2cm} \caption{} \label{fig:sub_l2} \end{subfigure} \end{center} \vspace{-0.40cm} \caption{(a) Ablation study on the importance of dropping snippets by selective thresholding. Other approaches like random dropping or inverse selective thresholding do not work well. (b) Ablation study on the importance of SSAL and HAL. A lower weight causes the model to learn only the most distinctive parts, and a higher weight gives too much focus to the less distinctive parts.} \label{fig:ablation_hp} \vspace{-0.3cm} \end{figure} \subsubsection{Ablation on $\lambda_2$ and $\lambda_3$} For this analysis, we set $\lambda_2=\lambda_3=\lambda$. In Figure~\ref{fig:sub_l2}, we analyze the effect of $\lambda$ to the performance. Note that $\lambda=0$ denotes ``MIL only mode", which achieves an average mAP of 34.8\%. Increasing the value of $\lambda$ results in performance improvement until $\lambda$ reaches 0.2, after which we observe performance degradation. The reason is that a lower weight does not incorporate $\mathcal{L}_{\text{SSAL}}$ and $\mathcal{L}_{\text{HAL}}$ effectively during training. On the contrary, a higher weight provides too much importance on the less discriminative parts, which might cause the model to ignore the more discriminative regions in every iteration, resulting in poor localization performance. The optimum value of 0.2 balances out both of the issues. \begin{table*}[htbp!] \fontsize{9}{9}\selectfont \centering \begin{tabular}{c c | c||r r r r r r r | r} \hline \multirow{2}{*}{} & \multirow{2}{*}{\bf Method} & \multirow{2}{*}{\bf Feature} & \multicolumn{8}{c}{\bf IoU}\\ \cline{4-11} & & & \bf0.1 & \bf0.2 & \bf0.3 & \bf0.4 & \bf0.5 & \bf0.6 & \bf0.7 & \bf AVG \\ \hline \hline \multirow{7}{*}{} & R-C3D \cite{Xu2017RC3DRC} & - & 54.5 & 51.5 & 44.8 & 35.6 & 28.9 &- &- & -\\ & SSN \cite{ssn} & - & 66.0 & 59.4 & 51.9 & 41.0 & 29.8 & - & - & - \\ & BSN \cite{lin2018bsn} & - & - & - & 53.5 & 45.0 & 36.9 & 28.4 & 20.0 & - \\ & G-TAD \cite{xu2019gtad} & - & - & - & 54.5 & 47.6 & 40.2 & \bf30.8 & \bf23.4 & -\\ & P-GCN \cite{Zeng_2019_ICCV} & - & \bf69.5 & \bf67.8 & \bf63.6 & \bf57.8 & \bf49.1 & - & - & -\\ \hline \multirow{16}{*}{} & Hide-and-Seek \cite{Singh2017HideandSeekFA} & - & 36.4 & 27.8 & 19.5 & 12.7 & 6.8 & - & -& -\\ & UntrimmedNets \cite{wang2017untrimmednets} & - & 44.4 & 37.7 &28.2 & 21.1 & 13.7 & -& -& -\\ & STPN \cite{stpn} & I3D & 52.0 & 44.7 & 35.5 & 25.8 & 16.9 & 9.9 & 4.3 & 26.4 \\ & AutoLoc \cite{shou2018autoloc} & UNT & - & - & 35.8 & 29.0 & 21.2 & 13.4 & 5.8 & -\\ & W-TALC \cite{wtalc} & I3D & 55.2 & 49.6 & 40.1 & 31.1 & 22.8 &-& 7.6& -\\ & Liu \emph{et~al}~\cite{liu2019completeness} & I3D & 57.4 & 50.8 & 41.2 & 32.1 & 23.1 & 15.0 & 7.0 & 32.4 \\ & MAAN \cite{yuan2018maan} & I3D & 59.8 & 50.8 & 41.1 & 30.6 & 20.3 & 12.0 & 6.9 & 31.6\\ & TSM \cite{yu2019weaktsm}& I3D & - & - & 39.5 & - & 24.5 & - & 7.1& -\\ & CleanNet \cite{liu2019weaklycleannet} & UNT & - & - & 37.0 & 30.9 & 23.9 & 13.9 & 7.1 & -\\ & 3C-Net \cite{narayan20193cnet} & I3D & 56.8 & 49.8 & 40.9 & 32.3 & 24.6 & - & 7.7 & -\\ & Nguyen \emph{et~al}~\cite{nguyen2019weaklybackgroundmodeling} & I3D & 60.4 & 56.0 & 46.6 & 37.5 & 26.8 & 17.6 & 9.0 & 36.3 \\ & WSGN \cite{fernando2020weaklywsgn} & I3D & 57.9 & 51.2 & 42.0 & 33.1 & 25.1 & 16.7 & 8.9 & 33.6\\ & Islam \emph{et~al}~\cite{islam2020weakly} & I3D & 62.3 & - & 46.8 & - & 29.6 & - & 9.7 & -\\ & BaS-Net \cite{lee2020backgroundbasnet} & I3D & 58.2 & 52.3 & 44.6 & 36.0 & 27.0 & 18.6 & 10.4 & 35.3 \\ & DGAM \cite{Shi_2020_CVPR_attention_modeling} & I3D & 60.0 & 54.2 & 46.8 & 38.2 & 28.8 & 19.8 & 11.4 & 37.0 \\ & \bf{HAM-Net (Ours)} & I3D & \bf65.4 & \bf59.0 & \bf50.3 & \bf41.1 & \bf31.0 & \bf20.7 & \bf11.14 & \bf39.8 \\ \hline \end{tabular} \caption{Comparison of our algorithm with other state-of-the-art methods on the THUMOS14 dataset for temporal action localization.} \label{tab:thumos_result} \vspace{-0.3cm} \end{table*} \subsection{Performance Comparison to State-of-the-Art} Table~\ref{tab:thumos_result} summarizes performance comparisons between our proposed HAM-Net and state-of-the-art fully-supervised and weakly-supervised TAL methods on the THUMOS14 dataset. We report mAP scores at different IoU thresholds. `AVG' is the average mAP for IoU 0.1 to 0.7 with step size of 0.1. With weak supervision, our proposed HAM-Net achieves state-of-the-art scores on all IoU thresholds. Specifically, HAM-Net achieves 2.2\% more mAP than the current best scores at IoU threshold 0.5. Moreover, our HAM-Net outperforms some fully-supervised TAL models, and even shows comparable results with some recent fully-supervised TAL methods. In Table~\ref{tab:anet_result}, we evaluate HAM-Net on the ActivityNet1.2 dataset. HAM-Net outperforms other WTAL approaches on ActivityNet1.2 across all metrics, verifying the effectiveness of our proposed HAM-Net. \begin{table}[h!] \fontsize{9}{9}\selectfont \centering \begin{tabular}{c|c||r r r | r} \hline \multirow{2}{*}{} & \multirow{2}{*}{\bf Method} & \multicolumn{4}{c}{\bf IoU}\\ \cline{3-6} && \bf0.5 & \bf0.75 & \bf0.95 & \bf{AVG} \\ \hline \hline \bf Full & SSN & 41.3 & 27.0 & 6.1 & 26.6 \\ \hline \multirow{11}{*}{\bf Weak} & UntrimmedNets & 7.4 & 3.2 & 0.7 & 3.6 \\ & AutoLoc& 27.3 & 15.1 & 3.3 & 16.0 \\ & W-TALC & 37.0 & 12.7 & 1.5 & 18.0 \\ & Islam \emph{et~al}& 35.2 & - & - & - \\ & TSM & 28.3 & 17.0 & 3.5 & 17.1 \\ & 3C-Net& 35.4 & - & - & 21.1 \\ & CleanNet & 37.1 & 20.3 & 5.0 & 21.6 \\ & Liu \emph{et~al} & 36.8 & 22.0 & 5.6 & 22.4 \\ & BaS-Net & 34.5 & 22.5 & 4.9 & 22.2 \\ & DGAM& \bf41.0 & 23.5 & \bf5.3 & 24.4\\ & \bf{HAM-Net (Ours)} & \bf41.0 & \bf24.8 & \bf5.3 & \bf25.1 \\ \hline \end{tabular} \caption{Comparison of our algorithm with other state-of-the-art methods on the ActivityNet1.2 validation set for temporal action localization. AVG means average mAP from IoU 0.5 to 0.95 with 0.05 increment.} \label{tab:anet_result} \vspace{-0.3cm} \end{table} \subsection{Qualitative Performance} We show some representative examples in Fig.~\ref{fig:qual_examples}. For each video, the top row shows example frames, the next row represents ground-truth localization, ``Ours'' is our prediction, and ``Ours w/o HAL \& SSAL'' is ours trained without $\mathcal{L}_{\text{HAL}}$ and $\mathcal{L}_{\text{SSAL}}$. Fig.~\ref{fig:qual_examples} shows that our model clearly captures the full temporal extent of activities, while ``ours w/o HAL \& SSAL'' focuses only on the more discriminative snippets. \begin{figure}[h!] \centering \begin{subfigure}[b]{0.4\textwidth} \includegraphics[width=\textwidth]{figures/visual/896_highjump.png} \vspace{-0.6cm} \caption{High Jump} \label{fig:highjump} \end{subfigure} \begin{subfigure}[b]{0.4\textwidth} \includegraphics[width=\textwidth]{figures/visual/1309_diving.png} \vspace{-0.6cm} \caption{Diving} \label{fig:diving} \end{subfigure} \vspace{-0.4cm} \caption{Qualitative results on THUMOS14. The horizontal axis denotes time. On the vertical axis, we sequentially plot the ground truth detection, our detection scores, and detection scores of ours without HAL and SSAL. SSAL and HAL helps to learn the full context of an action.} \label{fig:qual_examples} \end{figure} \vspace{-0.2cm} \section{Conclusion} We presented a novel framework called HAM-Net to learn temporal action localization from only video-level supervision during training. We introduced a hybrid attention mechanism including soft, semi-soft, and hard attentions to differentiate background frames from foreground ones and to capture the full temporal boundaries of the actions in the video, respectively. We perform extensive analysis to show the effectiveness of our approach. Our approach achieves state-of-the-art performance on both the THUMOS14 and ActivityNet1.2 dataset. \section{Acknowledgments} This material is based upon work supported by the U.S.~Department of Homeland Security under Award Number 2013-ST-061-ED0001. The views and conclusions contained in this document are those of the authors and should not be interpreted as necessarily representing the official policies, either expressed or implied, of the U.S. Department of Homeland Security. \section{To Reviewer 1 (R1)} We thank the reviewer for helpful comments. Regarding the inequalities in Eq. 1 and Eq. 5, we agree with the reviewer that $l=k$ should make more sense as we are calculating the average of top-k activations. We will rewrite Eq.1 and Eq.5 in a cleaner way in the final paper as suggested by the reviewer. We also thank the reviewer for pointing out the typos in the definition of semi-soft and hard-attention. We will correct them in the final submission. [Q1] Regarding grid-search for hyperparameter tuning, A separate validation set was randomly generated from the 30\% of the training data. We will indicate this in the final paper. \section{To Reviewer 3 (R3)} \quad [C1] In Figure 4, combination of semi-soft and ``hard" attention is used in the Hide\&Seek style approach. To clarify, in Fig. 4(a), ``ours with random drop" denotes `semi-soft(random)+hard(random)' which achieves average mAP 35.69\%, and ``ours" denotes `semi-soft(discriminative)+hard(discriminative)' which achieves average mAP of 39.8\%. We also performed experiemnts on `semi-soft(random)' that achieves 34.8\% average mAP, `semi-soft(random)+hard(discriminative)' that achieves 37.9\% average mAP, `semi-soft(discriminative)+hard(random)' that achieves 38.4\% average mAP. We will report these scores in the final paper. 'Semi-soft(discriminative)' and 'hard(discriminative)' have already been reported in Table.~1 (Exp.~9 and Exp.~10 respectively) in the main paper. [W2] Regarding the grid-search, please see the comment to Reviewer 1. [W3] Regarding separating the new components from prior components, our main contribution is the hybrid attention mechanism with background modeling. The other loss components (e.g. guide loss and sparsity loss) are incorporated to enhance the hybrid attention strategy. We performed ablations on the prior components to clarify how these components affect the attention mechanism. We will clarify it in the final paper. [C2] Regarding the term "hard" attention, we will include a comment about it in the final paper as suggested. [C3] Regarding the difference between our approach and Nguyen \emph{et~al}., although Nguyen \emph{et~al}. also proposed an attention branch to model the background class effectively, our attention scores are utilized to model both background activity and action completeness. Nguyen \emph{et~al}. introduces the attention scores to perform attention-weighted average pooling of the frame-level features to produce video-level foreground and background features. However, we do not explicitly modulate the frame-level features by the attention scores, rather, the class logits are modulated by the attention scores, and temporally pooled to produce video level scores. Moreover, three attention scores (soft, semi-soft, and hard) are calculated from our attention branch to model both action completeness and background activity. [C4] Note that the attention scores are calculated from the attention branch that consists of two temporal convolution layers with kernel size 3 (please refer to the 'implementation details' on the attention branch). Hence, we assume the attention scores should be similar for similar sub-actions in the video, as we do not apply any long-range temporal modeling between different snippets apart from the two temporal convolution layers. We do not assume all discriminative sub-actions will have have large soft-attention in the initial phase of the training. However, as the training progresses, the network will focus on less discriminative sub-actions [C5] We will report the standard deviation in the final paper. [C6] Regarding the small improvement in ActivityNet1.2, note that the average mAP in the ActivityNet1.2 is calculated by averaging mAP from IoU threshols 0.5 to 0.95 with 0.05 increment, whereas average mAP in THUMOS14 is calculated by averaging mAP from 0.1 to 0.7 with 0.1 increment. Hence, it's apparent that the improvement on ActivityNet would be smaller than that on Thumos14, as we are using higher IoU thresholds for ActivityNet. To see the detailed performance in ActivityNet1.2, please refer to the Table.~2 in the supplemental. [C7] The snippet length is 16 frames. We will clarify it in the final paper. [C8] l is the set of snippet indices, and l(m) is the m-th element. [C9] Thanks for pointing the discrepancy. We will fix this notation in the final paper. \section{To Reviewer 4 (R4)} \quad [Q1] The major difference between our work and Zhong \emph{et~al}.~, Zheng \emph{et~al}.~ and BaS-Net is discussed below: - BaS-Net modulates the frame-level features by the attention scores and produce suppressed class scores from the modulated features, whereas we do not modulate the frame-level features. Moreover, our hybrid attention modules are designed to model both action completeness and background activity. - Both Zheng \emph{et~al}.~ and Zhong \emph{et~al}.~ performed iterative erasing steps to gradually find the discriminative action parts. Our action completeness mechanism has similar motivation. However, we perform the whole operation in a single step. Moreover, Zheng \emph{et~al}. incorporates class specific attention scores and drops the frames that have the top-p class attention scores, whereas our attention module is class agnostic and frame dropping is performed by thresholding. Zhong \emph{et~al}.~ separately erases frames for each category, and incorporates conditional random field (FC-CRF) to retrieve the ignored actionness snippets. We believe our approach is simpler, and the hybrid of three attentions to model both completeness and background category is novel in weakly supervised action localization. [Q2] To clarify, the guide loss (Eqn.~13) ensures that the soft-attention scores follow the background class scores from the classification branch, and the sparsity loss (Eqn.~12) makes the soft-attention scores to have very low values in the background frames. Hence, although we do not have any temporal annotation to train the attention module, both the guide loss and the sparsity loss help the soft-attention to have higher values in the foreground frames and lower values in the background frames. However, as discussed in the main paper, the soft-attention scores will focus only on the most discriminative parts of an action instance ignoring the full action extent. By dropping the most discriminative segments from the video, the semi-soft attention scores will focus on the less discriminative action segments which helps the model to capture the complete action. \section{To Reviewer 5 (R5)} \quad [Q1] Regarding handling of the overlapping actions, note that both THUMOS14 and ActivityNet1.2 contain only non-overlapping actions. We believe that localizing overlapping actions without any temporal supervision is an ill defined problem. To our knowledge, most of the prior works on weakly-supervised action localization focus on localizing non-overlapping actions, and we also have the same assumption in our work. Regarding failure cases, we reported failure examples in Fig.2 in the supplemental. [Q2] Regarding small improvement in ActivityNet1.2, please refer to the response to Reviewer 3 ([C6]). Moreover, as most of the prior works only reported ActivityNet1.2 performance, we have also reported the performance on ActivityNet1.2 instead of ActivityNet1.3 for proper comparison with the SOTA methods. [Q3] We will include the missing related works in the final paper. \end{document}
{'timestamp': '2021-03-26T01:07:25', 'yymm': '2101', 'arxiv_id': '2101.00545', 'language': 'en', 'url': 'https://arxiv.org/abs/2101.00545'}
arxiv
\section*{Abstract} Angiogenesis is the process by which blood vessels form from pre-existing vessels. It plays a key role in many biological processes, including embryonic development and wound healing, and contributes to many diseases including cancer and rheumatoid arthritis. The structure of the resulting vessel networks determines their ability to deliver nutrients and remove waste products from biological tissues. Here we simulate the Anderson-Chaplain model of angiogenesis at different parameter values and quantify the vessel architectures of the resulting synthetic data. Specifically, we propose a topological data analysis (TDA) pipeline for systematic analysis of the model. TDA is a vibrant and relatively new field of computational mathematics for studying the shape of data. We compute topological and standard descriptors of model simulations generated by different parameter values. We show that TDA of model simulation data stratifies parameter space into regions with similar vessel morphology. The methodologies proposed here are widely applicable to other synthetic and experimental data including wound healing, development, and plant biology. \section*{Author summary} Vascular networks play a key role in many physiological processes, by delivering nutrition to, and removing waste from, biological tissues. In cancer, tumors stimulate the growth of new blood vessels, via a process called angiogenesis. The resulting vascular structure comprises many inter-connected vessels which lead to emergent morphologies that influence the rate of tumor growth and treatment efficacy. In this work, we consider several approaches to summarize the morphology of synthetic vascular networks generated from a mathematical model of tumor-induced angiogenesis. We find that a topological approach can be used quantify vascular morphology of model simulations and group the simulations into biologically interpretable clusters. This methodology may be useful for the diagnosis of abnormal blood vessel networks and quantifying the efficacy of vascular-targeting treatments. \section*{Introduction} Blood vessels deliver nutrients to, and remove waste products from, tissues during many physiological processes, including embryonic development, wound healing, and cancer \cite{gupta_mechanism_2003,kushner_building_2013,tonnesen_angiogenesis_2000}. The structure and form of connected blood vessels (e.g., vascular morphology), determines how nutrients and waste are supplied or removed from the environment and, in turn, influences the behavior of the tissue and its constituent cells. The morphology of vascular networks can reveal the presence of an underlying disease, or predict the response of a patient to treatment. High resolution vascular imaging technology creates an exciting opportunity to develop mathematical tools to discover new links between blood vessel structure and function. \new{Here, we focus on \emph{tumor-induced angiogenesis}, the process by which tumor cells stimulate the formation of new blood vessels from pre-existing vasculature \cite{gupta_mechanism_2003}. When oxygen and nutrient levels within a population of tumor cells become too low to sustain a viable cell population, the tumor cells produce several growth factors, including vascular endothelial growth factor (VEGF), platelet-derived growth factor (PDGF) and basic fibroblast growth factor (bFGF), which diffuse through the surrounding tissue \cite{ferrara_vegf_2002,folkman_tumor_1974,sherwood_tumor_1971}. On contact with neighboring blood vessels, these tumor angiogenesis factors (or TAFs) increase the permeability of the vessel walls and loosen adhesive bonds between the endothelial cells that line the blood vessels \cite{folkman_isolation_1971}. The TAFs activate the endothelial cells to release proteases that degrade the basement membrane \cite{menashi_2_1993}. Activated tip endothelial cells then migrate away from the parent vessel and follow external cues, such as spatial gradients of VEGF and/or fibronectin \cite{paweletz_tumor-related_1989,terranova_human_1985}. Stalk endothelial cells located behind the tip cells proliferate into the surrounding tissue matrix, causing the emerging vessel sprouts to elongate \cite{sholley_mechanisms_1984}. When tip endothelial cells from one sprout come into contact with tip or stalk endothelial cells from another sprout, the two endothelial cells may fuse or anastamose together, forming a new loop through which oxygen and nutrients may be transported \cite{paweletz_tumor-related_1989}. In Fig~\ref{fig:fig1} we present a schematic model of how these processes are coordinated. } \new{As the number of experimental and theoretical studies of angiogenesis has increased, so our knowledge of the mechanisms involved in its regulation has increased beyond the idealised description given above \cite{lugano_tumor_2020,saman_inducing_2020}. For example, subcellular signalling involving the VEGF and delta-notch signalling pathways is known to influence whether an endothelial cell adopts a tip or stalk cell phenotype \cite{bentley_role_2014}. Further, immune cells, including macrophages, that are present in the tumor microenvironment, are known to release TAFs such as VEGF and matrix degrading proteases which facilitate tumor angiogenesis \cite{lugano_tumor_2020}. Mechanical stimuli also influence endothelial cell migration. For example, the fluid shear stress experienced by endothelial cells lining blood vessels drives their migration by causing them to form lamellipodia and focal adhesions at the front of the cell, in the flow direction, and to retract focPrincipal component analysis of persistent homology rank functions with case studies of spatial point patterns, sphere packing and colloidal adhesions at the rear \cite{li_notch_2005,li_role_2002}. } \new {In this paper}, we explore several approaches for quantifying the morphology of vascular networks that form during angiogenesis, including recently developed techniques from topological data analysis. We develop and test our methodology through application to simulated data from a highly idealised, and well known hybrid (i.e., discrete and continuous) stochastic mathematical model of tumor-induced angiogenesis proposed by Anderson and Chaplain \cite{anderson_continuous_1998} (see Fig~\ref{fig:fig1} for a model schematic). \begin{figure} \centering \includegraphics[width=0.57\textwidth]{figures_arxiv/Fig1.jpg} \caption{\textbf{Schematic overview of tumor-induced angiogenesis.} \new{Schematic depicting seven aspects of tumor angiogenesis that are incorporated in the Anderson-Chaplain model of tumor-induced angiogenesis \cite{anderson_continuous_1998}. (1) Distant tumor cells release a range of chemoattractants, including vascular endothelial growth factors and basic fibroblast growth factors that stimulate the formation of new blood vessels. These growth factors are described collectively as a single, generic tumor angiogenesis factor (TAF). (2) Production and consumption of tissue-matrix bound fibronectin by the endothelial cells, creates a spatial gradient of fibronectin across the domain. (3) Endothelial cells sense the TAF and fibronectin gradients and undergo individual cell migration. (4) As endothelial tip cells migrate, via chemotaxis, up spatial gradients of the TAF, stalk cells in the developing vessels are assumed to proliferate, creating what has been termed a ``snail trail" of new endothelial cells. (5) Endothelial tip cells also migrate, via haptotaxis, up spatial gradients in fibronectin. (6) Endothelial cells in existing sprouts may initiate the formation of secondary sprouts. (7) If a sprout coincides with an existing vessel, then it is assumed to be annihilated and a new loop is formed; if two sprouts coincide or anastomose, then both are assumed to be annihilated and a new loop forms.} \old{ Schematic of \new{the processes included in the Anderson-Chaplain Model of }tumor-induced angiogenesis. We depict seven aspects of tumor-induced angiogenesis that are captured in the Anderson-Chaplain model \cite{anderson_continuous_1998}. (1) Tumor cells release a chemoattractant, or tumor angiogenesis factor (TAF), that stimulates the formation of new blood vessels. (2) \old{Endothelial cells lining pre-existing blood vessels} \new{In response to the presence of TAF, the parent vessel becomes permeable and releases plasma fibronectin. This plasma fibronectin then binds to the substrate, which creates a gradient of fibronectin. (3) In response to TAF, endothelial cells may sense the TAF gradient and exhibit individual cell migration}. (4) Endothelial tip cells migrate, via chemotaxis, up spatial gradients of the TAF and deposit a ``snail trail" of new vessels \new{comprised of endothelial cells} as they move. (5) Endothelial tip cells also migrate, via haptotaxis, up spatial gradients in fibronectin which is bound to the tissue matrix. (6) A migrating endothelial cell can branch into two cells, to form a new sprout. (7) If a sprout coincides with an existing vessel, then it is annihilated and a new loop is formed; if two sprouts coincide, or anastomose, then they are both annihilated and a new loop forms.}} \label{fig:fig1} \end{figure} The Anderson-Chaplain model of tumor angiogenesis is based on continuum models proposed by Balding and McElwain \cite{balding_mathematical_1985} \new{and Byrne and Chaplain \cite{byrne_growth_1995}}, as well as the stochastic model proposed by Stokes and Lauffenberger \cite{stokes_analysis_1991}. It is an on-lattice model in which endothelial cells perform a biased random walk and generate blood vessel networks that resemble those observed experimentally \cite{anderson_continuous_1998}. While more detailed theoretical models have been developed (see reviews \cite{byrne_dissecting_2010,hadjicharalambous_tumour_2021,metzcar_review_2019,scianna_review_2013,stepanova_multiscale_2021}), we focus on the Anderson-Chaplain model due to its simplicity \new{and wide adoption in the mathematical biology literature. The methods presented in this work can also be used to study alternative models of angiogenesis, such as the phase-field model presented in \cite{vilanova_mathematical_2017}, the 2D model of early angiogenesis and cell fate specification in \cite{stepanova_multiscale_2021}, the 3D hybrid model presented in \cite{perfahl_3d_2017}, and multiscale models of vascular tumor growth, such as those presented in \cite{grogan_microvessel_2017, vavourakis_validated_2017,cai_long_2017,sefidgar_numerical_2015}.} The \new{Anderson-Chaplain} model describes the spatio-temporal evolution of three physical variables: endothelial tip cells, tumor angiogenesis factor (TAF), and fibronectin \cite{anderson_continuous_1998}. Fig~\ref{fig:fig1} contains a model schematic where tumor cells located along the right boundary produce TAF and the endothelial tip cells from a nearby healthy vessel placed along the left boundary move via \emph{chemotaxis} up spatial gradients of TAF . \new{As the tip cells move, stalk cells located behind them proliferate, creating what has been termed} \old{they leave behind} a ``snail trail'' of new blood vessel segments \cite{byrne_dissecting_2010}. \new{Endothelial tip cells also migrate via \emph{haptotaxis}, up spatial gradients of fibronectin, which is produced and consumed by the migrating endothelial cells and binds to the tissue matrix in which the cells are embedded. As the tip cells migrate and the stalk cells proliferate, the vessel sprouts elongate, and secondary sprouts may emerge from the vessels, at the end of a sprout or laterally from the nascent vessel. Further, when a tip cell collides with another vessel segment or another tip cell, the two cells may fuse, forming a closed loop or anastomosis}. \begin{figure}[ht!] \centering \includegraphics[width=.99\textwidth]{figures_arxiv/Fig2.jpg} \caption{\textbf{Data generation and analysis pipeline.} (1) \uline{Spatio-temporal modeling: Anderson-Chaplain model.} The Anderson-Chaplain model is simulated for 11 $\times$ 11 = 121 different values of the haptotaxis and chemotaxis parameters, ($\rho, \chi$). The model output is saved as a binary image, where pixels labeled 1 or 0 denote the presence or absence, respectively, of blood vessels. We generate 10 realizations for each of the 121 parameter combinations, leading to 1,210 images of simulated vessel networks. (2) \uline{Data analysis.} \new{We use the binary images from Step 1 to generate standard and topological descriptor vectors} A.) Standard descriptor vectors We compute the number of active tip cells and the number of vessel segments \new{at discrete time points} \old{over time}. We also compute the length of the vessels at the final time point \cite{folarin_three-dimensional_2010,konerding_evidence_1999,konerding_3d_2001,adams_persistence_2017}. B.) Topological descriptor vectors. We construct flooding and sweeping plane filtrations \cite{bendich_persistent_2016} \new{using binary images from the final timepoint of each simulation.} We track the birth and death of topological features (connected components and loops) that are summarized as Betti curves and persistence images \cite{adams_persistence_2017}. (3) \uline{Data clustering.} We \old{next} perform $k$-means clustering \new{using either} the \new{standard or topological} descriptor vectors \old{for the set of 1,210 simulations} computed during step 2 \new{from all 1,210 simulations. In this way, we} \old{to} decompose \old{the} ($\rho,\chi$) parameter space into regions that group vessel networks with similar morphologies.} \label{fig:fig2} \end{figure} We would like a quantitative method to understand and compare vessel networks that is applicable to experimental and synthetic data. Standard quantitative descriptors of vascular morphology proposed by ~\cite{folarin_three-dimensional_2010,kannan_functional_2018,konerding_evidence_1999,konerding_3d_2001, perfahl_3d_2017} include inter-vessel spacing, the number of branch points, measuring the total area (volume) covered for 2D (3D) simulations, vessel length, density, tortuosity, the number of vessel segments, and the number of endothelial sprouts. These metrics correlate with tumor progression and treatment response in experimental datasets \cite{bauer_cell-based_2007}; however, they are computed at a fixed spatial scale, and neglect information about the connectedness (i.e., the topology) of vascular structures. Therefore, standard descriptors do not exploit the full information content of synthetic data generated from the models. At the same time, advances in imaging technology mean that it is now possible to visualize vascular architectures across multiple spatial scales \cite{zhan_mri_2019}. These imaging developments are creating a need for new methods that can quantify the multi-scale patterns in vascular networks, and how they change over time. A relatively new and expanding field of computational mathematics for studying the shape of data at multiple scales is TDA. TDA consists of algorithmic methods for identifying global structures in high-dimensional datasets that may be noisy \cite{carlsson_topology_2009,zomorodian_topology_2005}. TDA has been useful for biomedical applications \cite{nicolau_topology_2011,nielson_topological_2015,qaiser_persistent_2016,xia_persistent_2014}, including brain vessel MRI data \cite{bendich_persistent_2016} and experimental data of tumor blood vessel networks \cite{Byrne2019,Stolz2020}. A commonly-used tool from TDA is \emph{persistent homology} (PH). \emph{Homology} refers to the characterization of topological features (\emph{e.g.}, connected components and loops) in a dataset, and \emph{persistence} refers to the extent to which these features persist within the data as a scale parameter varies. PH is a useful way to summarize the topological characteristics of spatial network data \cite{Byrne2019,Stolz2020,feng_persistent_2019} as well as noisy and high dimensional agent-based models (ABMs) \cite{topaz_topological_2015, mcguirl_topological_2020}. More recently, PH has been combined with machine learning to extract accurate estimates of parameters from such models \cite{bhaskar_analyzing_2019}. Most of these studies focus on PH calculations for point clouds of data; notably, PH has been adapted to analyze networks and grayscale images \cite{Otter2017}. An active area of research is exploring different filtrations for application-driven PH. In this paper, we develop a computational pipeline for analyzing simulations of the Anderson-Chaplain model over a range of biologically-relevant parameter values. Our main objectives are to identify model descriptor vectors that group together \new{similar model simulations into \emph{biologically interpretable} clusters. By biologically interpretable, we mean that simulations within a cluster arise from similar parameter values and simulations in different clusters arise from different parameter values.} \old{similar model simulations, and then to interpret the resulting clusters. } We use two topological approaches, the sweeping plane and flooding filtrations, to construct simplicial complexes from \new{binary image} data generated from simulations of the Anderson-Chaplain model. We show that PH of the sweeping plane filtration and its subsequent vectorization provides an interpretable descriptor vector for the model parameters governing chemotaxis and haptotaxis. We show, \new{by comparison with existing morphologically-motivated standard descriptor vectors, that this topological approach} leads to more biologically \new{interpretable}\old{informative} clusters that \new{stratify the haptotaxis-chemotaxis parameter space} \old{existing morphologically-motivated standard descriptor vectors}. Furthermore, the clusters generated from the sweeping plane filtration are robust and generalize well to unseen model simulations. \section*{Materials and Methods} We simulate the Anderson-Chaplain model of tumor-induced angiogenesis for a range of values of the haptotaxis and chemotaxis coefficients, $\rho$ and $\chi$. Each simulation generates vasculature composed of a collection of interconnected blood vessels in the form of binary image data. \new{We compute three so-called standard descriptor vectors to summarize each simulation: two are computed at 50 time steps and the third is computed at the final time step.} We also compute 30 topological descriptor vectors \old{for each model simulation}. These topological descriptors encode the proposed multiscale quantification of the vascular morphology. We calculate standard and topological descriptor vectors for the entire set of 1,210 simulations. We then analyze the simulations by clustering the standard or topological descriptor vectors and compare the results. Fig~\ref{fig:fig2} shows the pipeline of data generation and analysis. We give details of the Anderson-Chaplain model, including governing equations, parameter values and implementation, in the S1 Appendix. The Python files and notebooks used for all steps of our analysis are publicly available at \href{https://github.com/johnnardini/Angio_TDA}{https://github.com/johnnardini/Angio\_TDA}. \subsection*{Data generation} We simulate the Anderson-Chaplain model as the parameters $\rho$ and $\chi$ are varied independently among the following 11 values: $\{0,0.05,0.1,0.15,\dots , 0.5\}$. \new{The parameter bounds of [0,0.5] were chosen to yield a range of vascular architectures that are visibly distinct and recapitulate vascular patterns seen \emph{in vivo}. The resolution of the parameter mesh (11 discrete values between 0 and 0.5) was chosen for computational tractability while still being sufficient to illustrate how TDA methods can detect and quantify differences between simulations from similar parameter values that are difficult to distinguish visually.} We generate 10 realizations of the model for each of the 121 $(\rho,\chi)$ parameter combinations, and produce 1,210 binary images that summarize the different synthetic blood vessel networks. \old{Each simulation runs until either an endothelial tip cell crosses the line corresponding to $x=0.95$ nondimensional spatial units or the maximum simulation time of $t=20$ nondimensional time units is exceeded. Each simulation is initialized using the same initial condition and with all other model parameters set to the baseline values from \cite{anderson_continuous_1998}. We use no-flux boundary conditions.}\new{Each simulation is initialized using the same initial conditions and with all other model parameters fixed at the baseline values used in \cite{anderson_continuous_1998}, and impose no-flux conditions on the domain boundary. For consistency with \cite{anderson_continuous_1998}, all simulations are computed on lattices of size $201\times 201$. Each simulation continues until either an endothelial tip cell crosses the line $x=0.95$ (in dimensionless spatial units) or the maximum simulation time, $t=20$ (in dimensionless time units), is exceeded. The final model output is a $201\times 201$ binary image in which nonzero (zero) pixels denote the presence (absence) of an endothelial cell at that lattice site.} \subsubsection*{Morphologically-motivated standard descriptors and descriptor vectors} Morphologically-motivated standard descriptors are used to summarize physical characteristics of each model simulation. \new{Commonly-used descriptors include inter-vessel spacing, the number of branch points, the total area (volume) spanned by the network for 2D (3D) simulations, the shape of such loops in 2D (voids in 3D), and tortuosity ~\cite{baish_scaling_2011,folarin_three-dimensional_2010,kannan_functional_2018,konerding_evidence_1999,konerding_3d_2001, perfahl_3d_2017}.} \old{The standard descriptors that we} \new{We choose to use the following standard descriptors due to their prevalence in the literature} \old{use}: the number of vessel segments ($N_S$), the number of endothelial tip cells ($N_T$), and the final length of the longest vessel ($L$) \cite{balding_mathematical_1985,folarin_three-dimensional_2010,konerding_evidence_1999,konerding_3d_2001}. \new{In Fig~\ref{fig:fig3} we use idealised networks to indicate how the standard descriptors are defined. } \old{Fig~\ref{fig:fig3} illustrates the standard descriptors at a snapshot of a schematic model simulation.} \new{As described in S1 Appendix, $N_S$ and $N_T$ both increase by one with each branching event, and $N_T$ decreases by one with each anastomosis event.} We record $N_S$ and $N_T$ at 50 time steps to create \new{the} descriptor vectors. To facilitate downstream clustering analysis, we require vectors of the same length for all simulations. To ensure the dynamic descriptor vectors for each model simulation are of length 50, we record $N_S(\textbf{t})$ and $N_T(\textbf{t})$ at the 50 time steps $\bm{t}=\{t_i\}_{i=1}^{50}$, where $t_i = (i-1)\Delta t$, $\Delta t=t_\text{end}/49$, and $t_\text{end}$ denotes the duration of a given simulation. \new{We remark that the requirement for having vectors of the same length for all simulations might not be feasible when dealing with experimental data, which could include heterogeneities in sample size and time point locations. We note further that this requirement only applies to the standard descriptors; for the topological filtrations considered in future sections, only the final segmented vessel image is needed.} For each simulation, we also compute $L(t_\text{end})$, the $x$-coordinate of the vessel segment location which has the greatest horizontal distance from the $y$-axis. Thus, the standard descriptor vectors we use for subsequent clustering analysis are $N_S(\textbf{t}), N_T(\textbf{t})$ and $L(t_\text{end})$. \begin{figure}[ht!] \centering \includegraphics[width=.7\textwidth]{figures_arxiv/Fig3.jpg} \caption{\textbf{Standard descriptor overview.} Standard descriptors are computed for each model simulation include the number of vessel segments ($N_S$, depicted by each colored solid curve), the number of endothelial tip cells ($N_T$, depicted by black dots), and the final length of the vasculature ($L$, depicted by the vertical grayed dashed line). This schematic example is initialized with 2 vessel segments and 2 tip cells at locations (1) and (2). A branching event at location (3) increases the value of both $N_S$ and $N_T$ by one. An anastomosis event at location (4) decreases $N_T$ by one. The branching event at location (5) increases both $N_S$ and $N_T$ by one.} \label{fig:fig3} \end{figure} \subsection*{Quantifying vessel shape using topological data analysis}\label{subsec:PH} The most prominent method from TDA is persistent homology (PH) \cite{carlsson_topology_2009,Edelsbrunner2010,Otter2017}. PH is rooted in the mathematical concept of homology, which captures the characteristics of shapes. To compute (persistent) homology from data, one needs to first construct simplicial complexes, which can be thought of as collections of generalized triangles. From the constructed simplicial complexes, one can quantify and visualize the connected components (dimension 0) and loops (dimension 1) of a dataset at different spatial scales. \new{While we compute the $N_T$ and $N_S$ standard decriptor vectors at 50 time points for each model simulation (see Section \textbf{Morphologically-motivated standard descriptors and descriptor vectors}), we compute topological descriptor vectors from the final output binary image.} \subsubsection*{Simplicial complexes and homology} We construct simplicial complexes from data points derived from binary images of the completed simulations of the Anderson-Chaplain model (see``Synthetic data" in Step 1 of Fig~\ref{fig:fig2}, where red pixels denote presence of vasculature). Normally, TDA of image data lends itself to the construction of cubical complexes, which are generalizations of cubes; however, we have binary rather than grayscale data, so we instead use information about the model generation and Moore neighborhoods as we describe here. Each pixel that has a value of one is embedded in $\mathbb{R}^2$ at the centroid of the pixel as a vertex (or $0$-simplex), as demonstrated in Fig.~\ref{fig:fig4}. We term the resulting collection of points a \emph{point cloud}. We connect two points by an edge (or $1$-simplex) if they are within each others' Moore neighborhood (the Moore neighborhood for one pixel is shaded in Fig.~\ref{fig:fig4}B). If three points are pairwise connected by an edge, then we connect them with a filled-in triangle (or $2$-simplex). The union of 0-,1-, and 2-simplices form a \emph{simplicial complex}, as shown in Fig.~\ref{fig:fig4}C. \begin{figure} \centering \includegraphics[width=0.99\textwidth]{figures_arxiv/Fig4.jpg} \caption{\textbf{Converting a binary image into a simplicial complex.} A) Schematic binary image. B) Point cloud for all nonzero pixels in the binary image. The Moore neighborhood of one nonzero pixel is highlighted in salmon. C) A simplicial complex constructed from the point cloud in panel B. } \label{fig:fig4} \end{figure} To compute topological invariants, such as connected components (dimension 0) and loops (dimension 1), we use homology. To obtain homology from a simplicial complex, $K$, we construct vector spaces whose bases are the $0$-simplices, $1$-simplices, and $2$-simplices, respectively, of $K$. There is a linear map between $2$-simplices and $1$-simplices, called the boundary map $\partial_2$, which sends triangles to their edges. Similarly, the boundary map $\partial_1$ sends edges to their points and $\partial_0$ sends points to 0. The action of the boundary map $\partial_1$ on the simplices is stored in a binary matrix where the entry $a_{i,j}$ indicates whether the $i$-th $0$-simplex forms part of the boundary of the $j$-th $1$-simplex. If so, then $a_{i,j} = 1$; otherwise, $a_{i,j}=0$. One can compute the kernel $\text{Ker}(\cdot)$ and image $\text{Im}(\cdot)$ of the boundary maps to obtain the vector spaces $H_0(K) = \text{Ker}(\partial_{0}) / \text{Im}(\partial_{1})$ and $H_1(K) = \text{Ker}(\partial_{1}) / \text{Im}(\partial_{2})$. These vector spaces are also referred to as homology groups and their dimensions define topological invariants called the \emph{Betti numbers} of $K$, $\beta_0$ and $\beta_1$, which quantify the numbers of connected components and loops, respectively. \subsubsection*{Filtrations for simulated vasculature} There are different ways to study vascular data at multiple scales~\cite{bendich_persistent_2016,garside_topological_2019,Byrne2019,Stolz2020}. We encode the multiple spatial scales of the data using a \emph{filtration}, which is a sequence of embedded simplicial complexes $K_0\subseteq K_1 \subseteq \dots \subseteq K_\text{end}$ built from the data. \new{A challenge for researchers is to determine informative filtrations for specific applications \cite{stolz-pretzer_global_2019}, such as blood vessel development in our study.} Here, the input data is the binary image from the final timepoint of the Anderson-Chaplain model, which we call $\bm{N}$ (See Eq~(13) in S1 Appendix). We construct sequences of binary images that correspond to different filtered simplicial complexes: a sweeping plane filtration \cite{bendich_persistent_2016} and a flooding filtration \cite{garside_topological_2019}. We remark that both filtrations can be considered sublevelset filtrations corresponding to a height function $h: X \rightarrow \mathbb{R}$ on some simplicial complex $X$ (or just on the vertices/pixels and considering the simplicial subcomplex spanned by them). \textbf{Sweeping plane filtration. In the sweeping plane filtration, we move a line across the binary image $\bm{N}$ and include pixels in the filtration at discrete steps once a pixel is crossed by the line. On every filtration step, we move the line by a fixed number of pixels in a chosen direction. In Fig \ref{fig:fig5}, we illustrate the method when a vertical line moves from left to right (LTR). From the corresponding sequence of binary images, we construct a filtered simplicial complex $K^\text{LTR}=\{K_1,K_2,\dots,K_\text{end}\}$. Similarly, we construct the filtered simplicial complexes $K^\text{RTL}$ when the vertical line moves from right to left (RTL), $K^\text{TTB}$ when a horizontal lines moves from top to bottom (TTB), and $K^\text{BTT}$ when a horizontal line moves from bottom to top (BTT). \begin{figure}[ht!] \centering \includegraphics[width=0.99\textwidth]{figures_arxiv/Fig5.jpg} \caption{\textbf{The LTR sweeping plane filtration for a binary image.} A) Sample binary image from a simulation of the Anderson-Chaplain model. B-E) Point clouds used for each iteration of the sweeping plane approach. On each step, only pixels located to the left of the plane (denoted here with a blue line) are included; gray pixels are ignored. F-I) Filtration steps constructed from the point clouds in panels B-E.} \label{fig:fig5} \end{figure} \textbf{Flooding filtration. } Our second filtration is the flooding filtration. From the binary image, $\bm{N}$, associated with a model simulation, we construct a sequence of binary images in the following way. On the first step, we input the \old{final} output binary image from a model simulation. \new{In the binary image, pixels with value one denote the presence of an endothelial cell and pixels with value zero denote the absence of endothelial cells. To create the second binary image, we consider all pixels of value one and assign all pixels in their Moore neighborhood} (as shown in Fig~\ref{fig:fig4}B) to value one. We \new{repeat this process} \old{iterate} until \new{a binary image with only pixels of value one is created} \old{all pixels are set equal to one}. In Fig \ref{fig:fig6}B, for example, the red pixels denote the nonzero pixels from the initial binary image, the orange pixels denote the nonzero pixels added on the first round of flooding, and the yellow pixels denote the nonzero pixels added on the second round of flooding. Each ``round" is called a step. From the corresponding sequence of binary images, we construct a filtered simplicial complex $K^\text{flood}=\{K_1,K_2,\dots,K_\text{end}\}$. \new{We chose $K_\text{end}=25$ so that the Betti curves for all simulations attain $\beta_0=1$ and $\beta_1=0$ at the final filtration step, thus ensuring that the maximum amount of topological information is encoded in the Betti curves.} \begin{figure}[ht!] \centering \includegraphics[width=0.99\textwidth]{figures_arxiv/Fig6.jpg} \caption{\textbf{The flooding filtration for a binary image.} A) Schematic binary image. B) Grayscale image of the original binary image. Red pixels are nonzero in the initial image, orange pixels become nonzero after one round of flooding, and yellow pixels become nonzero after two rounds of flooding. C-E) We performed three filtrations by dilating the image twice. During each filtration, the eight neighboring pixels of all nonzero pixels (ie pixels not marked as white) become nonzero. Red pixels are nonzero in the original image, orange pixels become nonzero on the second filtration (i.e., after one step of flooding), and yellow pixels become nonzero on the third filtration (i.e., after two steps of flooding). F-H) Simplicial complexes associated with the filtrations presented in panels C-E. } \label{fig:fig6} \end{figure} \subsubsection*{Persistent homology (PH)} PH is an algorithm that takes in data via a filtration and outputs a quantification of topological features such as connected components (dimension 0) and loops (dimension 1) across the filtration. The simplicial complexes are indexed by the scale parameter of the filtration. In our case, the scale parameter corresponds to the spatial location in the sweeping plane filtration or steps of flooding in the flooding filtration. \new{Note that we compute these filtrations on simulated blood vessel network images at the final time step of a model simulation.} The inclusion of a simplicial complex $K_i\subseteq K_j$ for $i\leq j$ gives a relationship between the corresponding homology groups $H_p(K_i)$ and $H_p(K_j)$ for $p = 0,1$. This relationship enables us to track topological features such as loops along the simplicial complexes in the filtration. Intuitively, a topological feature is born in filtration step $b$ when it is first computed as part of the homology group $H_p(K_b)$ and dies in filtration step $d$ when that feature no longer exists in $H_p(K_d)$, \emph{i.e.}, when a connected component merges with another component or when a loop is covered by 2-simplices. The output from PH is a multiset of intervals $[b,d)$ which quantifies the persistence of topological features. Each topological feature is said to persist for the scale $d-b$ in the filtration. Our topological descriptors are the connected components (i.e., 0-dimensional) and loops (i.e., 1-dimensional features) obtained by computing persistent homology of the sweeping plane and flooding filtrations. We use the superscript notation $K^v$ to denote the filtered simplicial complex $K$ in direction $v=\{\text{LTR, RTL, TTB, BTT, flood}\}$. \subsubsection*{Topological descriptor vectors from PH} We use PH to generate different output vectors. \begin{itemize} \item \textbf{Betti curves.} Betti curves~\cite{Giusti2015} show the Betti numbers on each filtration step. Let $\beta_i(K^v)$ denote the Betti curves of filtered simplicial complex $K$ in direction $v$ for dimensions $i=\{0,1\}$. \item \textbf{Persistence images.} A persistence image~\cite{adams_persistence_2017} uses as input the birth-death pairs given by PH and converts the set of (birth $b$, persistence $(d-b)$) coordinates into a vector, a format which is suitable for machine learning and other classification tasks. \new{Following the standard definition of a persistence image, } \old{we begin by blurring} the coordinates $(b,d-b)$ \old{In a first step the coordinates $(b,d-b)$} are blurred by a Gaussian, with standard deviation $\sigma$, that is centered about each birth-persistence point, \new{which accounts for uncertainty~\cite{adams_persistence_2017}.} We take a weighted sum of the Gaussians and place a grid on this surface to create a vector. We compute two alternative weighting strategies: all ones (in which case all features are equally weighted) and a persistence weight of ($d-b$) (in which more persistent features are given larger weights). Let PIO$_i(K^v)$ and PIR$_i(K^v)$ denote the corresponding persistence images computed from $K^v$ with equal and ramped weighting, respectively, for dimension $i=\{0,1\}$. \end{itemize} The topological descriptor vectors that we compute for each model simulation are $\beta_i(K^v)$, PIO$_i(K^v)$, and PIR$_i(K^v)$, where $i=\{0,1\}$ and $v=\{$LTR, RTL, TTB, BTT, flood $\}$. In total each simulation has $3 \times 2 \times 5 = 30$ topological descriptor vectors. \subsection*{Simulation Clustering} We use an unsupervised algorithm, $k$-means clustering, to group the quantitative descriptor vectors of the synthetic data generated from simulations of the Anderson-Chaplain model. To cluster $n$ samples $x_1,x_2,\dots,x_n\in\mathbb{R}^d$ into $k$ clusters, the $k$-means algorithm finds $k$ points in $\mathbb{R}^d$, and clusters each sample according to which of the $k$ means it is closest to, and then minimizes the within-cluster residual sum of squares distance \cite{lloyd_least_1982}. We cluster the standard descriptor vectors and the topological descriptor vectors (see steps 2A and 2B of the methods pipeline in Fig~\ref{fig:fig2}), respectively, to investigate whether descriptor vectors lead to biologically \old{meaningful}\new{interpretable} clusters. We test the robustness of each clustering assignment by randomly splitting the descriptor vectors into training and testing sets, and use the testing set to evaluate out-of-sample (OOS) accuracy. \new{Specifically, 7 of the 10 descriptor vectors from each of the 121 $(\rho,\chi)$ parameter combinations are randomly chosen with uniform sampling and placed into a training set (847 simulations); the remaining 3 descriptor vectors from each $(\rho,\chi)$ combination are placed into a testing set (363 simulations).} After performing unsupervised clustering with a $k$-means model on the training set, each $(\rho,\chi)$ combination is labeled by the majority of cluster assignments among its 7 training simulation descriptor vectors. To evaluate each clustering model's OOS accuracy, the 3 test data samples for each $(\rho,\chi)$ parameter combination are given a ``ground-truth'' label equal to the cluster assignment for the 7 training simulations for that same $(\rho,\chi)$ parameter combination. A ``predicted'' label is calculated for each descriptor vector from the test data using the trained $k$-means model, and OOS accuracy is defined as the proportion of test simulations for which the ``predicted'' label matched the ``ground-truth'' label. For example, if the seven training simulations from the parameter combination $(\rho,\chi)=(0.2,0.2)$ are placed into clusters $\{1,1,2,2,1,1,1\}$, then the three testing simulations from $(\rho,\chi)=(0.2,0.2)$ will be labeled as being in cluster 1. If the test simulations are predicted to be from clusters $\{1,2,1\}$, then we compute an OOS accuracy of 66.67$\%$. We use all 363 testing simulations when computing OOS accuracy and \new{use the \texttt{KMeans} command from scikit-learn (version 0.22.1), which uses Lloyd's algorithm for Euclidean space, for training and prediction.} \section*{Results} We simulated the Anderson-Chaplain model for 121 different values of the chemotaxis and haptotaxis coefficients ($ \rho, \chi$) and performed 10 model realizations for each parameter pair. We observed that simulations generated by different parameter pairs may appear visually distinct in their vessel growth patterns. To quantify and summarize the morphologies, we computed dynamic standard descriptor vectors as well as topological descriptor vectors for the set of 1,210 model simulations. We then performed unsupervised clustering using either standard or topological descriptor vectors to partition the $(\rho,\chi)$ parameter space. As we detail here, we found that the topological sweeping plane descriptor vectors offered a multi-scale analysis that led to biologically interpretable and robust clusterings of the $(\rho,\chi)$ parameter space, whereas the clusterings of the standard descriptor vectors were not biologically interpretable. The topological analysis succeeded in discriminating fine-grained vascular structures and the parameter pairs that generated them. \subsection*{Haptotaxis and chemotaxis alter vessel morphology} We investigated the influence of haptotaxis and chemotaxis by varying the parameters $\rho$ and $\chi$ \old{, respectively}. \new{We note that similar parameter sensitivity analyses have been performed previously \cite{anderson_continuous_1998,hadjicharalambous_tumour_2021}; we reproduce this analysis as the basis for our data analysis.} \old{for consistency in our study.} Recall that in model simulations, the vessels emerged from the left-most boundary and were recruited towards a tumor located on the right boundary. When chemotaxis alone drives endothelial tip cell movement ($\rho=0.00$,$\chi = 0.50$), the blood vessel segments are long and thin as the tip cells migrate directly towards the tumor and produce individual vessel segments with few anastomosis events (Fig~\ref{fig:fig7}A). When haptotaxis drives tip cell movement ($\rho = 0.50$,$\chi = 0.00$), the vessels fail to reach the tumor (Fig~\ref{fig:fig7}B). When both haptotaxis and chemotaxis are active ($\rho=\chi=0.15$), the network spans a large portion of the spatial domain and is highly connected (Fig~\ref{fig:fig7}C). \begin{figure}[ht!] \centering \includegraphics[width=0.99\textwidth]{figures_arxiv/Fig7.jpg} \caption{\textbf{Typical realizations of the Anderson-Chaplain model}. A) Chemotaxis-driven tip cell movement ($\rho=0.00$, $\chi=0.50$), B) a haptotaxis-driven tip cell movemement ($\rho=0.50$, $\chi=0.00$), and C) tip cell movement driven by chemotaxis and haptotaxis ($\rho=0.15,\chi=0.15$).} \label{fig:fig7} \end{figure} \subsection*{Standard and topological descriptors measure distinct aspects of vascular architectures} Rather than performing visual inspection of all model simulations, we computed and compared quantitative vessel descriptor vectors using data science approaches as described in the \textbf{Materials and Methods}. We demonstrate here how the biological and topological descriptors are distinct from each other. In Fig~\ref{fig:fig8}, we observe how the number of tip cells ($N_T$), vessel segments ($N_S$), connected components ($\beta_0$), and loops ($\beta_1$) associated with an evolving vasculature change following different events. After each anastomosis event, $N_T$ decreases by one (Fig~\ref{fig:fig8}B). After a branching event, both $N_T$ and $N_S$ increase by one (Fig~\ref{fig:fig8}C). We conclude that $N_T$ is unchanged and $N_S$ increases by one after one branching event and one anastomosis event have occurred. By contrast, the values of the topological descriptors before and after these events are not necessarily identical, as depicted in Figs \ref{fig:fig8}D-E. When an anastomosis event involves vessel segments that were previously connected, the number of loops, $\beta_1$, increases by 1 (compare Figs \ref{fig:fig8}A and \ref{fig:fig8}D); when the vessel segments were not previously connected, $\beta_0$ decreases by 1 (compare Figs \ref{fig:fig8}A and E). Let $N_A(r,s)$ and $N_B(r,s)$ denote the numbers of anastomosis and branching events, respectively, that occur between times $t=r$ and $t=s$. We computed $N_T(\bm{t}), N_S(\bm{t})$ vectors of the standard descriptors of evolving blood vessel simulations as follows: \begin{align*} N_T( t_1 ) &= N_S(t_1) = 9, \\ N_T( t_i ) &= N_T(t_{i-1}) + N_B(t_{i-1},t_i) - N_A(t_{i-1},t_i),\ i = 2,...,50, \\ N_S(t_i) &= N_S(t_i) + N_B(t_{i-1},t_i),\ i = 2,...,50. \end{align*} The values of $N_T(t_1)$ and $N_S(t_1)$ were determined from the models' initial conditions. We first constructed the filtrations $K^v$ where $v=\{\text{LTR, RTL, TTB, BTT, flood}\}$ of each simulation's final binary image. Then we computed connected components and loops, which we call topological descriptors of $K^v$, using PH. The topological descriptor vectors, Betti curves and persistence images, were then constructed for these five filtrations. \begin{figure} \centering \includegraphics[width=.92\textwidth]{figures_arxiv/Fig8.jpg} \caption{\textbf{Standard and topological descriptors describe distinct aspects of vessel morphology}. For clarity, each vessel segment is colored differently, and black dots represent active tip cells. A) The initial vessel configuration. B) A schematic showing how the vascular architecture changes after an anastomosis event. C) A schematic showing how the vascular architecture changes after a branching event. D-E) Schematics showing two ways in which vasculature can change after one anastomosis event and one branching event. F) A schematic showing how the vessels can change after one branching and two anastomosis events. (Key: $\beta_0$, number of connected components; $\beta_1$, number of loops; $N_T$, number of tip cells; $N_S$, number of vessel segments).} \label{fig:fig8} \end{figure} \subsection*{Quantification of blood vessel architecture data} Fig~\ref{fig:fig9} shows the standard descriptor vectors for the three simulations presented in Fig~\ref{fig:fig7}. For the haptotaxis-driven simulation growth in the horizontal direction halts (the total length remains at 0.095 units) and the numbers of tip cells and vessel segments stay constant (at or near the initial condition of 9 vessels). By contrast, the number of tip cells and vessel segments increase over time for the chemotaxis-driven simulation, with a more marked increase when both chemotaxis and haptotaxis are active. For both chemotaxis-active simulations, the vessels extend to the maximum horizontal distance. \begin{figure} \centering \includegraphics[width=\textwidth]{figures_arxiv/Fig9.jpg} \caption{\textbf{The standard descriptors used to summarize model simulations.} We show how the following descriptors change over 50 time steps for the three simulations presented in Fig~\ref{fig:fig7}: A) the number of tip cells, $N_T(\textbf{t})$, B) the number of vessel segments, $N_S(\textbf{t})$, and C) the final vessel length, $L(t_{end})$.} \label{fig:fig9} \end{figure} \begin{figure}[ht!] \centering \includegraphics[width=\textwidth]{figures_arxiv/Fig10.jpg} \caption{TDA sweeping plane descriptor vectors. A) The sweeping plane directions are left-to-right (LTR, gray); right-to-left (RTL, orange); bottom-to-top (BTT, cyan); and top-to-bottom (TTB, green). For these four \emph{v}=\emph{i}T\emph{j} filtrations, we started with points on the \emph{i}th boundary and included more points as we stepped towards the \emph{j}th boundary. Repeating this process produced the spatial filtration $K^v=K_0,K_1\ldots K_{\text{end}}$ for $v=\{\text{LTR, RTL, TTB, BTT}\}$ . B-D) We formed the Betti curves $\beta_0(K^v)$ and $\beta_1(K^v)$ by computing the Betti numbers along each step of $K^v$ for the three blood vessel simulations presented in Fig \ref{fig:fig7}; B) the chemotaxis-driven simulation, C) the haptotaxis-driven simulation and D) chemotaxis \& haptotaxis simulation}. \label{fig:fig10} \end{figure} \begin{figure} \centering \includegraphics[width=\textwidth]{figures_arxiv/Fig11.jpg} \caption{\textbf{The flooding filtration.} A,C,E) Illustrate the flooding filtrations for the three blood vessel simulations from Fig \ref{fig:fig7}. Dark red pixels were points included in the first steps of the filtration and yellow pixels were the points included in later filtration steps. White pixels were not included after 24 steps of the flooding filtration. B,D,F) The Betti Curves ($\beta_0(K^{\text{flood}})$ and $\beta_1(K^{\text{flood}}$) for the chemotaxis-driven, haptotaxis-driven, and chemotaxis \& haptotaxis simulations respectively.} \label{fig:fig11} \end{figure} We next illustrate \old{the topological analysis for} \new{how we use the plane sweeping and flooding filtrations to analyse} the chemotaxis-driven, haptotaxis-driven, and chemotaxis \& haptotaxis-driven simulations (from Fig~{\ref{fig:fig7}}). We computed Betti curves, $\beta_0(K^v)$ and $\beta_1(K^v)$, of the simulated data with sweeping plane filtrations for $v=\{\text{LTR, RTL, TTB, BTT}\}$ (see Fig~\ref{fig:fig10}) and a flooding filtration $v=\{\text{flood}\}$ (see Fig~\ref{fig:fig11}). \new{These filtrations are constructed to provide complementary but not directly comparable information; roughly, the sweeping plane gives an indication of the network in the (x-y) plane whereas the flooding filtration also focusses on vessel density (see earlier description of filtration construction).} We could interpret the PH of the sweeping plane filtration direction \old{. Since}\new{ as follows:} the blood vessels grow primarily from left to right, \new{so the LTR and RTL filtrations}\old{the topological analysis} primarily identify dynamic changes in branching and anastomosis of vessels. The BTT and TTB filtrations are similar to each other, and reflect only horizontal changes, which could be interpreted as measuring bendiness or tortuosity. Therefore, we only discuss the BTT results in this section. For the chemotaxis-driven simulation (Figs~\ref{fig:fig10}B, \ref{fig:fig11}A, and \ref{fig:fig11}B), the $\beta_0(K^\text{LTR})$ descriptor vector slightly decreases with distance $x$ from the $y$-axis as vessel segments anastomose together. The $\beta_0(K^\text{RTL})$ and $\beta_1(K^\text{RTL})$ descriptor vectors decrease with $x$ at the end of each vessel segment. The magnitude of $\beta_0(K^{\text{BTT}})$ increases almost linearly with the $y$-spatial coordinate, and $\beta_1(K^{\text{BTT}})$ increases with $y$ until it plateaus for $y \geq 0.6$. The $\beta_0(K^{\text{flood}})$ descriptor vector decreases with each filtration step, and $\beta_1(K^{\text{flood}})$ begins with $\beta_1=14$ and achieves a local maximum of $\beta_1=10$ after seven filtration steps before reaching $\beta_1=0$ after 11 filtration steps. For the haptotaxis-driven simulation (Figs ~\ref{fig:fig10}C, \ref{fig:fig11}C, and \ref{fig:fig11}D), all LTR and RTL Betti curves become zero for $x>0.1$ because each vessel segment has terminated by $x=0.1$. The $\beta_0(K^{\text{BTT}})$ and $\beta_1(K^{\text{BTT}})$ descriptor vectors increase steadily with $y$ as the horizontal plane moves past each individual vessel segment. The flooding descriptor vectors initially decrease with each flooding step and remain fixed at $\beta_0=1,\beta_1=0$ after six steps of flooding. For the chemotaxis \& haptotaxis-driven simulation (Figs \ref{fig:fig10}D, \ref{fig:fig11}E, \ref{fig:fig11}F), $\beta_0(K^\text{LTR})$ decreases with $x$ as vessel segments anastomose together, while $\beta_1(K^\text{LTR})$ increases with $x$ due to the formation of many loops. The $\beta_0(K^\text{RTL})$ descriptor vector increases with $x$ until it reaches its maximum value of $\beta_0=11$ at $x=0.85$ and then decreases to $\beta_0=0.$ The $\beta_1(K^\text{RTL})$ descriptor vector decreases with $x$. The $\beta_0(K^\text{BTT})$ descriptor vector periodically increases and decreases with $y$ as the horizontal plane moves past regions of high and low connectivity. The $\beta_1(K^\text{BTT})$ descriptor vector steadily increases with the $y$ coordinate. The $\beta_0(K^\text{flood})$ descriptor vector was equal to one for all steps of flooding, and $\beta_1(K^\text{flood})$ decreases with each round of flooding and reaches $\beta_1=0$ after 20 flooding steps. \subsection*{Sweeping plane descriptor vectors cluster simulations by parameter values} \begin{figure} \centering \includegraphics[width=.89\textwidth]{figures_arxiv/Fig12.jpg} \caption{\new{\textbf{Partitioning $(\rho,\chi)$ parameter space into distinct regions using standard biological descriptor vectors.} We applied $k$-means clustering, with $k=5$, to standard biological descriptor vectors. The resulting partitions are presented for A) $N_T(\bm{t})$, B) $N_S(\bm{t})$, C) $L(t_{end})$, and D) concatenation of all three descriptor vectors. The five clusters are ordered according to the mean $\chi$ value within the cluster.} } \label{fig:fig12} \end{figure} We applied $k$-means clustering separately to the standard descriptor vectors and the topological descriptor vectors. None of the clusterings of the standard descriptor vectors were biologically \new{interpretable}\old{meaningful} in ($\rho$,$\chi$) parameter space (see \new{Fig \ref{fig:fig12} and} S\ref{fig:SIfig1} Fig.) While the topological descriptor vectors from the sweeping plane filtration gave more biologically interpretable groupings for combined haptotaxis and chemotaxis parameter values, they were not robust for haptotaxis dominated or chemotaxis dominated ($\rho$,$\chi$) parameter ranges (see S\ref{fig:SIfig2} Fig). The flooding filtration did not give biologically \old{meaningful}\new{interpretable} groups for any parameter ranges (see \textbf{Clustering results} in S1 Appendix for all details). \new{We suggest that the LTR and RTL plane sweeping filtrations produce the most interpretable clusterings because sweeping the plane horizontally resembles the way in which endothelial tip cells migrate from left to right in the simulated data. } \new{No single descriptor vector was able to robustly cluster simulations into biologically interpretable groups.} However, \emph{double} descriptor vectors created by concatenating two sweeping plane topological descriptor vectors\footnote{For example, the double descriptor vector ``PIO$_0(K^{\text{LTR}})$ \& PIO$_1(K^{\text{LTR}})$'' denoted the topological descriptor vector created by concatenating the PIO$_0(K^{\text{LTR}})$ and PIO$_1(K^{\text{LTR}})$ descriptor vectors.} produced clusterings in ($\rho$,$\chi$) parameter space that were biologically interpretable and robust. We note that doubles of standard descriptor vectors or topological flooding descriptor vectors were unable to produce biologically interpretable and robust clusterings in $(\rho,\chi)$ parameter space (see \textbf{Clustering results} in S1 Appendix). We computed a total of $2\times4\times3=24$ individual sweeping plane descriptor vectors for each model simulation: each descriptor vector counted connected components or loops ($\beta_0$, $\beta_1$), swept a plane across the domain in one of four directions (LTR, RTL, TTB, and BTT), and used one of the three PH summaries (BC, PIO, PIR). We computed all double sweeping plane descriptor vectors and clustered all 276 combinations in $(\rho,\chi)$ parameter space. The 15 double descriptor vectors with the highest OOS accuracies are presented in Table~\ref{tab:tab1}; the four with the highest OOS accuracies are liested below: \begin{enumerate} \item PIO$_0(K^{LTR})$ \& PIO$_0(K^{RTL})$ (93.1\% OOS accuracy), \item PIO$_0(K^{RTL})$ \& PIR$_1(K^{LTR})$ (92.6\% OOS accuracy), \item PIR$_0(K^{TTB})$ \& PIR$_1(K^{LTR})$ (91.5\% OOS accuracy), \item PIR$_0(K^{BTT})$ \& PIR$_1(K^{LTR})$ (91.5\% OOS accuracy). \end{enumerate} In Fig~\ref{fig:fig13}, we show how the data clustered in ($\rho,\chi$) parameter space when the top four double sweeping plane descriptor vectors were used. The ``PIO$_0(K^{LTR})$ \& PIO$_0(K^{RTL})$" and ``PIO$_0(K^{RTL})$ \& PIR$_1(K^{LTR})$" doubles produced five connected clustering regions and, thus, attained high OOS accuracy and biologically interpretable clusterings. In contrast, the clusterings generated by the following double descriptor vectors (``PIR$_0(K^{TTB})$ \& PIR$_1(K^{LTR})$" and ``PIR$_0(K^{BTT})$ \& PIR$_1(K^{LTR})$") \old{was}\new{were} unable to distinguish between simulations with strong chemotaxis and strong haptotaxis. \new{We suggest that double descriptor vectors combining LTR and RTL descriptor vectors can robustly cluster simulations into biologically interpretable clusterings because the associated filtrations capture the ways in which vessel segments anastomose and branch, respectively. We performed principal components analysis to reduce the ``PIO$_0(K^{LTR})$ \& PIO$_0(K^{RTL})$" double descriptor vector to two principal components. The results presented in S\ref{fig:SIfig3} Fig show that the simulations from each group are also clustered in this two-dimensional space.} \begin{table} \centering \def1.5{1.5} \begin{tabular}{|c|c|c|} \hline Feature & In Sample Accuracy & Out of Sample Accuracy \\ \hline PIO$_0(K^{LTR})$ \& PIO$_0(K^{RTL})$ & 94.0\% & 93.1\% \\ \hline PIO$_0(K^{RTL})$ \& PIR$_1(K^{LTR})$ & 94.2\% & 92.6\% \\ \hline PIR$_0(K^{TTB})$ \& PIR$_1(K^{LTR})$ & 92.3\% & 91.5\% \\ \hline PIR$_0(K^{BTT})$ \& PIR$_1(K^{LTR})$ & 92.3\% & 91.5\% \\ \hline PIR$_0(K^{LTR})$ \& PIR$_1(K^{LTR})$ & 92.3\% & 90.9\% \\ \hline PIO$_0(K^{TTB})$ \& PIR$_1(K^{LTR})$ & 94.2\% & 90.4\% \\ \hline PIO$_0(K^{BTT})$ \& PIR$_1(K^{LTR})$ & 94.3\% & 90.1\% \\ \hline PIO$_0(K^{LTR})$ \& PIR$_1(K^{LTR})$ & 92.6\% & 90.1\% \\ \hline PIR$_0(K^{RTL})$ \& PIR$_1(K^{LTR})$ & 92.6\% & 89.0\% \\ \hline PIR$_0(K^{LTR})$ \& PIR$_0(K^{RTL})$ & 90.2\% & 89.0\% \\ \hline PIO$_0(K^{LTR})$ \& PIR$_0(K^{RTL})$ & 91.9\% & 88.4\% \\ \hline PIO$_0(K^{RTL})$ \& PIO$_1(K^{LTR})$ & 86.1\% & 86.0\% \\ \hline PIO$_0(K^{BTT})$ \& PIO$_1(K^{LTR})$ & 84.2\% & 85.1\% \\ \hline PIO$_1(K^{LTR})$ \& PIR$_1(K^{BTT})$ & 85.6\% & 84.8\% \\ \hline PIO$_1(K^{LTR})$ \& PIR$_1(K^{TTB})$ & 83.1\% & 84.8\% \\ \hline PIO$_0(K^{TTB})$ \& PIO$_1(K^{LTR})$ & 84.9\% & 84.8\% \\ \hline PIO$_0(K^{BTT})$ \& PIO$_1(K^{RTL})$ & 85.6\% & 84.8\% \\ \hline \end{tabular} \caption{Summary of the 15 sweeping plane double descriptor vectors that achieved the highest OOS accuracy scors.} \label{tab:tab1} \end{table} \begin{figure} \centering \includegraphics[width=0.89\textwidth]{figures_arxiv/Fig13.jpg} \caption{\textbf{Partitioning $(\rho,\chi)$ parameter space into distinct regions using sweeping plane double descriptor vectors.} We applied $k$-means clustering, with $k=5$, to sweeping plane double descriptor vectors. The resulting partitions are presented for the four descriptor vectors that have the highest OOS accuracy: A) $PIO_0(K^{LTR})$ \& $PIO_0(K^{RTL})$, B) $PIO_0(K^{RTL})$ \& $PIR_1(K^{LTR})$, C) $PIO_0(K^{TTB})$ \& $PIR_1(K^{LTR})$, and D) $PIO_0(K^{BTT})$ \& $PIR_1(K^{LTR})$. The five clusters are ordered according to the mean $\chi$ value within the cluster.} \label{fig:fig13} \end{figure} We applied $k-$means clustering to all sweeping plane double descriptor vectors and computed the average OOS accuracy for a range of values of $k$\new{, also known as an elbow plot} (S\ref{fig:SIfig4} Fig). While the average OOS accuracy decreased with increasing values of $k$, the rate of decrease slowed markedly for $k>5$. We fixed $k=5$ as this value robustly clustered the $(\rho,\chi)$ parameter space into biologically interpretable clusters (Fig~\ref{fig:fig13}). Larger values of $k$ may overfit the data \cite{bholowalia_ebk-means_2014}, while smaller values fail to partition ($\rho$,$\chi$) parameter space into biologically interpretable regions (S\ref{fig:SIfig5} Fig). For example, when $k=3$, simulations with strong haptotaxis ($\rho>\chi$), equal chemotaxis and haptotaxis ($\rho=\chi$), and strong chemotaxis ($\rho<\chi$) are clustered together. When $k=4$, there are two distinct clusters near $\rho=\chi$, but simulations with large values of the haptotaxis parameter, $\rho$, are clustered with those with high values of the chemotaxis parameter, $\chi$. With $k=5$ clusters, the region with large values of the haptotaxis parameter, $\rho$, was further subdivided. We suggest that clustering with $k=5$ provides sufficient resolution to distinguish model simulations generated from different regions of the parameter space. \new{We note that more sophisticated descriptors could be used to justify this choice of $k$, including the silhouette score \cite{rousseeuw_silhouettes_1987}. } We identified five model simulations whose double descriptor vectors closely resembled the means from the clusters associated with the ``PIO$_0(K^{LTR})$ \& PIO$_0(K^{RTL})$" clustering. Fig~\ref{fig:fig14} presents representative simulations of each cluster. We note that as $\rho$ and $\chi$ vary, the spatial extent and connectedness of the network vary as expected (i.e., greater spatial extent in the $x$-direction as $\chi$ increases, and greater connectedness as $\rho$ increases). We applied a similar analysis to model simulations sampled from $(\rho,\chi, \psi)$ parameter space, where the non-negative parameter $\psi$ represents the rate at which tip cells branch. The resulting parameter clustering changed only with $\rho$ and $\chi$, suggesting that the vascular morphology does not depend on $\psi$ (S\ref{fig:SIfig6} Fig). \begin{figure} \centering \includegraphics[width=0.99\textwidth]{figures_arxiv/Fig14.jpg} \caption{\textbf{Representative simulated blood vasculature from Groups 1-5.} Series of simulations that resemble the means from each of the five groups (as identified from the double descriptor vectors associated with the sweeping plane filtrations PIO$_0(K^{LTR})$ \& and PIO$_0(K^{RTL})$). The representative simulations for groups 1-5 were generated using the following pairs of parameter values: $(\rho,\chi) = (0.25,0), (0.5,0.2), (0.3,0.2), (0.15,0.15), \text{ and }(0.2,0.4)$, respectively.} \label{fig:fig14} \end{figure} \section*{Conclusions and Discussion} We have introduced a topological pipeline to analyze simulated data of tumor-induced angiogenesis \cite{anderson_continuous_1998}. We investigated different filtrations to feed into the persistent homology algorithm. We demonstrated that simple data science algorithms can group together topologically similar simulated data. Pairs of topological descriptor vectors generated from sweeping plane filtrations robustly clustered simulations into five biologically interpretable groups. Simulations within each group were generated from similar values of the model parameters $\rho$ and $\chi$, which determine the sensitivity of the tip cells to haptotaxis and chemotaxis. The Betti numbers quantify connectedness of the vasculature across spatial scales. We computed PH of four sweeping plane filtrations (LTR, RTL, TTB, BTT), which quantify topological features as a plane moves across the simulated data in a particular direction. We found that the filtration direction provides information about different aspects of the vascular network. For the LTR filtration, the number of connected components (i.e., $\beta_0$) decreases when an anastomosis event occurs, whereas for the RTL filtration, $\beta_0$ decreases when a branching event occurs. The TTB and BTT filtrations summarize vascular tortuosity: when tip cell movement in the $y$-spatial direction is negligible and/or tip cells do not merge with adjacent sprouts, $\beta_0$ increases with the number of tip cells/ number of sprouts. We found that the combined PIO$_0(K^{LTR})$ \& PIO$_0(K^{RTL})$ sweeping plane descriptor vectors robustly cluster haptotaxis-chemotaxis parameter space into five distinct regions that appear to be connected. Our results may depend on the model setup, in which new blood vessels are created as endothelial tip cells move from left to right. In the future, we may explore the use of extended persistence \cite{Edelsbrunner2008} and/or PH transform \cite{turner2014persistent}, which allow consideration of multiple different directions in the topological analysis. If the vessel network grows radially, for example, then radial filtrations may be more informative than the LTR filtration \cite{Byrne2019,Stolz2020}. Classically in PH, topological features of short persistence are topological noise, yet there is growing evidence that these short features can provide information about geometry and curvature \cite{bendich_persistent_2016,Stolz2020,feng_persistent_2019,marchese_signal_2018,robins_principal_2016,stolz_persistent_2017,xia_persistent_2014,bubenik2020persistent}. Our results using persistence images with unit weightings, rather than ramped weightings, also suggest that short persistence features may be informative for distinguishing vessel morphologies. \new{The spatial resolution of the output binary images that we used for our analyses was the same as that used to generate the simulations, enabling us to distinguish the presence and absence of individual endothelial cells. In future work, we will consider finer and coarser binary images to investigate how the performance of the methods depends on their spatial resolution.} Many models of angiogenesis have been developed and implemented since the Anderson-Chaplain model, as has been extensively reviewed previously \cite{byrne_dissecting_2010,hadjicharalambous_tumour_2021,hamis_blackboard_2019,karolak_towards_2018,mantzaris_mathematical_2004,metzcar_review_2019,peirce_computational_2008,rockne_2019_2019,scianna_review_2013}. We plan to use the methods described in this work to interpret more sophisticated models of angiogenesis and, in the longer term, to determine how vessel morphology affects tumor survival and to predict the efficacy of vascular targetting agents. The tumor is not explicitly modeled in the Anderson-Chaplain model, but many studies couple angiogenesis and tumor growth \cite{owen_angiogenesis_2008,perfahl_3d_2017,norton_modeling_2018,vavourakis_validated_2017,vilanova_mathematical_2017}. For example, Vavourakis et al. developed a 3D model of angiogenic tumor growth that incorporates the effects of mechanotaxis on vessel sprouting and mechano-sensitive vascular remodelling \cite{vavourakis_validated_2017}. \new{Even though the Anderson-Chaplain model neglects mechanotaxis, subcellular signalling, and many other biophysical processes, it has been widely adopted due to its ability to generate networks which are in good agreement with those seen \emph{in vivo}. More complex models have been developed that account for mechanical factors such as mechanotaxis, pressure-driven convective transport of extracellular factors, mechanical stimulation of endothelial cell proliferation, and subcellular signalling pathways that guide cell fate specification of tip and stalk cells \cite{vavourakis_validated_2017, vilanova_computational_2018, perfahl_3d_2017, stepanova_multiscale_2021}. Importantly, these more complex models have been shown to recapitulate experimental observations of time-varying spatial distributions of angiogenic vasculature \cite{vavourakis_validated_2017} and features such as asymmetric neovasculature \cite{vilanova_computational_2018} and cell rearrangements and phenotype switching of endothelial stalk and tip cells \cite{chen_endothelial_2019,jakobsson_endothelial_2010}. In future work we will apply the TDA framework developed here to these, and other angiogenesis models. Such analyses will enable us to investigate the effect that processes such as mechanotaxis and subcellular signalling have on the topology of blood vessel networks. } \old{Vilanova et al. developed a phase-field model of vascular growth, regression, and re-growth that agrees with \emph{in vivo} experimental data \cite{vilanova_mathematical_2017}.} Miller at al. used computational models to analyze tumor regression in response to drug treatment as a function of vasculature morphology and heterogeneity \cite{ha_evaluation_2018}. \old{Our future analysis of such state-of-the-art modeling techniques will require us to extend the topological methods presented here to handle heterogeneous data comprised of multiple cell types in 3D.} \new{Our future analysis of such state-of-the-art modeling techniques will require us to extend the topological methods presented here for spatio-temporal data that describes how multiple cell types (e.g., tumor cells, immune cells and endothelial cells) interact in 3D. In a preliminary study, we applied these methods to 3D data from \emph{in vivo} studies of tumor vessel networks, which is near the edge of current computational feasibility \cite{Stolz2020}. Further work in this direction}\old{. and would } requires significant computational advancements to scale the TDA pipeline to multiple, more complex models and analyze the parameter landscape. The topological approaches considered in this work represent a multiscale way to summarize the properties of \textit{in silico} vasculature, and could be extended to experimental image data. Previous studies have quantified experimental data of tumor-induced angiogenesis using standard descriptors that include sprout length and diameter, number of tumor cells, concentration of angiogenic chemicals \cite{feleszko_lovastatin_1999,cai_long_2017,sailem2020morphological}. To compare models and data will require descriptors, such as the topological ones proposed here, that can discriminate between different conditions (e.g., parameter values). The challenges of making direct comparisons between experimental and synthetic data is a significant bottleneck in the validation of mathematical and computational models of angiogenesis. In future work we will apply the topological approaches outlined in this paper to compare different model simulations with experimental data \cite{gimbrone_tumor_1974,hlushchuk_morphological_2016}. In this way, we aim to determine biologically realistic parameter values for control conditions \cite{bauer_cell-based_2007}, and to identify parameter values that are associated with response to treatments, including vessel normalization. \section*{Acknowledgments} HAH, BJS and HB are grateful to the support provided by the UK Centre for Topological Data Analysis EPSRC grant EP/R018472/1. HAH gratefully acknowledges funding from EPSRC EP/R005125/1 and EP/T001968/1, the Royal Society RGF$\backslash$EA$\backslash$201074 and UF150238, and Emerson Collective. This work was partially supported by the National Science Foundation under Grant DMS-1638521 to the Statistical and Applied Mathematical Sciences Institute and IOS-1838314 to KBF, and in part by National Institute of Aging grant R21AG059099 to KBF. The funders had no role in study design, data collection and analysis, decision to publish, or preparation of the manuscript.
{'timestamp': '2021-04-23T02:29:04', 'yymm': '2101', 'arxiv_id': '2101.00523', 'language': 'en', 'url': 'https://arxiv.org/abs/2101.00523'}
arxiv
\subsection{Past Coverage Including Survey and Review Papers} As one of the core fields of research in robotics, SLAM has been the subject of a number of reviews, surveys and tutorials over the past few decades, including coverage of semantic concepts. A recent review of SLAM by Cadena \textit{et al.}~\cite{cadena2016past} positioned itself and other existing surveys as belonging to either classical~\cite{durrant2006simultaneous, bailey2006simultaneous, thrun2002probabilistic, stachniss2016simultaneous}, algorithmic-analysis~\cite{dissanayake2011review} or the ``robust perception'' age~\cite{cadena2016past}. This review highlighted the evolution of SLAM, from its earlier focus on probabilistic formulations and analyses of fundamental properties to the current and growing focus on robustness, scalablity and high-level understanding of the environment - where semantics comes to the fore. Also discussed were robustness and scalability in the context of long-term autonomy and how the underlying representation models, metric \textit{and} semantic, shape the SLAM problem formulation. For the high-level semantic representation and understanding of the environment, \cite{cadena2016past} discussed literature where SLAM is used for inferring semantics, and semantics are used to improve SLAM, paving the way for a joint optimization-based semantic SLAM system. They further highlight the key challenges of such a system, including consistent fusion of semantic and metric information, task-driven semantic representations, dynamic adaptation to changes in the environment, and effective exploitation of semantic reasoning. Kostavelis and Gasteratos~\cite{kostavelis2015semantic} reviewed semantic mapping for mobile robotics. They categorized algorithms according to scalability, inference model, temporal coherence and topological map usage, while outlining their potential applications and emphasizing the role of human interaction, knowledge representation and planning. More recently, \cite{davison2018futuremapping} reviewed current progress in SLAM research, proposing that SLAM including semantic components could evolve into ``Spatial AI'', either in the form of autonomous AI, such as a robot, or as Intelligent Augmentation (IA), such as in the form of an AR headset. A Spatial AI system would not only capture and represent the scene intelligently but also take into account the embodied device's constraints, thus requiring joint innovation and co-design of algorithms, processors and sensors. More recently, \cite{davison2019futuremapping} presented Gaussian Belief Propagation (GBP) as an algorithmic framework suited to the needs of a Spatial AI system, capable of delivering high performance despite resource constraints. The proposals in both~\cite{davison2018futuremapping} and \cite{davison2019futuremapping} are significantly motivated by rapid developments in processor hardware, and touch on the opportunities for closing the gap between intelligent perception and resource-constrained deployment devices. More recently, \cite{xia2020survey} surveyed the use of semantics for visual SLAM, particularly reviewing the integration of ``semantic extractors'' (object recognition and semantic segmentation) within modern visual SLAM pipelines. Much of the growth in semantics-based approaches has coincided with the increase in capabilities brought about by the modern deep learning revolution. Schmidhuber~\cite{schmidhuber2015deep} presented a detailed review of deep learning in neural networks as applied through supervised, unsupervised and reinforcement learning regimes. They introduced the concept of ``Credit Assignment Paths'' (CAPs) representing chains of causal links between events, which help understand the level of depth required for a given Neural Network (NN) application. With a vision of creating general purpose learning algorithms, they highlighted the need for a brain-like learning system following the rules of fractional neural activation and sparse neural connectivity. \cite{liu2020deep} presented a more focused review of deep learning, surveying generic object detection. They highlighted the key elements involved in the task such as the accuracy-efficiency trade-off of detection frameworks, the choice and evolution of backbone networks, the robustness of object representation and reasoning based on additionally available context. A significant body of work has focused on extracting more meaningful abstractions of the raw data typically obtained in robotics such as 3D point clouds. Towards this end, a number of surveys have been conducted in recent years for point cloud filtering~\cite{han2017review} and description~\cite{hana2018comprehensive}, 3D shape/object classification~\cite{liu2019deep, guo2020deep}, 3D object detection~\cite{ioannidou2017deep, arnold2019survey, rahman2019recent, liu2019deep, guo2020deep}, 3D object tracking~\cite{guo2020deep} and 3D semantic segmentation~\cite{grilli2017review, ioannidou2017deep, zhang2019review, lateef2019survey, xie2020review, malinverni2019deep, liu2019deep, guo2020deep}. With only a couple of exceptions, all of these surveys have particularly reviewed the use of \textit{deep learning} on 3D point clouds for respective tasks. Segmentation has also long been a fundamental component of many robotic and autonomous vehicle systems, with \textit{semantic} segmentation focusing on labeling areas or pixels in an image by class type. In particular the overall goal is to label by class, not by instance. For example, in an autonomous vehicle context this goal constitutes labeling pixels as belonging to \textit{a} vehicle, rather than as a specific instance of a vehicle (although that is also an important capability). The topic has been the focus of a large quantity of research with resulting survey papers that focus primarily on semantic segmentation, such as \cite{lateef2019survey, garcia2018survey, guo2018review, zhao2017survey, siam2017deep, thoma2016survey, zhu2016beyond}. Beyond these flagship domains, semantics have also been investigated in a range of other subdomains. \cite{Ramirez-Amaro2019} reviewed the use of semantics in the context of understanding human actions and activities, to enable a robot to execute a task. They classified semantics-based methods for \textit{recognition} into four categories: syntactic methods based on symbols and rules, affordance-based understanding of objects in the environment, graph-based encoding of complex variable relations, and knowledge-based methods. In conjunction with recognition, different methods to \textit{learn and execute} various tasks were also reviewed including learning by demonstration, learning by observation and execution based on structured plans. Likewise for the service robotics field, \cite{Liu2016} presented a survey of vision-based semantic mapping, particularly focusing on its need for an effective human-robot interface for service robots, beyond pure navigation capabilities. \cite{paulius2019survey} also surveyed knowledge representations in service robotics. Many robots are likely to require image retrieval capabilities where semantics may play a key role, including in scenarios where humans are interacting with the robotic systems. \cite{enser2003towards} and \cite{Liu2007} surveyed the ``semantic gap'' in current content-based image retrieval systems, highlighting the discrepancy between the limited descriptive power of low-level image features and the typical richness of (human) user semantics. Bridging this gap is likely to be important for both improved robot capabilities \textit{and} better interfaces with humans. Some of the reviewed approaches to reducing the semantic gap, as discussed in~\cite{Liu2007}, include the use of object ontology, learning meaningful associations between image features and query concepts and learning the user's intention by relevance feedback. This semantic gap concept has gained significant attention and is reviewed in a range of other papers including~\cite{li2016socializing, sudha2015reducing, ramkumar2014ontology, zhang2012review, ehrig2006ontology, hare2006mind, wen2005review}. Acting upon the enriched understanding of the scene, robots are also likely to require sophisticated grasping capabilities, as reviewed in \cite{du2020vision}, covering vision-based robotic grasping in the context of object localization, pose estimation, grasp detection and motion planning. Enriched interaction with the environment based on an understanding of what can be done with an object - its ``affordances'' - is also important, as reviewed in \cite{ardon2020affordances}. Enriched interaction with humans is also likely to require an understanding of language, as reviewed recently by \cite{tellex2020}. This review covers some of the key elements of language usage by robots: collaboration via dialogue with a person, language as a means to drive learning and understanding natural language requests, and deployment, as shown in application examples. \subsection{Summary and Rationale for this Survey} The majority of semantics coverage in the literature to date has occurred with respect to a specific research topic, such as SLAM or segmentation, or targeted to specific application areas, such as autonomous vehicles. As can be seen in the previous section, there has been both extensive research across these fields as well as a number of key survey and review papers summarizing progress to date. These deep dives into specific sub-areas in robotics can provide readers with a deep understanding of technical considerations regarding semantics in that context. As the field continues to grow however there is increasing need for an overview that more broadly covers semantics across all of robotics, whilst still providing sufficient technical coverage to be of use to practitioners working in these fields. For example, while~\cite{cadena2016past} extensively considers the use of semantics primarily within SLAM research, there is a need to more broadly cover the role of semantics in various robotics tasks and competencies which are closely related to each other. The task, ``bring a cup of coffee'', likely requires semantic understanding borne out of both the underlying SLAM system \textit{and} the affordance-grasping pipeline. This survey therefore goes beyond specific application domains or methodologies to provide an overarching survey of semantics across all of robotics, as well as the semantics-enabling research that occurs in related fields like computer vision and machine learning. To encompass such a broad range of topics in this survey, we have divided our coverage of research relating to semantics into a) the fundamentals underlying the current and potential use of semantics in robotics, b) the widespread use of semantics in robotic mapping and navigation systems, and c) the use of semantics to enhance the range of interactions robots have with the world, with humans, and with other robots. This survey is also motivated by timeliness: the use of semantics is a rapidly evolving area, due to both significant current interest in this field, as well as technological advances in local and cloud compute, and the increasing availability of data that is critical to developing or training these semantic systems. Consequently, with many of the key papers now half a decade old or more, it is useful to capture a snapshot of the field as it stands now, and to update the treatment of various topic areas based on recently proposed paradigms. For example, this paper discusses recent semantic mapping paradigms that mostly post-date key papers by~\cite{cadena2016past, kostavelis2015semantic}, such as combining single- and multi-view point clouds with semantic segmentation to directly obtain a local semantic map~\cite{Qi2017a, lawin2017deep, huang2016point, Boulch2018, Dai2018a}. Whilst contributing a new overview of the use of semantics across robotics in general, we are also careful to adhere where possible to recent proposed taxonomies in specific research areas. For example, in the area of 3D point clouds and their usage for semantics, within Section~\ref{sec:semRep+SU+SLAM}, with the help of key representative papers, we \textit{briefly} describe the recent research evolution of using 3D point cloud representations for learning object- or pixel-level semantic labeling, in line with the taxonomy proposed by existing comprehensive surveys~\cite{guo2020deep, liu2019deep, lateef2019survey, xie2020review, ioannidou2017deep}. Finally, beyond covering new high level conceptual developments, there is also the need to simply update the paper-level coverage of what has been an incredibly large volume of research in these fields even over the past five years. The survey refers to well over a hundred research works from the past year alone, representative of a much larger total number of research works. This breadth of coverage would normally come at the cost of some depth of coverage: here we have attempted to cover the individual topics in as much detail as possible, with over 900 referenced works covered in total. Where appropriate we also make reference to prior survey and review papers where further detailed coverage may be of interest, such as for the topic of 3D point clouds and their usage for semantics. Moving beyond single application domains, we also provide an overview of how the use of semantics is becoming an increasingly integral part of many trial (and in some cases full scale commercial) deployments including in autonomous vehicles, service robotics and drones. A richer understanding of the world will open up opportunities for robotic deployments in contexts traditionally \textit{too difficult} for safe robotic deployment: nowhere is this more apparent perhaps than for on-road autonomous vehicles, where a subtle, nuanced understanding of all aspects of the driving task is likely required before robot cars become comparable to, or ideally superior to, human drivers. Compute and data availability has also enabled many of the advancements in semantics-based robotics research; likewise these technological advances have also facilitated investigation of their deployment in robotic applications that previously would have been unthinkable - such as enabling sufficient on-board computation for deploying semantic techniques on power- and weight-limited drones. We cover the current and likely future advancements in computational technology relevant to semantics, both local and online versions, as well as the burgeoning availability of rich, informative datasets that can be used for training semantically-informed systems. In summary, this survey paper aims to provide a unifying overview of the development and use of semantics across the entire robotics field, covering as much detailed work as feasible whilst referencing the reader to further details where appropriate. Beyond its breadth, the paper represents a substantial update to the semantics topics covered in survey and review papers published even only a few years ago. By surveying the technical research, the application domains and the technology enablers in a single treatment of the field, we can provide a unified snapshot of what is possible now and what is likely to be possible in the near future. \subsection{Taxonomy and Survey Structure} \begin{figure} \centering \includegraphics[width=\textwidth]{images/taxonomy.eps} \caption{A taxonomy for semantics in robotics. Four broad categories of semantics research are complemented by technological, knowledge and training-related enhancers and lead to a range of robotic applications. Areas can be primarily involved in extracting semantics, using semantics or a combination of both.} \label{fig:taxonomy} \end{figure} Existing literature covering the role of \textit{semantics} in robotics is fragmented and is usually discussed in a variety of task- and application-specific contexts. In this survey, we consolidate the disconnected semantics research in robotics; draw links with the fundamental computer vision capabilities of extracting semantic information; cover a range of potential applications that typically require high-level decision making; and discuss critical upcoming enhancers for improving the scope and use of semantics. To aid in navigating this rapidly growing and already sizable field, here we propose a taxonomy of semantics as it pertains to robotics (see Figure~\ref{fig:taxonomy}). We find the relevant literature can be divided into four broad categories: \begin{enumerate} \item \textit{Static and Un-embodied Scene Understanding}, where the focus of research is typically on developing intrinsic capability to extract semantic information from images, for example, object recognition and image classification. The majority of research in this direction uses single image-based 2D input to infer the underlying semantic or 3D content of that image. However, image acquisition and processing in this case is primarily static in nature (including videos shot by a static camera), separating it conceptually from a mobile embodied agent's dynamic perception of the environment due to motion of the agent. Because RGB cameras are widely used in robotics, and the tasks being performed, such as object recognition, are also performed by robots, advances in this area are relevant to robotics research. In Section \ref{secn:semanticsfundamental}, we introduce the fundamental components of semantics that relate to or enable robotics, focusing on topics that have been primarily or initially investigated in non-robotics but related research fields, such as computer vision. We cover the key components of semantics as regards object detection, segmentation, scene representations and image retrieval, all highly relevant capabilities for robotics, even if not all the work has yet been demonstrated on robotic platforms. \item \textit{Dynamic Environment Understanding and Mapping}, where the research is typically motivated by the mobile or dynamic nature of robots and their surroundings. The research literature in this category includes the task of semantic mapping, which could be topological, or a dense and precise 3D reconstruction. These mapping tasks can often leverage advances in static scene understanding research, for example, place categorization (image classification) forming the basis of semantic topological mapping, or pixel-wise semantic segmentation being used as part of a semantic 3D reconstruction pipeline. Semantic maps provide a representation of information and understanding at an environment or spatial level. With the increasing use of 3D sensing devices, along with the maturity of visual SLAM, research on semantic understanding of 3D point clouds is also growing, aimed at enabling a richer semantic representation of the 3D world. In Section \ref{secn:mappingSLAM}, we cover the use of semantics for developing representations and understanding at an environment level. This includes the use of places, objects and scene graphs for semantic mapping, and 3D scene understanding through Simultaneous Localization And Mapping (SLAM) and point clouds processing. \item \textit{Interacting with Humans and the World}, where the existing research ``connects the dots" between the ability to \textit{perceive} and the ability to \textit{act}. The literature in this space can be further divided into the ``perception \textit{of} interaction'' and ``perception \textit{for} interaction''. The former includes the basic abilities of understanding actions and activities of humans and other dynamic agents, and enabling robots to learn from demonstration. The latter encompasses research related to the use of the perceived information to act or perform a task, for example, developing a manipulation strategy for a detected object. In the context of robotics, detecting an object's affordances can be as important as recognizing that object, enabling semantic reasoning relevant to the task and affordances (e.g. `cut' and `contain') rather than to the specific object category (e.g. `knife' and `jar'). While object grasping and manipulation relate to a robot's interaction with the environment, research on interaction with other \textit{humans} and \textit{robots} includes the use of natural language to generate inverse semantics, or to follow navigation instructions. Section \ref{secn:interaction} addresses the use of semantics to facilitate robot interaction with the world, as well as with the humans and robots that inhabit that world. It looks at key issues around affordances, grasping, manipulation, higher-level goals and decision making, human-robot interaction and vision-and-language navigation. \item \textit{Improving Task Capability}, where researchers have focused on utilizing semantic representations to improve the capability of other tasks. This includes for example the use of semantics for high-level reasoning to improve localization and visual place recognition techniques. Furthermore, semantic information can be used to solve more challenging problems such as dealing with challenging environmental conditions. Robotics researchers have also focused on techniques that unlock the full potential of semantics in robotics, since existing research has not always been motivated by or had to deal with the challenges of real world robotic applications, by addressing challenges like noise, clutter, cost, uncertainty and efficiency. In Section~\ref{secn:improvingTask}, we discuss various ways in which researchers extract or employ semantic representations for localization and visual place recognition, dealing with challenging environmental conditions, and generally enabling semantics in a robotics context through addressing additional challenges. \end{enumerate} The four broad categories presented above encompass the relevant literature on how semantics are defined or used in various contexts in robotics and related fields. This is also reflected in Figure~\ref{fig:taxonomy} through `extract semantics' and `use semantics' labels associated with different sections of the taxonomy. Extracting semantics from images, videos, 3D point clouds, or by actively traversing an environment are all methods of creating semantic representations. Such semantic representations can be input into high-level reasoning and decision-making processes, enabling execution of complex tasks such as path planning in a crowded environment, pedestrian intention prediction, and vehicle trajectory prediction. Moreover, the use of semantics is often fine-tuned to particular applications like agricultural robotics, autonomous driving, augmented reality and UAVs. Rather than simply being exploited, the semantic representations themselves can be jointly developed and defined in consideration of how they are then used. Hence, in Figure~\ref{fig:taxonomy}, the sections associated with `use semantics' are also associated with `extract semantics'. These high-level tasks can benefit from advances in fundamental and applied research related to semantics. But this research alone is not enough: advances in other areas are critical, such as better cloud infrastructure, advanced hardware architectures and compute capability, and the availability of large datasets and knowledge repositories. Section \ref{secn:discussion} reviews the influx of semantics-based approaches for robotic deployments across a wide range of domains, as well as the critical technology enablers underpinning much of this current and future progress. Finally, Section \ref{secn:conclusion} discusses some of the key remaining challenges in the field and opportunities for addressing them through future research, concluding coverage of what is likely to remain an exciting and highly active research area into the future. \subsection{Image Classification and Retrieval} Image classification is the process of determining the content shown within an image, typically at a \textit{whole} image level, although the process may involve detecting and recognizing specific objects or regions within the overall image. Complementing classification, image retrieval refers to the process of parsing a database of images and picking out images that meet a certain content criteria, which can be specified in a number of ways. For example, images can be retrieved based on a ``query'' image (find images with similar content), or based on some description of the desired content within the image (find images of trees). Image retrieval in particular has a strong overlap with visual mapping and place recognition techniques, and hence much of the mapping or spatially-specific retrieval research is covered in that section. Here we touch on classification and retrieval techniques with a focus on developments in the semantic space. \subsubsection{Image-based Classification} A typical goal of this task is to semantically tag images based on their visual content, for example, classifying an image as belonging to a category like ``peacock'' or ``train station''. The former represents the presence of an ``object'' within an image, whereas the latter represents a ``place''. In a broader sense however, image classification or recognition can be based on a hierarchy of concepts that might exist in the visual observation. \cite{Li-jiaLi2009} presented a hierarchical generative model that classifies the overall scene, recognizes and segments each object component, and annotates the image with a list of tags. It is claimed to be the first model that performs all three tasks in one coherent framework. The framework was able to learn robust scene models from noisy web data such as images and user tags from Flickr.com. \cite{Li2010} proposed a high-level image representation, \textit{Object Bank}, based on a scale-invariant response map of a large number of pre-trained generic object detectors, for the task of object recognition and scene classification. \cite{Yao2012} designed an approach to jointly reason about regions, location, class and spatial extent of objects, the presence of a class in the image, and the scene type. The novel reasoning scheme at the segment level enabled efficient learning and inference. \cite{Sanchez2013} proposed the \textit{Fisher Vector} - a state-of-the-art patch encoding technique - as an alternative to Bag of Visual Words (BoVW), where patches are described by their derivation from a universal generative Gaussian Mixture Model (GMM). \cite{Qi2019} developed a Bag of Semantic Words (BoSW) model based on automatic dense image segmentation and semantic annotation, achieved by graph cut and (Support Vector Machine) SVM respectively. While the SVM learns one-versus-all classification for different semantic categories, the reduced vocabulary size due to BoSW decreases computation time and increases accuracy. While effective, the methods above rely on hand-designed image features that are not optimally designed for image classification. Consequently alternative approaches that can automatically learn not only the classifier, but also the optimal features, have been investigated, with methods based on deep learning techniques generally being superior, as detailed below. Like many other research areas, deep learning has played an increasing role in image classification over the past decade. With the availability of large-scale image dataset like ImageNet~\cite{deng2009imagenet} and the availability of Graphics Processing Units (GPUs), learning via \textit{deep} Convolutional Neural Network (CNN) such as AlexNet~\cite{krizhevsky2012imagenet} opened up enormous opportunities for enhanced scene understanding. \cite{zhou2014learning} introduced the \textit{Places} dataset, consisting of 7 million labeled scenes, and demonstrated state-of-the-art performance on scene-centric datasets. Through this dataset, complementing ImageNet, \cite{zhou2014learning} highlighted the differences in internal representations of object-centric and scene-centric networks. \cite{Zhou2018} extended this line of work, discussing the released Places database of 10 million images and its corresponding Places-CNNs baselines for scene recognition problems. \cite{zhou2015object} showed that object detectors naturally emerge from training CNNs for scene classification. They argue that since scenes are typically composed of objects, CNNs trained on them automatically discover meaningful object detectors, representative of the learned scene category. This work then demonstrated that the same network can perform both scene recognition and object localization in a single forward-pass, without an explicitly taught notion of objects. The methods above are generally referred to as weakly supervised detectors, because they are trained with scene-level annotations but are able to localise objects within a scene. One of their main limitations was that their object detection accuracy was significantly inferior to fully supervised detection methods that relied on object localisation labels -- further research in the area has focused on reducing this performance gap. A CNN visualisation technique was presented in \cite{Zhou2016} where the Class Activation Map (CAM) was based on Global Average Pooling (GAP) in CNNs. This work demonstrated that GAP enables accurate localization ability (i.e. activation of scene category-specific local image regions), despite being trained on image-level labels for scene classification. Meng \textit{et al}.~\cite{Meng2017} designed a first-of-its-kind semantic place categorization system based on text-image pairs extracted from social media. They concatenate and learn features from two CNNs -- one each for the two modalities -- to predict the place category. The proposed system uses a newly curated dataset with 8 semantic categories: home, school, work, restaurant, shopping, cinema, sports, and travel. \cite{Wei2019} explored aggregation of CNN features through two different modules: a ``Content Estimator'' and a ``Context Estimator'', where the latter is comprised of three sub-modules based on text, object and scene context. The authors claim it is the first work that leverages text information from a scene text detector for extracting context information. The papers above were successful at introducing approaches that combined different modalities, but did not include geometrical information, limiting their ability to ``understand'' the scene. When depth information is available, including when explicitly available from range-based sensors, RGB-D-based scene recognition and classification techniques classify scene images using aligned color and depth information. Wang \textit{et al.} \cite{wang2016modality} extracted and combined deep discriminative features from different modalities in a component-aware fusion manner. Gupta \textit{et al.} \cite{gupta2016cross} transferred the RGB model to depth net using unlabeled paired data according to their mid-level representations. More recently, Du \textit{et al.} \cite{du2019translate} presented a unified framework to integrate the tasks of cross-modal translation and modality specific recognition. While additional cues in the form of depth information or text descriptions improve image classification, the essence of the task is to enable semantic scene understanding by providing a ``compressed'' but meaningful representation of the visual observation, which a robot can then use to intelligently reason about the environment. \subsubsection{Semantics for Image Retrieval and Classification} Except in specific circumstances or in the case of instance-level retrieval (finding a specific image), broader content-based image retrieval generally requires some semantics-based knowledge of the content of images in order to be feasible. Much of the research in this area has focused on what form that knowledge should take, and how similarity should be calculated. \cite{Hong2016} explored concept-relationship based feature extraction and learning using textual and visual data for content based image retrieval. This was achieved by using five pre-defined specific concept relationships: \textit{complete similarity} (Beijing, Peking), \textit{type similarity} (Husky, Bulldog), \textit{Hypernym Hyponym} (Husky, Domestic Dog), \textit{Parallel relationship} (cat, dog), and \textit{unknown relationship}; these conceptual semantic relationships were shown to improve retrieval performance. \cite{huang2018sketch} proposed fusing low-level and high-level features from sketches and images, along with clustering-based re-ranking optimization for image retrieval. \cite{lu2017latent} developed a novel joint binary codes learning method that combines image features with latent semantic features (labels/tags of images); the intent was to encode samples sharing the same semantic concepts into similar codes, rather than only preserving geometric structure via hashing. \cite{Gordo2017} explored a method to retrieve images based on semantic information like ``a boy jumping'' or ``throw'', as opposed to traditional instance-level retrieval. They proposed a similarity function based on annotators' captions as a computable surrogate of true semantic similarity for learning a semantic visual representation. Learning a joint embedding for visual and textual representations improved accuracy, and enabled combined text and image based retrieval. To reduce the semantic gap in existing visual BoW approaches, \cite{Bai2018} extracted SIFT~\cite{lowe2004distinctive}, Local Binary Patterns (LBP)~\cite{ojala2002multiresolution}, and color histogram features \textit{separately} for the foreground and background in an image, segmented using the SaliencyCut method~\cite{Cheng2015}. \cite{Quinn2018} presented \textit{Situate} - an architecture to learn models that capture visual features of objects and their spatial configuration to retrieve instances of visual situations like ``walking a dog'' or ``a game of ping-pong''. The method actively searches for each expected component of the situation in the image to calculate a matching score. \cite{Barz2019} explored hierarchy-based semantic embeddings for image retrieval by incorporating prior knowledge about semantic relationships between classes obtained from the class hierarchy of \textit{WordNet}~\cite{miller1998wordnet}. \cite{lee2019sfnet} used an end-to-end trainable CNN to learn ``semantic correspondences'' as dense flow between images depicting different instances of the same semantic object category, such as a bicycle. To train the CNN, they used binary segmented images with synthetic geometric transformations and a new differentiable \textit{argmax} function. \cite{li2019visual} proposed the Visual Semantic Reasoning Network (VSRN), based on connections \textit{between} image regions (ROIs from F-RCNN~\cite{ren2015faster}). This approach learns features with semantic relationships from the pairwise affinity between regions using a Graph Convolutional Network. The research included both image-to-text (caption) and text-to-image (image) retrieval capabilities; the learnt representation (also visualized in 2D) captures key semantic objects (bounding boxes) and semantic concepts (within a caption) of a scene as in the corresponding text caption. \cite{Engilberge2018} designed a new two-path neural network architecture that maps images and text while enabling spatial localization in the proposed semantic-visual embedding. Using this system, text queries like ``a burger'', ``some beans'' and ``a tomato'', can be localized in an image comprising all of these. \cite{Chang2017} presented a framework for event detection that uses ``semantic interaction'' based on pairwise affinity between semantic representations of multiple source videos. This approach enables the detection of events such as ``birthday party'', ``grooming an animal'', ``town hall meeting'' or ``marriage proposal''. Semantic image retrieval and semantic image classification are closely related to each other, as improved methods for the latter inherently enable higher accuracy for the former. This is in part due to the high level of abstraction and reasoning capability that is attained through semantically representing images. Such an approach also bridges the gap between natural language semantics of humans and the user's intended retrieval outcome, thus reducing the \textit{semantic gap}. In a world where robots and humans co-exist, reducing the semantic gap will likely lead to more seamless human-robot interaction. \subsection{Object Detection and Recognition} While semantic reasoning at the \textit{whole} image level can enable high-level decision making for a robot such as that required for path planning, semantically understanding the content \textit{within} an observed image is necessary for a robot to perform a task such as manipulating an object. A key task for many robots operating in real world environments therefore is object detection and recognition. While there is no absolute definition of what constitutes an object, general definitions revolve around the concept of objects being distinct things or entities in the environment, with the ability to be seen and touched. Before moving into more sophisticated uses of objects and object understanding in the context of robotic tasks like mapping and environmental interaction, we first cover some key background. \textit{Detection} is exactly that: detecting what objects are present in a particular environment, observed through the robot's sensors. \textit{Recognition} involves calculating what types of objects are present, and can be performed at both a class level - all the mugs in the room - and at instance level - a specific, single mug. Classical approaches to object recognition include \textit{template-based} approaches, which match potential objects in the scene to some form of 2D or 3D \textit{exemplar} of the object class; \textit{hand-crafted feature-based} methods, which build object structures on top of simple edge, SIFT~\cite{lowe1999object} or SURF~\cite{bay2006surf} features, and \textit{direct} approaches that perform matching based on pixel intensities or intensity gradients in an image. Because of the inherent difficulty of the problem in all but the simplest of circumstances, decades of research has developed enhancements to these processes including efficient tree-based search methods, various geometric matching tests and a range of other mechanisms. With the advent of modern deep learning techniques, a number of key advances were made in CNN-based object detection approaches, including Fast R-CNN~\cite{Girshick2015}, SPPNet~\cite{He2015} and Faster R-CNN~\cite{ren2015faster}. In particular, approaches have started to investigate the use of semantics as part of the detection pipeline. \cite{cadena2015icra} presented a modular scene understanding system that used semantic segmentation to improve object detection performance for out-of-the-box specific object detectors. In the 3D object detection area, \cite{simon2019complexer} explored a detection and tracking pipeline for autonomous vehicles using RGB, LiDAR, and dense semantic segmentation to form semantic point clouds (voxel grids), which are then fed into Complex-YOLO to obtain 3D detections. They use Labeled Multi-Bernoulli-Filter for multi-target tracking and claim to be the first to fuse visual semantics with 3D object detection. \cite{Yao2019} presented a generic object tracking framework that uses a semantic segmentation network for object proposals by ranking and selecting relevant feature maps from the final layer based on activations. Temporal information and template models were used to improve prediction. \cite{Zhang2018} designed a Detection with Enriched Semantics (DES) network for object detection that uses semantic segmentation as an input to the network (in a weakly supervised manner) to enrich the learnt feature maps. They also use a global activation module for extracting high-level information from higher-order layers of the network. \cite{Li2019a} proposed an end-to-end learning framework for pedestrian attribute recognition using a Graph Convolution Network comprising sub-networks: one to capture spatial relations between image regions and another to learn semantic relationships between attributes. The state-of-the-art 2D object detectors have also been shown to be useful in facilitating automated annotation and recovery of 3D objects when used in conjunction with sparse LiDAR data, as demonstrated recently in ~\cite{zakharov2020autolabeling}. Pursuing this capability is partly motivated by the current requirement for enhanced 3D scene understanding to enable practical applications like autonomous driving. Given this requirement, there has been significant activity in 3D object detection research, which is covered in detail in Section~\ref{sec:semRep+SU+SLAM}, especially in the context of using 3D point clouds. In robotics, object detection and recognition is fundamental to the core competencies of a robot, that is, perception and interaction. Spatially-intelligent robots would require understanding both the object of interest and everything else that surrounds it in order to successfully perform many tasks, which can only be achieved by accurate 2D and 3D object recognition and dense semantic segmentation. \subsection{Dense Pixel-wise Segmentation} Object-only semantic understanding is typically motivated by applications that define an object or region of interest; it is detected, recognized, often tracked, and in the case of robotics, grasped and manipulated. While dealing with objects, the ``background'' information is typically discarded. In an indoor environment where the task might be counting coffee mugs of different colors, this background information exists in the form of walls, floors, and ceilings. Similarly, for an outdoor environment, the task of pedestrian detection and tracking might consider roads and buildings as background. Beyond the notion of background, the lack of a single unique way of representing object shapes paves the way for dense image segmentation. Like object detection, segmentation is a research topic with great relevance to robotics (especially autonomous vehicles in recent years) where much of the pioneering work was performed in the computer vision domain. The core segmentation task is straightforward to describe: partitioning an image up into segments, but the ways in which this can be achieved, and its subsequent use cases for robotics vary hugely. Segmentation is tightly coupled to semantics because the most common segmentation approaches revolve around dividing up the image into semantically meaningful areas, with objects being a common example - in an autonomous vehicle context this could be pedestrians, vehicles, and traffic signs. Dense semantic segmentation is not only often more informative than \textit{specific} object detection, it also discloses various ways of leveraging additional context for performing a task, for example, utilizing spatial co-existence or physics based priors. Semantic segmentation is increasingly becoming a core part of systems in the robotics field and its development and use in mapping or interaction contexts is covered in the appropriate sections later in this survey. Here we overview the key foundational work which many of these robotic systems then build upon. \subsubsection{2D Semantic Segmentation} The world is a three-dimensional environment but much of the key work has occurred in the 2D image co-ordinate space. Already a significant research topic before modern deep learning techniques became dominant, earlier works involved elevating the capability of coherent region-based segmentation~\cite{lucchese2001colour}, including watershed~\cite{vincent1991watersheds} and mean-shift~\cite{comaniciu2002mean} like techniques, to a more meaningful parts-based semantic segmentation~\cite{schnitman2006inducing, athanasiadis2007semantic, lempitsky2011pylon}. \cite{schnitman2006inducing} induced semantic labeling using an example image from a common image domain based on a non-parametric model. \cite{athanasiadis2007semantic} presented semantic segmentation and object labeling based on a novel region-growing algorithm, combined with context obtained from ontological knowledge representation. \cite{lempitsky2011pylon} explored a hierarchical tree based, rather than flat, partitioning of an image~\cite{fulkerson2009class, shotton2006textonboost} within the scope of using graph cut~\cite{boykov2001fast} for image segmentation. Given that these approaches were mostly based on prior information about particular segmentation tasks, it was challenging for them to produce highly accurate segmentation results. With the advent of modern deep learning came a proliferation of new semantic segmentation methods. Long \textit{et al}.~\cite{Long2015} presented the Fully Convolutional Network (FCN) that processes arbitrary size input images and produces correspondingly-sized output with efficient inference and learning. They also defined a skip architecture that combines semantic information from a deep, coarse layer with appearance information from a shallow fine layer to produce accurate and detailed segmentations. Yu \textit{et al}.~\cite{yu2015multi} designed a CNN specifically for dense prediction, with their proposed model based on ``dilated convolutions'' systematically aggregating multi-scale contextual information without losing resolution. Badrinarayanan \textit{et al}.~\cite{Badrinarayanan2017} presented SegNet, an ``encoder-decoder'' architecture for semantic segmentation. The main novelty of SegNet was in the up-sampling strategy, where the decoder used the pooling indices from the encoder's max pooling step to perform non-linear up-sampling, thereby eliminating the need for learning to up-sample. The system was relatively efficient in terms of memory and computation time. Another relevant model was the Unet~\cite{ronneberger2015u}, that consisted of an encoder-decoder architecture with skip connections from the contracting path (i.e., encoder) to the expanding path (i.e., decoder), with the goal of addressing the issue of vanishing gradients. These approaches represent some of the first attempts to use deep learning for semantic segmentation, and the impressive results at that time significantly motivated the development of new deep learning approaches. The Efficient neural Network (ENet) was proposed by Paszke \textit{et al}.~\cite{Paszke2016} for tasks requiring low latency operations; their network was up to 18x faster, required 75x less FLOPs, and had 79x less parameters than comparable methods at the time, while achieving similar or better accuracy. Chen \textit{et al}.~\cite{Chen2018a} designed a semantic segmentation network based on: 1) atrous (dilated) convolutions that enlarged the field of view of filters using the same number of parameters, 2) Atrous Spatial Pyramid Pooling (ASPP) that aided in segmenting objects at multiple scales, and 3) fully connected CRFs that improved the localization boundaries. More recently, Takikawa \textit{et al}. presented the Gated-SCNN~\cite{takikawa2019gated}: a two-branch CNN model that analyses the RGB image and an image gradient (representing the shape information of the image). These branches are connected by a new type of gating mechanism that joins the higher-level activations of the RGB image to the lower-level activations of the gradient image. Gated-SCNN~\cite{takikawa2019gated} held the state-of-the-art segmentation results in several public computer vision datasets. As the application of segmentation methods continued to expand into challenging scenarios such as autonomous vehicles, it became clear that improvements were needed to make them perform well in challenging or adverse environmental conditions. Sakaridis \textit{et al}.~\cite{Sakaridis2018} developed a pipeline to add synthetic fog to real clear-weather images using incomplete depth information, to address the problem of semantic scene understanding in foggy conditions. They used supervised and semi-supervised learning techniques to improve performance, introducing the Foggy Driving dataset and Foggy Cityscapes dataset. In order to deal with variations in weather conditions, \cite{erkent2020semantic} explored unsupervised domain adaptation to learn accurate semantic segmentation in a \textit{challenging target} weather condition using an \textit{ideal source} weather condition. Integrating information over time - in an autonomous vehicle context for example over multiple camera frames - can also improve performance in challenging circumstances. Kundu \textit{et al}.~\cite{Kundu2016} proposed a method for long-range spatio-temporal regularization in semantic video segmentation, in contrast to a naive regularization over the video volume, which does not take into account camera and object motion. They used optical flow and dense CRF over points optimized in Euclidean feature space to improve accuracy, and demonstrated the effectiveness of the method on outdoor Cityscapes data~\cite{Cordts2016}. \cite{guarino20temporal} presented a Bayesian filtering approach to semantic segmentation of a video sequence, where each pixel is considered a random variable with a discrete probability distribution function. He \textit{et al}.~\cite{He2017a} presented a superpixel-based multi-view CNN for semantic segmentation that leveraged information from additional views of the scene, by first computing region correspondences through optical flow and superpixels, and then using a novel spatio-temporal pooling layer to aggregate information over space and time. The training process in this case benefited from unlabeled frames that led to improved prediction performance. More recently, in order to address the problem of data labeling for supervised semantic segmentation, \cite{lottes2020gradient} employed gradient and log-based active learning for semantic segmentation to distinguish between crop and weed plants in an agricultural field. To foster research in the context of temporally-coherent semantic segmentation, \cite{perazzi2016benchmark} presented a video segmentation benchmark using the proposed DAVIS (Densely Annotated VIdeo Segmentation) dataset. The benchmark helped increase the community's interest in developing novel techniques to address this task. \cite{caelles2017one} proposed a one-shot video object segmentation method that used only a single labeled training example, that is, the first frame. In order to reduce the reliance on large-scale data, \cite{wang2017video} leveraged existing annotated image datasets to augment video training data, enabling them to learn diverse saliency information while also preventing overfitting due to limited original data. In an extended work~\cite{wang2017saliency}, the authors considered the task of unsupervised video segmentation, leveraging object saliency cues to achieve temporally-consistent pixel labeling. \cite{perazzi2017learning} presented a learning strategy based on single image segmentation and incremental frame-by-frame processing to refine video object segmentation. While spatio-temporal cues have been demonstrated to be useful for segmentation in \textit{videos}, \cite{pathak2017learning} presented a learning framework to correctly group pixels based on motion, to improve object segmentation in \textit{static images}. Beyond semantic segmentation based on classes, instance-level segmentation - recognizing specific singular areas of interest - is also highly relevant for many robotic applications. Held \textit{et al}.~\cite{Held2016} developed a real-time probabilistic 3D segmentation method that combined spatial, temporal, and semantic information to help in the decision between splitting and merging of the initial coarse segmentation, significantly reducing under- and over-segmentation results on the KITTI dataset. The Faster R-CNN~\cite{ren2015faster} approach was also extended by He \textit{et al}.~\cite{He2017} for instance segmentation, by adding a branch for predicting object masks in parallel with existing bounding box recognition. The proposed system demonstrated state-of-the-art results on the following COCO challenges: instance segmentation, bounding box object detection, and person keypoint detection. Bai \textit{et al}.~\cite{Bai2017} presented a CNN combining classical watershed transform and modern deep learning to produce an energy map of an image, where object instances are unambiguously represented as energy basins, enabling direct extraction of high quality object instances. Methods based on metric learning~\cite{harley2017segmentation,newell2017associative} have been explored for instance-level segmentation, with the aim of learning a pixel-based embedding where pixels of the same instance have a similar embedding. One of the current state-of-the-art methods is the masking score RCNN (MS-RCNN)~\cite{huang2019mask}, based on a network block which learns the quality of the predicted instance masks. Unifying the tasks of semantic segmentation and instance segmentation, \cite{kirillov2019panoptic} proposed a joint scene understanding task, termed ``panoptic segmentation'', while also defining a novel Panoptic Quality (PQ) metric to evaluate performance on this task. Panoptic segmentation has become the focus of research in many applications, in particular autonomous driving, with a number of novel techniques developed only recently~\cite{kirillov2019panopticFPN, xiong2019upsnet, li2020fusing, hou2020real, cheng2020panoptic, wang2020axial}. It is likely that future 2D segmentation approaches will target several of the goals above in a joint manner. \subsubsection{Semantic Segmentation using Depth and Other Sensing Modalities} While visual segmentation using RGB imagery or video has been a significant focus of the research community, other sensing modalities can aid in segmentation, which in turn can then help the sensing pipeline. These other modalities are not just depth-related (in the case of commonly used LiDAR sensors on autonomous vehicles for example), but can include other sensors including infrared and multispectral cameras. Silberman \textit{et al}.~\cite{Silberman2012} proposed a method to parse ``messy'' indoor scenes into floors, walls, supporting surfaces, and object regions, while also recovering support relationships. They classified objects into ``structural classes'' based on their role: a) ground, b) permanent structures like walls and ceilings, c) large furniture, and d) props that are movable. For reasoning about support, they used physical constraints and statistical priors. Gupta \textit{et al}.~\cite{Gupta2015} designed a set of algorithmic tools for perceptual organization and recognition in indoor scenes from RGB-D data. Their system produced contour detection, hierarchical segmentation, grouping by amodal completion, object detection and semantic labeling of objects and scene surfaces. \cite{cadena2016rss} explored the use of a Multi-modal stacked Auto-Encoder (MAE)~\cite{ngiam2011multimodal} to jointly estimate per-pixel depth and semantic labels. The authors demonstrated that learning a shared latent representation aids in semantic scene understanding even when input data has imperfect or missing information. \cite{Valada2017} presented UpNet, a fusion architecture that can learn from RGB, Near-InfraRed, and depth data to perform semantic segmentation. They also introduced a first-of-its-kind multispectral segmentation benchmark of unstructured forest environments. \cite{chen2019learning} explored the use of easy-to-obtain synthetic data for semantic segmentation, particularly making use of geometry in the form of synthetic depth maps. They used geometric information to first adapt the input to the segmentation network via image translation, and then adapt the output of the network via \textit{simultaneous} depth and semantic label prediction. More recently, \cite{wong2020identifying} addressed the problem of open-set instance segmentation by projecting point clouds into a category-agnostic embedding space, where clustering is used to perform 3D segmentation independent of semantics. Semantic segmentation can also be used to improve the results of processing some of the sensing modalities. \cite{Bai2016} proposed semantically selecting dynamic object instances (and removing the background) from stereo pairs of images, in order to estimate optical flow for each instance individually. The estimated flow for the background and foreground could then be merged to obtain the final, improved result. \cite{Yang2018a} explored the use of semantics to improve per-pixel disparity estimation by simultaneously predicting per-pixel semantic labels and using intermediate CNN feature embeddings from the segmentation network. \cite{Dovesi2019} presented RTS2Net - a single, compact, and lightweight architecture for real-time ``semantic stereo matching'' (the term coined to refer to the combination of two tasks: depth estimation and semantic segmentation). The two tasks are accomplished by corresponding sub-networks, along with a disparity refinement network that uses the output from the predicted semantics. \cite{Wu2019} explored the use of \textit{pyramid} cost volumes, defined through multiple scales of feature maps, to better capture the disparity details in stereo matching, while also incorporating semantic segmentation to rectify disparity values along object boundaries. The latter task is achieved through the use of a single semantic cost volume (cost volumes are the set of correspondence costs per pixel used to infer the optimal disparity map). More recently, \cite{guizilini2020semantically} proposed a novel architecture that leverages a pre-trained semantic segmentation network to self-supervise monocular depth estimation via pixel-adaptive convolutions. \subsubsection{Jointly Learning Semantic Segmentation with Other Tasks} The semantic segmentation process closely relates to other tasks required for robots and autonomous vehicles like depth estimation, and researchers have investigated jointly learning it with these other tasks. \cite{neven2017fast} developed a real-time implementation of ENet~\cite{Paszke2016} to simultaneously address three autonomous driving related tasks: semantic segmentation, instance segmentation, and depth estimation. They proposed a shared encoder but with different decoder branches for the three tasks. \cite{Kokkinos2017} presented a multi-task CNN to jointly handle a large number of functional tasks: boundary detection, normal estimation, saliency estimation, semantic segmentation, human part segmentation, semantic boundary detection, region proposal generation and object detection. They demonstrated effective scaling up of diverse tasks with limited memory and incoherently annotated datasets. \cite{Nekrasov2019} explored joint learning of two tasks, depth estimation and semantic segmentation, using a single model with an uneven number of annotations per modality. The latter was achieved using hard knowledge distillation through a teacher network. Through computational efficiency-related modifications of an existing semantic segmentation network, they achieved real time operation. They demonstrated their system's utility through 3D reconstruction based on SemanticFusion~\cite{McCormac2017} for both indoor and outdoor data. \cite{Yang2019} proposed a CNN to predict polarization information (per-pixel polarization difference) along with semantic segmentation using monocular RGB data, as opposed to using a micro-grid array polarization camera or polarized stereo camera. The work was motivated by the challenges of specular scene semantics like water hazards, transparent glass, and metallic surfaces, where polarization imaging often complements RGB semantic segmentation. Finally, as an extension of the Stixel representation~\cite{Badino2009}, \cite{Schneider2016} combined both depth and semantics per pixel for compactly representing an environment, benchmarking pixel-wise semantic segmentation and depth estimation tasks. For robots carrying a suite of sensors, joint learning based on input from these different sensing modalities can be leveraged to address increasingly complex and challenging tasks. \subsection{Scene Representations} Semantic representation of an observed scene can be defined at various levels of detail and is typically motivated by the application scenario. While image classification produces a single semantic label for an image, object recognition and semantic segmentation provide labeling at region- and pixel- level respectively. However, a scene can be represented in distinct ways that may or may not explicitly take into account the pixel- or region-level semantics, but still have a high-level representation which is semantically meaningful. We explore these additional scene representation approaches in this section, including scene graphs and zero-shot learning of generalized semantic scene representations. The representation of a scene involves the extraction of visual information that can summarise the contents of the image captured from a particular scene~\cite{smeulders2000content}. For typical computer vision and robotics problems, imagery constitutes a broad domain where the variability is unlimited and unpredictable, even for images with the same semantic meaning~\cite{smeulders2000content}. Historically, the main goal of an effective image representation is the reduction of the semantic gap~\cite{santini1999user}, defined as the difference between the visual information extracted from an image and its high-level semantic interpretation. Traditional image representations transformed the original image pixels into features spaces of color, shape or texture, with the goal of amplifying particular characteristics of the image that are relevant for representing the semantic information of the scene, while at the same time suppressing irrelevant information. Such a goal can be partially achieved by promoting feature invariance properties that makes the representation robust to (generally) non-relevant distortions to the image, such as geometric transformation, illumination changes, and weather variations. One important trade-off encountered in doing so was between discrimination power and robustness to distortions. So much of the classical work on the design of feature representations was significantly influenced by the goal of finding an effective operating point that balanced discriminative and invariance properties. \textit{Color} invariance is typically achieved by transforming the original RGB (Red Green Blue) space into a more robust HSV (Hue Saturation Value) space (other similar spaces have also been proposed), where the hue channel is invariant to the illumination and camera direction with respect to an object's orientation~\cite{smeulders2000content}. The invariance to \textit{shape information} is commonly obtained by computing image derivatives using scale- and rotationally-invariant operators~\cite{freeman1990steerable}. \textit{Texture} invariance is generally obtained by representing an image in the frequency domain~\cite{smeulders2000content}. The classical representation of images involves the partitioning of the image into regions, and the computation of features from each region. Image partitioning can be done in a dense manner~\cite{smeulders2000content}, where the whole image is broken into regions of fixed~\cite{carneiro2007supervised} or variable~\cite{achanta2012slic} size, or in a sparse manner~\cite{lowe2004distinctive}, with the selection of salient image patches. Features (including color, shape and/or texture) are then extracted from the region and summarised into a fixed dimension representation using, for example, a particular spatial distribution~\cite{schmid1997local} or a histogram~\cite{swain1992indexing}. Images can then be represented by a collection of these features~\cite{smeulders2000content}. Some of the most prominent image representations in computer vision and robotics before deep learning representations largely replaced them~\cite{krizhevsky2012imagenet}, were based on Bag of Visual Words (BoVW)~\cite{sivic2003video}. In brief, these methods were based on the sparse image partitioning of the image, where each region is labeled as a particular visual word, with visual words being learned from a large collection of image regions. The image is then represented by a histogram of the visual words. For example in the place recognition domain (again, prior to the use of deep learning representation approaches), Williams \textit{et al.}~\cite{williams2009comparison} presented a comparison of different image representations, concluding that methods based on BoVW were generally superior. In the following subsections, we discuss two distinct ways of representing a scene: Scene Graphs and Generalized Semantic Representations, both of which are critical to semantic scene understanding for robotics. \subsubsection{Scene Graphs} Understanding a visual scene fully requires knowledge beyond just what is present in the scene. Much of the meaningful information can be extracted by examining the \textit{relationships} between objects and other components of the scene, which is one of the main motivations of the scene graph research area. Lin \textit{et al}.~\cite{Lin2013} developed a CRF-based method to address indoor scene understanding from RGB-D data. The method integrates information from 2D segmentation, 3D geometry, and contextual relations between scenes and objects to classify the volume cuboids extracted from the scene. With this formulation, scene classification and 3D object recognition tasks are coupled and can be jointly solved through probabilistic inference. Johnson \textit{et al}.~\cite{Johnson2015} proposed scene graphs that represent objects, attributes of objects, and the relationships between them in order to retrieve semantically related images. Their method used CRFs to ground the scene graphs to local regions in the images. As an extension of~\cite{Johnson2015}, Schuster \textit{et al}.~\cite{schuster2015generating} explored the scope of scene graphs created automatically from a natural language description of a scene, using rule-based and classifier-based parsing to improve image retrieval. Following the work by~\cite{Johnson2015}, Xu \textit{et al}.~\cite{Xu2017} developed a method to generate scene graphs by end-to-end learning, using an RNN and iterative message passing. The main focus on this work was on improving reasoning about spatial relationships based on surrounding contextual cues within an image. Li \textit{et al}.~\cite{Li2017} presented a Multi-level Scene Description Network (MSDN) that jointly learns to leverage mutual connections across three semantic levels of scene understanding: object detection, scene graph generation, and region captioning. Zellers \textit{et al}.~\cite{Zellers2018} explored a motifs-based scene parsing - looking for repeated patterns or regularly appearing substructures, in this case within graph representations of the scene. In particular, they proposed Stacked Motif Networks to capture higher order motifs in scene graphs, focusing on global contextual information to inform local predictors of objects and relations. Herzig \textit{et al}.~\cite{Herzig2018} developed a method that constrains the neural network architecture to be invariant to structurally identical inputs, based on the conditions of the Graph-Permutation Invariance (GPI). Johnson \textit{et al}.~\cite{Johnson2018} presented a method to generate images from complex sentences using scene graphs, that enables explicit reasoning about objects and their relationships. Their method uses graph convolutions to compute scene layout, that is then converted into an image using a cascaded refinement network trained adversarially against a pair of discriminators. More recently, Ashual and Wolf~\cite{ashual2019specifying} introduced a method that generated multiple diverse output images per scene graph using scene layout and appearance embedding information. Chen \textit{et al}.~\cite{chen2019scene} explored a semi-supervised method that automatically estimated probabilistic relationship labels for unlabeled images using a small number of labeled examples. The goal of this work was to address a recurring issue that affects much of the research in this field; that the models have been trained with small visual relationships sets, with each relationship having thousands of samples. Addressing the issue of scene graph generation dataset biases, Gu \textit{et al}.~\cite{gu2019scene} introduced a scene graph generation method that uses external knowledge and image reconstruction loss to reduce this bias. To further address these biases, zero-shot learning techniques have been proposed that aim to achieve a generalized scene representation, which are discussed in the next subsection. \subsubsection{Semantic Generalized Representations via Zero-Shot Learning} A common practical issue in robotics is that the system can only be exposed to a subset of the classes it is expected to encounter during actual deployment. Zero-shot Learning (ZSL) addresses this problem: defined as a learning problem, it focuses on the scenario where the training process has access to the visual and semantic representations of only a subset of the classes. This observed subset is labeled as the \textit{seen} classes; the challenge during deployment and testing involves the classification of \textit{unseen} visual classes that do not belong to the set of \textit{seen} classes~\cite{xian2018zero}. Zero-shot learning generally depends on the learning of a mapping from the visual to the semantic space using the \textit{seen} classes~\cite{lampert2013attribute,Palatucci2009,xian2018zero,Zhang2015}, where the hope is that this learnt mapping can be reliably used to classify the \textit{unseen} classes. \cite{Chen2018} proposed SP-AEN for zero shot learning to tackle the semantic loss problem in ZSL. Acknowledging that \textit{classification} and \textit{reconstruction} are contradictory objectives, an independent visual-to-semantic embedding was introduced for both the tasks. Both these semantic embeddings were used for adversarial learning, and to transfer information between the two tasks. An alternative to mapping from the visual to the semantic space is to assume the availability of the semantic representations of the unseen classes during training. This assumption allows the implementation of a conditional generative model that is trained to generate visual representations from their semantic representations using the seen classes. Once the generator is stable, it is then possible to generate unseen visual representations which can be used to directly train a visual classifier with real \textit{seen} visual representations and generated \textit{unseen} visual representations~\cite{kumar2018generalized}. This method can work better than others for the problem of \textit{Generalised} Zero-Shot Learning (GZSL), where the testing process involves the classification of seen and unseen classes. GZSL is more challenging than vanilla ZSL because the classifier tends to be severely biased towards the classification of seen classes. Much of the current research in the field is therefore focused on achieving a balance between the classification of seen and unseen classes. The general theme of this research is to combine the semantic and visual representations, with modulation of the classification of seen and unseen classes based on the input test visual sample. For example, Felix \textit{et al}.~\cite{felix2018multi} proposed a cycle consistency loss to generate visual representations from semantic ones, and then in reverse generate the semantic representation. The modulation of seen and unseen classes has also been addressed by Atzmon and Chechik~\cite{atzmon2019adaptive}. One can also learn a joint semantic and visual space that mitigates the need for learning a mapping between these two spaces~\cite{Felix2019}. The classifier is learnt in conjunction with a domain classifier to differentiate between seen and unseen domains. Niu \textit{et al}.~\cite{Niu2019} proposed to reduce the \textit{projection domain shift}, defined as the lack of generalization of visual-semantic mapping based on seen categories to unseen categories. Their approach involved learning an adaptive mapping for each unseen category, followed by progressive label refinement using unlabeled test instances. More recently, \cite{vyas2020leveraging} proposed LsrGAN, which explicitly transfers the knowledge of semantic relationships between seen and unseen classes by generating corresponding mirrored visual features. The overarching goal of object detection, semantic segmentation and scene representation is to enable effective scene understanding. It can be commonly observed in all these fundamental areas of research that the use of additional sources of information in the form of sensor data, knowledge repositories and textual descriptions can significantly enhance the task performance. This is highly relevant to robotics, as a robot typically carries multiple sensors, can \textit{actively} explore its environment and has access to additional resources from the ``cloud'' online or on a local network. These tasks also have high functional overlap with those required of robots in many applications. In the following sections, we discuss how semantic understanding approaches like those discussed so far can be used in robotics, and the associated further research advances required to do so. \subsection{Semantics for Localization and Place Recognition} A major sub-component of the navigation problem is localization - assuming a map exists, how can a robot calculate its location within the map. This process occurs in a number of different ways and has differing, overlapping terminology. Localization often refers to calculating the robot's location in some form of metric map space, while place recognition often refers to recognizing a particular sensory snapshot or encoding of a distinct location, without necessarily any use of or calculation of metric pose information. In a SLAM system performing mapping, the act of recognizing a familiar location is called ``closing the loop'' or ``loop closure''. Depending on the sensory modality used, the terminology is often pre-fixed with the appropriate term - for example \textit{visual} place recognition. In this section we survey the increasing use of semantics for localization and place recognition systems, with a focus on vision-based techniques given their natural affinity for semantics-based approaches. Visual Place Recognition (VPR) is integral to vision-based mobile robot localization. Given a reference map of the environment comprised of unique ``places'', the task is to recognize the currently observed place (query) and decide whether or not the robot has seen this before. VPR is a widely researched topic in robotics, as reviewed in a recent survey~\cite{Lowry2016}. Distinct from place \textit{classification} or \textit{categorization}, processes that produce place-level semantic labels representing the \textit{general} appearance of the scene, here we discuss place \textit{recognition} that produces a localization cue by identifying a \textit{specific} place. In particular, we review the VPR methods that use semantic information at either scene, object, patch, edge or pixel level for effective localization. \subsubsection{Object-level Semantics for VPR} Semantic information in the form of object detection is often used for place recognition and localization, as well as in full SLAM systems (see Subsection~\ref{sec:semRep+SU+SLAM}). \cite{kim2009simultaneous} developed a hierarchical graphical model that enabled simultaneous object and place recognition using bidirectional interaction between objects and places. Similarly, \cite{Luo2011} presented a hierarchical random field model based on SIFT~\cite{lowe2004distinctive} and GIST~\cite{oliva2006building} using relative pose context among point features, objects and places. \cite{Atanasov2016} explored the use of a semantically-labeled prior map of landmarks based on object recognition~\cite{felzenszwalb2009object} for localizing a robot. They developed a sensor model to encode semantic observations with a unified treatment of missed detections, false alarms and data association, and demonstrated it functioning on simulated and real-world indoor and outdoor data. \cite{weng2018semantic} proposed ``semantic signatures'' as descriptors of images comprising \textit{type} and \textit{angle} sequences of objects visible from a given spatial location. They used trees, street lights and bus stops as objects for this task. With further advances in the field of object recognition, methods like Faster-RCNN~\cite{ren2015faster} have been adopted for visual localization. Recently, \cite{zhang2019coarse} developed a hierarchical localization pipeline based on a semantic database of objects detected using \cite{ren2015faster} and SURF~\cite{bay2006surf} descriptors. In particular, the coarse localization estimates based on object matching were refined using keypoint-level SURF matching to obtain the final result. \cite{han2018learning} presented a novel place representation based on a graph where nodes were formed by holistic image descriptors and semantic landmarks derived from \cite{ren2015faster}; the edges in the graph indicated whether or not the nodes represented the same landmark/place; finally, the learnt graphical embeddings were used for visual localization. Another source of semantic information in urban environments is Geographical Information System (GIS) databases, which provide semantic and pose information for various objects like traffic signs, traffic signals, street lights, bus stops and fire hydrants. \cite{ardeshir2014gis} extracted and combined GIS data with object semantics to improve both object detection (bounding box) and geospatial localization. They tackled the inherent noise within GIS information by formulating a higher-order graph matching problem, solved robustly using RANSAC. Coarse localization is enabled by searching over a dense grid of locations for high similarity between GIS objects and objects detected within the query image. Similar to~\cite{ardeshir2014gis}, \cite{castaldo2015semantic} explored the use of Deformable Part Models (DPM)~\cite{felzenszwalb2009object} along with GIS information for localization but based on ``cross-view'' matching, where a query image from street-level is matched against an aerial top-view GIS semantic map. They proposed a Semantic Segment Layout (SSL) descriptor to validate the spatial layout of semantic segments detected in a query image in accordance with the GIS map. In order to localize precisely, certain semantic categories in the scene can be more useful than the others depending on the underlying application scenario. \cite{pink2008visual} presented a lane markings-based localization system, where a prior map is derived from aerial images and map matching is performed using ICP. Aimed at assisted and autonomous driving, \cite{schreiber2013laneloc} explored the use of highly accurate maps comprising visible lane markings and curbs for precise and robust localization. They employed a Kalman Filter~\cite{kalman1960new} for map matching using stereo cameras and an IMU to achieve centimeter-level precision. \cite{armagan2017learning} proposed using segment building facades to estimate camera pose, given a 2.5D map of the environment comprising building outlines and their heights. \cite{mousavian2016semantic} developed an approach for geo-locating a novel view of a scene and determining camera orientation using a 2D map of buildings along with a sparse set of geo-tagged reference views. They detected and identified building facades, along with their geometric layout, in order to localize a query image. \subsubsection{Beyond Object-Level Semantics} Semantic segmentation of visual information can not only be leveraged at object or pixel level, but at edge level as well. \cite{meguro2007development} and \cite{bazin2009dynamic} segmented the sky using Infrared images to use it as a unique signature for localization. The ultraviolet spectrum has also been explored for the task of sky segmentation based navigation~\cite{stone2014sky} and tilt-invariant place recognition~\cite{stone2016skyline}. \cite{ramalingam2010skyline2gps} explored an automatic skyline segmentation approach for an upward-facing omnidirectional color camera. These omni-skylines were observed to be unique for a specific location in a city, particularly in GPS-challenged urban canyons. \cite{saurer2016image} developed a skyline extraction and representation method for localizing in mountainous terrains. \cite{pepperell2016routed} proposed a ``sky blackening'' method to remove the sky region from images in order to improve place recognition performance across day and night cycles. Beyond sky-based representations, variations in weather conditions can also be used to localize a static camera, by analyzing the temporal variations in the appearance of the viewed scene~\cite{jacobs2007geolocating}. Recently, \cite{Yu2018} presented an image descriptor based on the VLAD aggregation~\cite{jegou2011aggregating} of semantic edge features~\cite{yu2017casenet} defined between distinct semantic categories like building-sky and road-sidewalk. \cite{singh2016semantically} developed an image descriptor based on histograms of semantically-labeled ``superpixels''~\cite{ren2003learning, gould2009decomposing} within an image grid, and demonstrated its utility for geo-localization, semantic concept discovery, and road intersection recognition. \subsubsection{Life-long Operation of VPR Systems} Appearance variability of places can occur at vastly different time scales. At one extreme, time of day, weather fluctuations and even momentary lighting changes contribute towards intra-day appearance changes. Longer-term factors such as seasons, vegetation growth, and climate change also lead to appearance variability. A significant additional contributor to appearance variations are human activities, such as construction work, general wear and tear, updating of signage/billboards/fa\c{c}ades including increased digital signage, and abrupt changes to traffic flow. Compared to natural causes of appearance variability, the changes caused by human activities can be far less ``cyclical'' or predictable. The fact that the appearance of places can change indefinitely and unpredictably imposes a requirement that localization and VPR systems remain accurate and robust under those continuous changes, throughout the lifetime of the system. Compared to the majority of research in VPR that has so far considered static datasets (though with significant appearance variations within the datasets), lifelong VPR is an under-investigated area. To handle continuous appearance changes, some approaches attempt to extract the ``semantic essence'' of a place that is independent of appearance, and to transfer the appearance of the place seen in a particular condition to unseen conditions~\cite{latif2018addressing,porav2018adversarial,anoosheh2019night}. To date, such methods have primarily been demonstrated on \textit{natural} variations such as time of day and seasons. Another paradigm continuously accumulates data to refine the system~\cite{churchill2013experience,doan2019scalable,dymczyk2015gist}. The practicality of such approaches depend on the ability to continuously collect data from the target environment at high frequency (e.g. weekly), which can be achieved using deliberate recording schemes (e.g. mapping vehicles~\cite{anguelov2010google}, taxi fleets~\cite{geyer2020a2d2, kesten2019lyft}) or opportunistic and crowd-sourced schemes such as user-uploaded videos~\cite{warburg2020mapillary} or webcams~\cite{jacobs2009global}. The fundamental challenge arises from the perpetually growing database, which demands a VPR algorithm that is scalable; the computational effort for inference and continuous refinement of the VPR system must grow slowly or not at all with the database size. \subsection{Semantics to Deal with Challenging Environmental Conditions} \subsubsection{Addressing Extreme Variations in Appearance and Viewpoint} Semantic cues have been demonstrated to be of high utility for place recognition under challenging scenarios where appearance- and geometry-only features alone fall short, for example, dealing with extreme appearance variations across repeated traverses of the environment~\cite{garg2019robust}. These non-uniform appearance variations are often caused by weather, time of day and season cycles. \cite{toft2017long} presented an appearance-invariant localization system based on a 3D model of semantically-labeled points and curves, which were projected onto a single query image to minimize error for pose estimation. \cite{Garg17IrosImproving} proposed a temporal place segmentation approach based on semantic place categories~\cite{zhou2014learning} to improve VPR~\cite{milford2012seqslam} under significant appearance variations occurring both within and across the traverses. \cite{naseer2017semantics} developed a method to learn salient image descriptions based on regions of the image which are geometrically stable over large time gaps (across seasons and weather changes). They combined this representation with an off-the-shelf holistic representation to obtain a robust descriptor. Cross-view matching, typically referring to the problem of matching images across highly-varied viewpoints like aerial top-view versus ground front-view~\cite{lin2013cross, castaldo2015semantic, Gawel2018}, is a challenging task due to extreme variations in visual appearance and geometry between the matching pair, often requiring additional information to enable effective localization. \cite{lin2013cross} explored a cross-view geo-localization approach that used SVMs to learn relationships among image triplets: ground level image, its corresponding aerial image and a land cover attribute map. More recently, \cite{Gawel2018} presented a localization system for cross-view matching where aerial images were captured using UAVs. They developed a semantic blobs-based hybrid representation derived from pixel-wise semantic segmentation, and combined topological, metric, and semantic information for wide-baseline image matching, i.e., forward vs reverse and aerial vs ground. In order to deal with \textit{simultaneous} extreme variations in scene appearance (day-night) and camera viewpoint (forward-reverse), \cite{garg2018lost} proposed Local Semantic Tensor (LoST) as a global image descriptor based on pixel-wise semantic labels and spatial aggregation of local descriptors derived from a CNN. They extracted keypoints from maximally-activated locations within the CNN feature maps, and performed semantic keypoint filtering and weighted local descriptor matching to re-rank the place matches for high-precision place recognition. \cite{garg19Semantic} extended this approach with a concatenated descriptor that encoded semantics both explicitly and implicitly, in the form of selective semantic feature aggregation and a deep-learnt VLAD descriptor~\cite{arandjelovic2016netvlad}, respectively. \subsubsection{Linking Place Categorization with Place Recognition} Bridging the gap between semantic place categorization and the place recognition problem, \cite{wang2018visual} proposed a 3-layer perception framework using a topological directed graph as a map of the environment. Each node represented a set of semantic regions, and each edge represented a set of rotation-recognition regions. This structural representation enabled the recovery of the optimal path for indoor semantic navigation based on the number of semantic regions encountered. \cite{Martinez-Gomez2016} developed a framework for semantic localization that used 3D global descriptors based on a Bag of Visual Words (BoVW) approach~\cite{sivic2003video} to train a classifier for categorizing rooms labeled as unique places. \subsubsection{Semantics within High-Level Representations} In this subsection, we discuss the use of image representations that capture shapes and patterns at a higher abstraction level, which may not be \textit{strictly} semantically meaningful to humans. To some extent, this can be attributed to feature extraction from higher-order layers of CNNs and methods like \textit{Edge Boxes}~\cite{zitnick2014edge} that provide a ``semantically-aware'' representation of whole images or image regions. \cite{sunderhauf2015place} explored the use of Edge Boxes to detect and represent ``ConvNet Landmarks'' for visual place recognition. \cite{cascianelli2016robust} represented the environment using a co-visibility graph of semantic image patches~\cite{zitnick2014edge}, where an edge was established only if patches were observed in the same image, unlike the common notation of edges as spatial relationships. \cite{seymour2018semantically} presented Semantically-Aware Attentive Neural Embeddings (SAANE) that fused appearance features and higher-order layers of the CNN to learn embeddings for matching places under a wide variety of environmental conditions. \cite{sunderhauf2015performance} demonstrated that the higher-order layers of CNNs encoded semantic information about a place, which can be utilized for partitioning the descriptor search space. \cite{garg2018don} showed that the fully-connected layers of a place categorization CNN, being semantics-aware, exhibited viewpoint-invariance and hence enabled place matching from opposing viewpoints, even with the additional challenge of significant appearance variations. The use of additional modalities like pixel-wise depth for visual place recognition has also been explored in the past~\cite{fiolka2013distinctive, cupec2015place, cieslewski2016point, garg2019look, maffra2019real, vankadari2020unsupervised, taubner2020lcd}, where meaningful representations in the form of surfaces~\cite{fiolka2013distinctive}, planes~\cite{torii201524}, and lines~\cite{cupec2015place, taubner2020lcd} have been shown to improve VPR performance. \cite{Larsson2019} proposed FGSN (Fine-grained Segmentation Networks) based on k-means clustering of CNN embeddings for self-supervised pixel labeling and 2D-2D point correspondence. They showed that fine-grained clustering, even though non-semantic, is more suitable for visual localization than methods based on a limited number of semantic classes, for example, the 19 in Cityscapes~\cite{Cordts2016} and 66 in the Vistas~\cite{neuhold2017mapillary} dataset. However, it was also observed that pre-training on semantic segmentation networks improved performance significantly, suggesting semantics would still play a key, albeit different, role. \subsection{Enabling Semantics for Robotics: Additional Considerations} Methods developed primarily in other research fields like computer vision often do not readily translate to robotic systems~\cite{sunderhauf2018limits}. Many critical issues for successful robotics deployment are not addressed or not prioritized in many of the research fields from which robotics draws much of its inspiration. Robotic deployment has a range of additional constraints and opportunities compared to much dataset-based research, including the availability of multiple sensing modalities, limited computational resources, a focus on real-time and on-line deployment, and a range of problems including obscuration, clutter and uncertainty that are not adequately encountered in dataset-based research. Hence, further innovation is typically required to bridge the gap between a laboratory or dataset-demonstrated system and a deployable solution for robots ``in the wild''. In this subsection, we cover some of the relevant research bridging this divide that has not already been covered in previous sections. \subsubsection{Efficiency} In order to classify 3D objects in real-time, Maturana and Scherer~\cite{maturana2015voxnet} developed a simplified version of a 3D CNN~\cite{maturana20153d} for real-time object recognition. \cite{zeng2018rt3d} proposed \textit{RT3D}: a real-time 3D vehicle detection method based on pre-ROI-pooling convolutions~\cite{dai2016r} that accelerate the classification stage, thus completing detection in real-time with detection accuracy comparable to state-of-the-art. More recently, \cite{hou2020real} demonstrated real-time panoptic segmentation using a single-shot network based on a parameter-free mask construction operation that reuses dense object predictions via a global self-attention mechanism. \subsubsection{Noise, Occlusions and Clutter} In order to deal with noise, occlusion and clutter in robotic sensing and point-based representation, \cite{bobkov2018noise} designed 4D CNNs for object classification that process robust point-pair based shape descriptors~\cite{wahl2003surflet, rusu2009fast, drost2010model, wohlkinger2011ensemble, birdal2015point} represented as 4D histograms. Occlusions also pose a challenge for object-based representation of the environment and is an active area of research in the context of object-based SLAM~\cite{tan2013robust, mu2016slam, gaudilliere2020perspective, feldmantowards, ok2019robust, liao2020rgb}. Moreover, occluded objects affect the evaluation of object detection systems~\cite{hoiem2012diagnosing} and require novel error measures to deal with partially-visible objects~\cite{Nicholson2019}. To deal with background clutter, Wang \textit{et al}.~\cite{wang2012could} proposed first removing the background, posing it as a binary classification task, before segmenting the point cloud data into semantic classes of interest for autonomous driving like cars, pedestrians and cyclists. \subsubsection{Cost} As a cost-effective alternative to a LiDAR-based 3D point cloud, Pseudo-LiDAR~\cite{wang2019pseudo} has been proposed to represent pixel depth estimated using stereo cameras as a 3D point cloud, leading to a significant performance improvement for 3D object detection. In a subsequent work, the authors presented Pseudo-LiDAR++~\cite{you2019pseudo} to improve depth estimation of faraway objects while also incorporating a depth signal from cheaper LiDAR sensors that typically have sparse 3D coverage. \cite{vianney2019refinedmpl} extended the concept of Pseudo-LiDAR to monocular systems, while also addressing the numerical and computational bottleneck of the dense Pseudo-LiDAR point cloud. Recently, Qian \textit{et al}.~\cite{qian2020end} developed an end-to-end Pseudo-LiDAR framework based on differentiable Change of Representation (CoR) modules to further improve detection accuracy. \subsubsection{Uncertainty Estimation} Uncertainty estimation is essential for semantic understanding and decision making during mapping and interaction. Current approaches for uncertainty estimation include approximations of Bayesian deep learning~\cite{mackay1992practical} such as dropout sampling~\cite{gal2016dropout}, deep ensemble methods~\cite{lakshminarayanan2017simple} and the recently proposed Stochastic Weight Averaging-Gaussian (SWAG)~\cite{maddox2019simple}. For object detection, Monte Carlo Dropout Sampling was used in~\cite{miller2018dropout} to measure label uncertainty. Other works proposed estimating the uncertainty in detecting the location of the object in the image, introducing the probabilistic bounding box~\cite{hall2020probabilistic}. In~\cite{ wang2020inferring}, an alternative representation of probabilistic bounding boxes was introduced through the spatial distribution of a generative bounding box model. In~\cite{harakeh2020bayesod}, probabilistic bounding boxes were generated by replacing the standard non-maximum suppression (NMS) step in the object detector by a Bayesian inference step, allowing the detector to retain all predicted information for both the bounding box and the category of a detected object instance. Dropout sampling for semantic segmentation can be slow for robotics applications, prompting ~\cite{huang2018efficient} to propose a Region-based Temporal Aggregation (RTA) method which leverages temporal information using a sequence of frames. Other works expressed uncertainty as a measure of quality in the predictions, such as predicting the quality of the IoU for semantic segmentation~\cite{rottmann2019uncertainty} or per-frame mAP (mean average precision) in the case of object detection~\cite{rahman2020performance}. Recently, \cite{blum2019fishyscapes} showcased that unseen object categories can be mislabeled by state-of-the-art semantic segmentation networks with high certainty. To mitigate this the authors presented the Fishyscapes dataset, for pixel-wise uncertainty estimation for autonomous driving to enable detection of such anomalous objects. \subsubsection{Multi-modal and Non-Vision Based Approaches} Given that robots typically carry a suite of sensors, effective integration of information from multiple modalities is also an active area of research. Towards this goal, \cite{Pronobis2010} developed a multi-modal semantic space labeling system leveraging information from camera, laser scanner, and wheel odometry sensors. This work was further extended in~\cite{Pronobis2011} to incorporate high-level information as ``properties'' of a place, defined in terms of shape, size, appearance, and doorway (binary). While using multiple modalities, authors in \cite{Mozos2012} concluded that although combining features from depth and color drastically reduce uncertainty, depth information contributes more to the performance due to inherent illumination-invariance. For synchronized multiple modalities, \cite{Jung2016} proposed a Local N-ary Patterns (LNP) descriptor to describe relationships among neighboring pixels of reflectance and depth images, as an extension of the Local Binary Pattern descriptor~\cite{Ojala2000}. As a general framework for semantic place categorization using any sensor modality, \cite{Premebida2015} demonstrated the superiority of DBMM (Dynamic Bayesian Mixture Models) based temporal inference over a commonly used SVM approach. With the success of deep learning based methods, amenable to early, intermediate and late fusion techniques, use of multiple modalities has now become much more accessible~\cite{ramachandram2017deep}, including in semantic-based approaches. The complementary properties of the modalities can be harnessed via multi-modal fusion. Recently, Feng \textit{et al}.~\cite{feng2020deep} reviewed the state-of-the-art deep learning based approaches for object detection and semantic segmentation that employ multi-modal fusion, particularly exploring the answers to the ``\textit{what}, \textit{when} and \textit{how} to fuse'' questions. Chen \textit{et al}.~\cite{chen20153d} proposed a 3D object proposal method using stereo cameras, posing it as an energy minimization problem exploiting object size priors and depth-informed features like height above the ground plane, free space and point cloud density. In subsequent work~\cite{chen2017multi}, the authors presented the \textit{MV3D} (Multi-View 3D) object detection network, which combines RGB images and a LiDAR's front and Bird's-Eye Views (BEV) to enable effective multi-modal fusion based on interactions between different layers of the network. A similar multi-modal fusion is proposed in~\cite{ku2018joint}, dubbed \textit{AVOD} (Aggregate View Object Detection), with a novel use of high-resolution feature maps, $1\times1$ convolutions and a look-up table for 3D anchor projections, achieving real-time and memory-efficient high detection performance. Vora \textit{et al}.~\cite{vora2019pointpainting} presented \textit{PointPainting} as a way to ``decorate'' the LiDAR point cloud with the semantic segmentation output of color images for improved 3D object detection, addressing the limitations of previous fusion concepts that led to ``feature blurring''~\cite{liang2018deep, wang2018fusing} and limited maximum recall~\cite{qi2018frustum, yang2018ipod, wang2019frustum}. A subset of research in place categorization semantically categorizes places using sensors other than those used for visual perception. With the increasing focus on Internet of Things and the ubiquity of edge-based sensors, upcoming solutions for semantic place categorization might be able to leverage these additional sources of information and existing approaches to effectively use multi-stream data. \cite{Krumm2013} proposed place classification of geographical locations based on individual demographics, timing of visits, and nearby businesses using government diary data. The demographic and temporal features of individual visits included age, gender, arrival and departure details and season. The place categories included home, work, restaurant, library, place of worship and recreation. \cite{Krumm2015} extended this work by also considering additional cues like sequential information in the form of the periodicity of the individual visits, cross labels extracted from multiple visits to the same place, travel distance, and place co-occurrences. \cite{Lv2016} presented a semantic place classification system using GPS trajectories of users. Their method is based on visit-level features including day of week, time of day, duration, and response rate, which were then used to infer place-level features. \cite{Roor2017} developed a semantic place labeling system based on multiple sensor sources including Bluetooth, smartphone, GPS, motion activity, WLAN and time, where place categories included home, work, friend and family, nightlife and education. Depending on the application type, the use of semantics can vary significantly. For example, \cite{Weiss2010} proposed a particle filter-based semantic state estimation system for semantic mapping and navigation of agricultural robots. Here, the ``semantic states'' (classes) were defined according to the topology of crop rows, considering the ``side'', ``start'', ``end'', and ``gap'' as the semantic elements of the agricultural field. \subsection{A Brief History of Maps and Representations} A practical SLAM system typically employs a combination of interoceptive sensors (e.g., rotary encoders, accelerometers, inertial measurement devices) and exteroceptive sensors (e.g., LiDAR, sonar, radar, cameras). The mapping functionality in SLAM derives largely from the capability of the exteroceptive sensors to \textit{measure} (directly or indirectly) structural or visual elements in the scene. While LiDAR and sonar were dominant sensing modalities in the early days of SLAM~\cite{durrant2006simultaneous, bailey2006simultaneous,thrun2002probabilistic}, the use of cameras (e.g., standard RGB cameras, depth cameras, and event cameras) as the primary sensors for SLAM (thus leading to visual SLAM) is currently a major area of interest in robotics and computer vision. A key reason behind the popularity of visual SLAM is the flexibility and relatively low cost of optical sensing devices (e.g. consumer RGB and depth cameras). Moreover, compared to other exteroceptive sensors, cameras provide a richer source of information and thus the prospect of extracting higher-level understanding (e.g. semantics) of the scene. \subsubsection{Classical 3D Maps} Classical visual SLAM methods have largely focused on extracting the geometric 3D structure of the environment. Feature-based methods~\cite{davison03,davison07,klein2009parallel,mei09,strasdat12,mur-atal15} (both monocular and stereo) construct maps in the form of sparse 3D point clouds, where the 3D points are typically reconstructions of the salient local features detected in the images. To facilitate the generation of 2D-3D correspondences, descriptors of the local features associated with the reconstructed 3D points are also often embedded in the map. In contrast to feature-based methods, direct methods~\cite{newcombe2011dtam,engel13,forster14,Engel-et-al-pami2018} utilize a photometric error formulation to estimate structure and motion. Maps produced by direct SLAM methods are typically semi-dense or dense 3D point clouds, where each reconstructed 3D point is associated with corresponding pixels (that are not necessarily locally salient) observed across multiple frames in the input sequence. For visualisation, the point clouds are often texture-mapped with pixel RGB values. In contrast to conventional cameras, depth cameras~\cite{geng11} such as the Microsoft Kinect are able to directly acquire depth information at frame rate (such cameras are often called RGB-D cameras since they also record in the RGB channels, in addition to depth). Accordingly, RGB-D SLAM algorithms~\cite{HenryKHRF10,newcombe11kinectfusion,EndresHESCB12,KahlerPRSTM15,InfiniTAM_ECCV_2016} are able to construct dense volumetric 3D maps of the environment. Since depth cameras can acquire metrically consistent depths, the 3D maps generated via RGB-D SLAM algorithms do not suffer from the global scale ambiguity problem which affects monocular visual SLAM systems. Classical visual SLAM methods (as outlined above) have reached a level of maturity where accurate 3D maps (sparse or dense point clouds) and localisation of the observer within the map can be efficiently computed (though some require hardware accelerators such as GPUs). However, most practical robotics applications require more than just 3D maps; semantic SLAM is a cogent and timely extension to classical visual SLAM. \subsubsection{Topological Maps} Topological maps represent an environment as an abstract graph~\cite{brooks1985visual}, where nodes represent distinct places a robot has visited and edges between the nodes represent topological relations like proximity and order~\cite{kortenkamp1994topological}. One of the limitations of classic metric maps had been the accumulation of error (drift) in global coordinates, despite the use of multiple sensors, beacons and elaborate error-tracking systems~\cite{giralt1983integrated}. Topological maps do not suffer as directly from the accumulation of movement errors, as the robot has only to navigate locally between adjacent place nodes, although drift is still an issue for loop closure. Furthermore, topological maps are highly scalable when compared to classical metric maps that use detailed a priori models of the world~\cite{kosaka1992fast, fennema1990experiments}. Topological SLAM systems have been widely explored in the past where the use of multi-sensory approaches~\cite{choset2001topological} has gradually been replaced with visual similarity-based metric error correction via loop closures~\cite{levin2004visual, newman2005slam, se2005vision}. One of the key enablers for relatively modern topological mapping systems has been the development of Bag-of-Visual-Words (BoVW)~\cite{sivic2003video} like methods, leading to robust large scale appearance-based topological SLAM systems like FAB-MAP~\cite{cummins2008fab}. Existing surveys on topological maps~\cite{garcia2015vision} and visual place recognition~\cite{Lowry2016} provide further details about developments in this field in recent years. \subsubsection{Hybrid Approaches} Hybrid map representations have been demonstrated to achieve an ideal balance between classic metric maps and topological maps~\cite{kuipers1991robot}, where a map is represented as a hierarchy. In such representations, metric information from the local geometry of the scene is incrementally fused into a global ``topometric" map, which is defined at a large scale using topological relations between distinct places (the hierarchy is almost always globally topological and locally metric rather than the reverse). Thrun~\cite{thrun1998learning} proposed an integration of grid-based and topological maps, where the latter partitions the former into coherent regions. Simhon and Dudek~\cite{simhon1998global} explored a hybrid map representation where local metrically accurate maps, dubbed ``islands of reliability'', form nodes of a topological model of the world, thus avoiding the need to perform large-scale error integration. The \textit{Atlas} framework developed by \cite{bosse2003atlas} comprised an interconnected set of local coordinate ``frames''. Each frame is a local metric map of the environment, connected to other frames via transformations represented as edges in the global graph of coordinate frames. \cite{tomatis2003hybrid} proposed a hybrid map representation, based on extracting ``corners'' and ``openings'' that represented topology, and ``lines'' that represented local geometric structure using a $360^{\circ}$ laser scanner. \cite{mei2010closing} explored a landmark-based co-visibility graph representation of the environment, where co-visibility corresponds to the connectivity of a topological map and inter-frame motion is used to encode metric transforms between landmarks. More recently, hybrid maps have been explored beyond the bounds of two-layer hierarchies, and have started to introduce semantic concepts. \cite{Pronobis2012} developed a probabilistic framework based on chain graphs to create a hierarchical hybrid map comprising four layers: sensory (accurate metric map), place (places and paths information), categorical (geometry and appearance of objects and landmarks), and conceptual (instances of spatial concepts relating a cereal box with kitchen). The proposed system used laser and camera sensors in indoor environments and attempted to relate conceptual knowledge with object and place semantics. \cite{Riazuelo2015} presented a cloud service-based semantic mapping system comprising an ontology to code concepts/relations in maps and objects (CAD models), built on top of an RGB-D metric map using both keyframe-based and 3D occupancy grid-based map representations. The proposed system enabled semantic mapping of novel environments and searching for novel objects within a semantic map. In \cite{Kochanov2016}, authors used stereo frames to obtain depth, scene flow, visual odometry and semantic segmentation, all of which formed the input for semantic mapping based on 3D occupancy. This enabled reasoning on objects, and led to object instance discovery based on temporally consistent shape, appearance, motion, and semantic cues in the map, while also being able to handle dynamic objects. More recently, \cite{yue2020hierarchical} presented a hierarchical framework for probabilistic semantic mapping using multiple cooperative robots in a distributed setting. Although hybrid maps, particularly those involving a semantic layer, are more amenable to human-robot interaction, they are still in a phase where certain implementation choices might limit their universal applicability. It's still unknown whether, given the complexity of robotic tasks and applications, a generalized solution is viable, or whether specialized solutions will be required for each class of applications. \subsection{Places and Objects for Semantic Mapping} Semantic mapping has been explored both in the context of place-level and object-level representation of the environment, where a more detailed semantic representation typically combines place and object labels in a hierarchical manner to create a hybrid map, as also discussed in the previous subsection. In this subsection, we first cover the use of scene classification and place categorization, where researchers have focused on abstracting the changing appearance of the scene into meaningful place labels as the robot explores an environment. We then discuss one of the clearest opportunities to enrich robot mapping systems with the use of \textit{objects}. Since objects can be categorized and are meaningful by themselves, all this information can be used in a variety of ways by semantic mapping and localization approaches. In our discussion below, we further split the objects-based approaches into two categories: those that use prior knowledge of the expected objects, often including 3D models, and those that have limited or no knowledge available beforehand, instead learning how to use objects at deployment time. \subsubsection{Scene Classification and Place Categorization} Semantic maps of an environment can be constructed by categorizing places with semantic labels which are typically pre-defined. Such semantic categories for different places can be defined by only considering the functionality of that place, for example, ``kitchen'', ``printer area'', and ``seminar room''~\cite{Rottmann2005}. Alternatively, a more general hierarchical framework approach can also consider the structural properties, for example, having a broad classification based on ``room'' and ``corridor'' be followed by specialization labels of rooms like \textit{office} and \textit{classroom}~\cite{Luperto2016}. ~\cite{Rottmann2005} combined vision and range information to extract objects (e.g. monitor and coffee machine) and geometric features, respectively, which were fed to AdaBoost~\cite{freund1995desicion} to classify places and perform efficient global localization. ~\cite{Stachniss2006} used semantics as ``background knowledge'' to explicitly represent environments with corridors and other indoor structures. Such a semantic distinction led to efficient multi-robot exploration of an environment, through learning of a behaviour which rewarded robots to preference exploring corridors, which led to unexplored branches of connecting rooms. \cite{Goeddel2016} developed a CNN-based place classification system trained using black and white images of occupancy grid maps (black uncarved space vs white carved free space) obtained through 2D laser scan data. The semantic classes used for the task included corridor, doorway, and room. \cite{Sunderhauf2016} presented a CNN-based semantic mapping system that overcame the closed-set limitations of supervised classification by complementing the system with one-vs-all classifiers, in order to recognize new semantic classes online. The proposed system used Bayesian filtering to incorporate prior knowledge and ensure temporal coherence. Furthermore, they also demonstrated the effective use of semantics for improving object recognition and modulating a robot's behavior during navigation tasks. \cite{Liao2016} presented a scene classification CNN that incorporates object-level information by regularization of semantic segmentation, demonstrated on indoor RGB-D data. \cite{Premebida2017} proposed a Dynamic Bayesian Mixture Model (DBMM) -- a mixture of heterogeneous base classifiers -- that incorporates time-based inferences from previous class-conditional probabilities and priors. Their system used 2D laser scans and indoor data for experiments, and extended their prior work~\cite{Premebida2015}. \cite{Mancini2017} explored the use of fully-convolutional CNN for learning better feature representations for the task of semantic place categorization. This system used a Naive Bayes Nearest Neighbor (NBNN) method within the learning framework for end-to-end training. \cite{Mancini2018} developed a novel method for domain generalization for place classification to deal with the unknown/unseen deployment scenarios, when the test data might not be similar to the data used for training. In this case, domain generalization was achieved by automatically computing a model for the unknown domain through combining models of the known domains. \cite{Zheng2018} presented \textit{TopoNets} for semantic mapping based on the topological structure of the environment, using a Sum-Product Network (SPN) as the backbone for learning and inference. The proposed system was demonstrated on various tasks: place classification, inferring semantics of unexplored space, and novelty detection using the COLD dataset, which includes semantic classes like doorway, kitchen, office, bathroom and laboratory. Most of the aforementioned place categorization systems are based on supervised learning, consider only a finite set of pre-defined place labels, and therefore are not suitable for recognizing newly encountered places. \cite{Ranganathan2012} developed an online Bayesian change-point detection framework: PLISS (Place Labeling through Image Sequence Segmentation), enabling discovery of novel place categories, along with uncertainty estimation through consideration of the spatio-temporal characteristics. The semantic place labels obtained in this manner were further combined with high-level information like adjacency and place boundaries using Conditional Random Field (CRF), in order to obtain a semantic map of the environment~\cite{Ranganathan2011}. \cite{Fazl-Ersi2012} proposed an alternative approach to addressing open-set place categorization, HOUP (Histogram of Oriented Uniform Patterns), as an image descriptor. Although the framework does not create new semantic classes, the proposed representation is demonstrated to exhibit a balance between strong discriminative power for (specific) place recognition, and generalization capability for place categorization. \subsubsection{Using Pre-defined 3D Object Models} The ability of a robot to track objects in its working environment is critical for performing many tasks. Approaches based on scan registration were among the earliest to emerge in this domain, such as the work presented in~\cite{Stuckler2012}. They proposed to learn and track 3D object models from RGB-D indoor data by aligning multiple views of these objects within multi-resolution ``surfel'' maps. Real-time alignment on a CPU was achieved using a probabilistic optimization framework and an efficient variant of ICP. Other approaches have built a point-cloud based 3D map, and then identified objects within it as in~\cite{Wei2012}. The authors developed a shape-based method to build a 3D semantic map using point cloud data from an RGB-D camera. Data was segmented based on planes (horizontal/vertical), and an a-priori model library was used to identify objects and extract object features; this information was then used for wheelchair navigation. Another example can be found in~\cite{Gunther2013}, where the authors developed a mapping-only framework based on indoor RGB-D data that created a triangle mesh for extracting and classifying planar regions as different furniture objects. The recognized objects were then replaced by their corresponding 3D CAD models following ICP alignment. Their system used OWL-DL (Web Ontology Language - Description Logic) and SWRL (Semantic Web Rule Language) as the ontology for defining object-property relations. \cite{Vasudevan2008} presented a hierarchical mapping approach based on detecting and clustering different objects while also considering their spatial relationships using a Bayesian classifier. For example, an \textit{office} is considered to be constituted by ``work-space'', ``meeting-space'', and ``storage-space'', each of which are further composed of several objects. Many researchers have focused on the ability to build a semantic map while also being able to track objects in the map. In~\cite{dame2013cvpr}, the authors demonstrated the use of object-specific knowledge to obtain accurate maps within a dense SLAM system. They also highlighted how 3D object tracking and 3D reconstruction could benefit each other, thus improving reconstruction of unseen parts and enabling accurate estimation of the scale of the map. \cite{Salas-Moreno2013} presented SLAM++, performing 3D object recognition and tracking to produce an explicit graph of objects (with 6-DoF poses), which is then used in a pose-graph optimization framework for instance-level object-oriented 3D SLAM. The authors used a database of 3D object models and performed relocalization and loop closures in large cluttered environments, while also enabling interaction with objects. Researchers have also explored the possibility of performing 3D object detection and recognition using a pre-built 3D map. \cite{Tateno2016} proposed incremental real-time segmentation of a 3D scene, reconstructed by SLAM, in order to perform 3D object recognition and pose estimation. They also highlighted the advantages of using multiple views of the objects, as opposed to single-view based (2.5D) object recognition. Their system used 3D models and was demonstrated through an AR application. \cite{Dong2017} developed semantic representation of an environment based on sparse point clouds, provided by a SLAM process, and semantic object detections, for example, cars detected through YOLO~\cite{redmon2016you}. They used vision and inertial sensors (accelerometer and gyrometer - now ubiquitous in phones and drones) to obtain semantic and syntactic attributes respectively. These representations were fed to a localization-and-mapping Bayesian filter to enable persistent object representation and re-detection of temporarily occluded objects. \subsubsection{Without Pre-defined Object Models} Without explicit knowledge about some or all of the objects that are encountered in an environment, robots must be equipped with a means by which to deal with novel objects. \cite{Rogers2012} presented a CRF model to jointly classify objects and room labels on a mobile robot, by incorporating information from both recognition of trained objects and classification of novel objects. They created a map with topologically connected rooms and metrically connected object poses using SURF features for object recognition. \cite{Pham2016} proposed an unsupervised geometry-based approach for segmentation of 3D point clouds into objects and meaningful scene structures, which form a high-level representation of a 3D geometric map. They also developed a novel global plane extraction algorithm that enforced planes to be mutually-orthogonal or parallel, conforming with man-made indoor environments. \cite{McCormac2018} presented Fusion++, an online object-level SLAM system with a 3D graph map of arbitrary reconstructed objects, where objects are incrementally refined via depth fusion, and are used for tracking, relocalization and loop closure detection, without intra-object warping. The proposed pipeline uses Mask-RCNN for instance segmentation that initializes per-object TSDF reconstruction, and was demonstrated on RGB-D indoor sequences. The open set recognition research field is also relevant here~\cite{scheirer2012toward, li2005open, phillips2011evaluation, scheirer2014probability, bendale2015towards, bendale2016towards}, and some existing mapping work has focused on dealing with open set conditions. \cite{Sunderhauf2017} built a semantic map with both object-level and low-level (point and mesh based) geometric representations that functions under open-set conditions and handles unseen instances. Their pipeline involves feature-based RGB-D SLAM, deep-learnt object detection, and 3D unsupervised segmentation~\cite{Pham2016}. \cite{Furrer2018} incrementally builds a database of object models from a traverse of a mobile agent requiring no prior knowledge of shapes or objects present in the scene. The presented pipeline includes: Global Segmentation Map (GSM) built from RGB-D images, object-like segment extraction, intra-segment matching and merging with previous instances in the database, and reconstruction of unobserved parts of the scene from merged models. \cite{Grinvald2019} incrementally builds volumetric object-centric maps using a RGB-D camera, while also reasoning jointly over geometric and semantic cues using a frame-wise segmentation approach. Their system infers high-level category information about detected and recognized elements, and discovers novel objects in the scene without requiring prior information about the objects. The proposed method also enables a distinction between unobserved and free space for enhanced human-robot interaction. Semantic mapping pipelines are not typically computationally cheap. While continual improvements in compute hardware help with this issue, as covered in Section \ref{secn:discussion}, efficiency is always beneficial with respect to cost, power consumption and deployment versatility. Research has therefore focused on improving absolute efficiency and scalability to larger environments. \cite{Tateno2015} developed a real-time incremental segmentation method for 3D point clouds obtained through SLAM, yielding segmentation in real-time, with complexity independent of the size of the global model. The proposed method is generally applicable to any frame-wise segmentation and any SLAM algorithm and was demonstrated in indoor environments. \cite{Vineet2015} presented dense, large-scale, outdoor semantic reconstruction of a scene in (near) real time that was also capable of handling dynamic objects through semantic fusion. They used hash-based techniques for large-scale fusion and efficient mean-field inference with dense CRFs, claiming it to be the first of its kind. \cite{Nakajima2019} presented highly accurate object-oriented scene reconstruction in real-time by using fast and scalable object detection for semantics and geometric incremental segmentation. They reduced computational cost and memory footprint by only labeling segmented \textit{regions} and not individual elements in the 3D map. \cite{Pham2019} performed on-the-fly dense reconstruction and semantic segmentation of 3D indoor scenes using an efficient super-voxel clustering, and a CRF based on higher-order constraints derived from structural and object cues. A reliance on objects brings with it new challenges, with one of the largest being the inconvenient property of them being movable. \cite{Runz2017} presented a dense RGB-D SLAM system that segments the scene into different objects using either motion or semantic cues while tracking and reconstructing their 3D shape in real time. It allows objects to move freely by fusing its shape over time using only the pixels associated to that object label. Consequently it is able to deal with dynamic scenes without treating moving objects as outliers, as was the approach in much prior research. \cite{Runz2019} presented MaskFusion, a real-time, object-aware RGB-D SLAM system that recognizes, segments, and assigns semantic labels to different objects, even if multiple objects are moving. The proposed system uses image-based, instance-level semantic segmentation to create an object-level semantic map, unlike the voxel-level representations used in prior work. More recently, \cite{di2020unified} developed a novel framework for dense piece-wise semantic reconstruction of dynamic scenes using motion and spatial relations, where moving objects are handled by imposing constraints based on the spatial locations of neighboring superpixels. Shape is an important property when dealing with objects, resulting in research focusing on using parameterized geometric primitives. \cite{Hashemifar2017} represented indoor environment objects as cuboids for semantic mapping; the cuboid detection method is based on image segmentation and plane fitting, and the cuboid matching is based on features like emptiness, orientation, surface coverage, and distance from edges. \cite{Nicholson2019}~presented QuadricSLAM, a factor graph based SLAM system that uses dual quadrics to represent 3D landmarks, derived from 2D object detections obtained over multiple views. They proposed a new geometric error formulation while also addressing the challenges of object occlusions. Building on this work,~\cite{hosseinzadeh2018structure} integrated additional planar and point constraints that help stabilise the SLAM estimate. Later,~\cite{hosseinzadeh2019real} explored how single view point cloud reconstructions of objects (via a CNN) can effectively constrain the shape of dual quadric landmarks. \cite{Drews2010} developed a framework to detect and compactly represent changes in the environment. This is achieved though multi-scale sampling of point cloud data, change detection using Gaussian Mixture Models, a superquadrics-based representation of objects that caused the change, and final refinement and optimization. Other related research includes research on cuboids from~\cite{Lin2013} as well as basic primitives from~\cite{Kaiser2015}. \subsubsection{Scene Graphs at Environment Level} A dense grid representation of an image or an environment can be thought of as a specific case of a graph structure. We discussed the use of scene graphs previously at image level based on spatial relationships between various objects or regions observed in a single image. In a robotics context, the concept of a scene graph typically comprises spatial elements at an environment level which the robot explores over time. In this vein, a number of researchers have explored the use of scene graphs for better representation of the environment~\cite{Blumenthal2013, Aksoy2010, Grotz2017, Kim2019, Zeng2018, Gawel2018, rosinol20203d}, leading to improved spatial reasoning. Using the concept of a Directed Acyclic Graph (DAG)~\cite{Shuey1986}, \cite{Blumenthal2013} proposed a 3D scene representation, Robot Scene Graph (RSG), which defines the organization of topological and spatial relations between objects, semantics of such relations, time-based handling, computational assets, and resource sharing. \cite{Blumenthal2014} extended this work with a Domain Specific Language (DSL) with four levels of abstraction for RSG~\cite{Blumenthal2013}, used for model-driven engineering tool chains in robotics. RSG-DSL is capable of expressing (a) application specific scene configurations, (b) semantic scene structures and (c) inputs and outputs for the computational entities that are loaded into an instance of a world model. \cite{Kim2019} presented a 3D scene graph constructed using a RGB-D data processing pipeline: keyframe extraction, spurious detection rejection (object detection based), local 3D scene graph construction, and finally, graph merging and updating for a global 3D scene graph. The proposed method was demonstrated on two tasks: Task Planning and Visual Question and Answering. \cite{Bozcan2019} developed a Boltzmann Machines-based generative scene model for representing objects and their spatial relations and affordances while also considering co-occurrences. In order to solve the cross-view localization problem, \cite{Gawel2018} used a graph of semantic blobs defined over a sequence of images, with a random walks strategy used to match a query sequence. \cite{pan2020spatio} demonstrated a video captioning system based on a spatio-temporal scene graph that explicitly captures object interactions using directed temporal edges and undirected spatial edges. Recently, \cite{rosinol20203d} proposed 3D Dynamic Scene Graphs (DSGs) which define an environment with multiple layers of abstraction, starting from a metric-semantic mesh, to objects, places and rooms and eventually to the whole building. While the aforementioned entities form the nodes in the directed graph, the edges encode pairwise spatio-temporal relations and explicitly model dynamic entities in the scene like humans and robots. DSGs represent the current state-of-the-art in terms of a high-level actionable representation of the environment, where robots can semantically reason about the space they are operating in and interact with humans. \subsection{Semantic Representations for SLAM and 3D Scene Understanding} \label{sec:semRep+SU+SLAM} \subsubsection{SLAM with Semantic Segmentation} \cite{flint2010cvpr} proposed a semantically meaningful indoor mapping system based on the Manhattan World assumption, where photometric cues were combined with pose information and sparse point cloud data obtained from an underlying metric SLAM system. In a subsequent work~\cite{flint2010eccv}, the authors developed a more efficient approach based on dynamic programming to label the indoor environment as floor, wall or ceiling. Further extending the use of Manhattan world, \cite{flint2011iccv} presented a joint inference procedure based on a Bayesian framework that combines photometric, stereo and 3D data to reason about floor and ceiling planes, and thus enable effective semantic scene understanding. Beyond reasoning at the surface level, researchers have also explored 3D structure-based semantic representations. \cite{Kundu2014} proposed a 3D occupancy map based on joint inference of 3D scene structure and semantic labels for outdoor monocular video data. They used a CRF model defined in 3D space and class-specific semantic cues to constrain the 3D structure in areas where multi-view constraints are weak. \cite{Hermans2014} described a process for transferring labels from 2D to 3D based on Bayesian updates and dense pairwise 3D CRFs for indoor RGB-D data, combined with a fast 2D semantic segmentation approach based on Randomized Decision Forests. \cite{Stuckler2015} integrated multi-view image segmentations within an octree-based 3D map by modelling geometry, appearance, and semantic labeling of surfaces for indoor RGB-D video. For robotics applications, real-time operations are typically necessary. Hence, some of the research work has particularly been focused on efficient processing. The pipeline proposed in~\cite{Stuckler2015} is based on random decision forests and probabilistic labeling using a Bayesian framework, and performs in real time or better on CPU and GPUs. \cite{Li2016} developed a scale-drift-aware, monocular semi-dense mapping system that can seamlessly switch between indoor and outdoor scenes where previous methods struggled. The system also saves computation time by enabling frame skipping for 2D segmentation, and through only considering keyframe connectivity and spatial consistency. \cite{McCormac2017} presented \textit{SemanticFusion}, a dense semantic 3D mapping system for indoor RGB-D data where semantic predictions from a CNN are probabilistically fused from multiple viewpoints using ElasticFusion (Dense SLAM)~\cite{Whelan2015}. The fusion technique also improves 2D semantic labeling performance over single frame predictions. The proposed system works in real time at 25 Hz. \cite{Xiang2017} combined CNN-based 2D semantic labeling with RNN-based data association (found using ElasticFusion~\cite{Whelan2015}) for dense semantic mapping on RGB-D indoor data. \cite{Yang2017} presented a 3D scrolling occupancy grid map, achieving near real time performance, with relatively low memory and computational requirements and an upper bound as environment size scales. To achieve this, they used a novel hierarchical CRF model with CNN-based 2D segmentation to optimize 3D grid labels on top of a stereo ORB-SLAM based grid map, and used superpixels to enforce smoothness. \cite{Hazirbas2017} proposed semantic labeling of indoor RGB-D data based on an encoder-decoder type network with two branches, one each for RGB and Depth, which improved performance when combined together. They found that the ``HHA'' representation~\cite{gupta2014learning} of depth images -- encoding \textit{H}orizontal disparity, \textit{H}eight above ground, and the \textit{A}ngle the pixel’s local surface normal makes with the inferred gravity direction -- improved performance. Both sparse and dense fusion also improved performance. \cite{Ma2017} used a CNN to predict semantic segmentation for RGB-D sequences. They trained the CNN to predict multi-view consistent semantics in a self-supervised way, enabling improved fusion at test time -- enhancing \cite{Hazirbas2017} with multi-scale loss minimization. Their system performed better than single-view baselines. Kimera~\cite{rosinol2020kimera} is a real-time metric-semantic SLAM system that works in real-time and integrates 2D semantic segmentation, IMU measurements, and optional depth measurements into a dense semantically annotated mesh of the environment. \subsubsection{Semantic Scene Understanding using 3D Point Clouds} \label{sec:sem+3DPointCloud} While 3D scene information can (somewhat laboriously) be derived from scale-unaware monocular visual SLAM algorithms for online mapping~\cite{newcombe2011dtam, engel2014lsd, mur-atal15, weerasekera2017icra}, a common avenue for estimating pixel depth in robotics research is to use range sensors, for example, Laser Scanners~\cite{nuchter2008towards,Xiong2010}, stereo camera pairs~\cite{Morreale2019}, LiDAR, radar, sonar or RGB-D sensors (like Microsoft Kinect~\cite{zhang2012microsoft}, Intel RealSense, Apple PrimeSense and Google Tango)~\cite{Wolf2015,Boulch2018}. The point cloud data from these sensors can be used to obtain a semantic map of the environment either directly~\cite{nuchter2008towards, Xiong2010, maturana2015voxnet} or in conjunction with color cameras~\cite{Riemenschneider2014,Wolf2015}. In this section, we discuss various semantic mapping techniques based on 3D information obtained either directly from range sensors~\cite{Xiong2010,Wolf2015} or indirectly inferred using SfM (Structure from Motion) offline~\cite{Riemenschneider2014} or other commercial solutions~\cite{Armeni2016}, like Matterport~\cite{bell2014capturing}. \cite{Xiong2010} proposed a method for creating a 3D semantic model from cluttered point cloud data using a CRF model to discover and exploit contextual information for classifying planar patches, without relying on pre-defined rules~\cite{nuchter2008towards}. The results suggested that using co-planar context improved semantic classification results, while other tested context types didn't help. Researchers have also focused on efficiently processing point cloud data by either avoiding redundant processing~\cite{Riemenschneider2014} or using approximation techniques~\cite{Wolf2015}. \cite{Riemenschneider2014} proposed exploiting the geometry of a 3D mesh model obtained from multi-view SfM reconstruction to avoid the redundant labeling of visually-overlapping individual 2D images. Instead of clustering similar views, their method searched for the ideal view that best supported the correct semantic labeling of each face of the underlying 3D mesh. Their proposed single-image approach performed better than label fusing of multiple images, while also being more efficient. \cite{Wolf2015} presented an efficient semantic segmentation framework for indoor RGB-D point clouds combining a Random Forest classifier and dense CRF to learn common spatial relations via pairwise potentials. The use of parallelization and mean-field approximation for CRF inference enabled a halving of computation time. Many conventional semantic segmentation based techniques consider small-scale point cloud data. Focusing on larger scalability, \cite{Armeni2016} presented a detection-based semantic parsing method for large-scale indoor point clouds. The proposed pipeline was based on a hierarchical approach that first created semantically meaningful spaces (e.g. rooms) and then parsed them into their structural and building elements (e.g. walls and columns) -- all of it in a global 3D space, where the first step injected strong 3D priors into the second. Demonstrated at scale in an area covering over 6000 square meters and 215 million points, the study highlighted a unique set of challenges and opportunities associated with parsing such large point clouds, including the richness of recurrent geometric information and the introduction of additional semantic classes. Recent trends include the advent of modern deep learning-based approaches, the increased availability of 3D point clouds~\cite{Silberman2012, Armeni2016} for robots, and a growing number of shape datasets~\cite{de2013unsupervised, wu20153d}. Connected with these trends has been significant growth in research focusing on 3D object detection and semantic segmentation along with shape and scene completion, areas highly relevant to dense semantic mapping. 3D ShapeNets~\cite{wu20153d} and VoxNet~\cite{maturana2015voxnet} pioneered the use of 3D CNNs for object recognition using 3D point clouds. Previously existing ``2.5D'' approaches based on RGB-D data mainly considered depth as an additional 2D channel to the RGB input and have been extensively leveraged for tasks like object recognition~\cite{socher2012convolutional, quadros2012occlusion, de2013unsupervised, song2014sliding, gupta2014learning, alexandre20163d}, grasp detection~\cite{lenz2015deep}, vehicle detection~\cite{li2016vehicle} and semantic segmentation~\cite{hoft2014fast, gupta2014learning}. The use of voxel grids~\cite{wu20153d, maturana2015voxnet} to learn 3D representations for such tasks is both conceptually different and significantly robust, as discussed in subsequent sections. \subsubsection{\textit{Dense} Volumetric Representation and 3D CNNs} Wu \textit{et al}.~\cite{wu20153d} proposed representing a 3D geometric shape on a 3D voxel grid and learnt a joint probabilistic distribution of binary variables on the grid using a Deep Belief Network (DBN)~\cite{hinton2006fast}. Distinct from their generative model aimed at shape reconstruction, Maturana and Scherer~\cite{maturana2015voxnet} presented VoxNet: a basic 3D CNN architecture designed for voxel grid representation of point clouds aimed at real-time 3D object detection, with an order of magnitude fewer trainable parameters than 3D ShapeNets~\cite{wu20153d}. \cite{cciccek20163d} extended U-Net~\cite{ronneberger2015u} to 3D U-Net to learn from sparsely annotated volumetric data, applied to biomedical data segmentation. Unlike the use of pre-segmented objects in~\cite{wu20153d, maturana2015voxnet,cciccek20163d}, Huang and You~\cite{huang2016point} extended the use of 3D CNNs using a LeNet~\cite{lecun1998gradient} based architecture for semantic segmentation of raw point cloud data in outdoor scenes comprising a variety of semantic classes. 3D voxel representations used with 3D CNNs often lead to coarse semantic segmentation~\cite{huang2016point, qi2016volumetric}, by assuming all the points within a voxel belong to the same object class. Addressing this problem, \cite{tchapmi2017segcloud} proposed SEGCloud as an end-to-end framework, where coarse voxel predictions from a 3D Fully Convolutional CNN are transferred back to the raw 3D points via trilinear interpolation. Fine-grained semantics are then obtained from a global consistency constraint enforced by the Fully Connected Conditional Random Field. \subsubsection{Scene Completion and Semantic Segmentation} ``Semantic Scene Completion''~\cite{Song2016} refers to the joint learning task of scene completion and semantic segmentation, leading to enhanced understanding of the environment, particularly relevant to robotic exploration. Song \textit{et al}.~\cite{Song2016} used single-view depth map observations to produce a complete 3D voxel representation with semantic labels. They proposed \textit{SSCNet}: an end-to-end 3D CNN that uses a dilation-based 3D context module to efficiently expand the receptive field and enable 3D context learning. Dai \textit{et al}.~\cite{Dai2017a} presented a 3D CNN for shape completion that encodes the global context using semantic class predictions from a 3D shape classifier. They used a patch-based 3D shape synthesis method to refine the predictions, by imposing 3D geometry from shapes retrieved from a prior database. In follow-up work, Dai \textit{et al}.~\cite{Dai2018} designed a 3D CNN to process an incomplete 3D scan and predict a complete 3D model with per-voxel semantic labels. The proposed CNN is a fully-convolutional generative network, with filter kernels that are invariant to the overall scene size, enabling processing of large scenes with varying spatial extent. They also developed a coarse-to-fine inference strategy to produce high resolution output. \subsubsection{\textit{Sparse} Volumetric Representation and 3D CNNs} One of the common challenges in dealing with 3D point cloud data is its non-uniform density, where certain regions of the scene may not have any information at all, or where existing information may not always be semantically informative. A uniform voxel grid therefore may not be the best way to represent the data. In this vein, \cite{Riegler2017} proposed OctNet, a 3D CNN suited to sparse 3D data, enabling efficient representation of high resolution input. Their method hierarchically partitioned the 3D voxel grid using a set of unbalanced octrees~\cite{meagher1982geometric} where each leaf node stored a pooled feature representation, thus enabling effective allocation of memory and computation to the relevant dense regions. Sparse 3D convolutions have also been explored to avoid redundant computations~\cite{graham2015sparse, engelcke2017vote3deep, graham20183d}. \cite{graham2015sparse} extended sparse 2D CNNs used for hand-writing recognition~\cite{graham2014spatially} to sparse 3D CNNs, based on the concept of performing convolutions only on the ``active'' spatial locations that do not differ from their ``ground state''. \cite{engelcke2017vote3deep} presented Vote3Deep: a feature-centric voting mechanism~\cite{wang2015voting} to perform sparse 3D convolutions by only considering non-zero feature locations. The use of ReLU~\cite{glorot2011deep} after a sparse convolutional layer also prevented the dilation of non-empty cells, thus achieving greater sparsity than~\cite{graham2015sparse}. \cite{graham20183d} proposed Submanifold Sparse Convolutional Networks (SSCN) that fix the spatial locations of active sites to prevent the ``submanifold dilation problem''~\cite{graham2015sparse}, keeping the sparsity unchanged for subsequent layers of the network. \cite{jampani2016learning} proposed learning high dimensional linear filters for sparse feature spaces using permutohedral lattices, and demonstrated learning the kernel parameters for a general bilateral convolution in semantic segmentation. \cite{li2016fpnn} presented the Field Probing Neural Network (FPNN) that employs field probing filters to efficiently extract features from volumetric distance fields, learning the weights and locations of the probing points that compose the filter. In order to obtain a semantically informative map, \cite{Morreale2019} proposed using semantic segmentation to remove redundancy and noise from dense 3D point clouds attributed to planar surfaces like ground and walls. They developed a variety of point cloud simplification techniques that employed global and local region statistics to selectively decimate 3D points, while mostly preserving those near intra-class edges and discontinuities. \subsubsection{2D Multi-View Representation of 3D} The spatial sparsity within 3D point clouds can lead to decreased spatial resolution and increased memory consumption when using regular voxel grids~\cite{qi2016volumetric}. To mitigate these issues, an alternative approach processes multiple 2D views generated from the 3D point cloud~\cite{su2015multi} and then projects them from 2D back to 3D~\cite{lawin2017deep, Boulch2018}. \cite{su2015multi} presented a Multi-View CNN (MVCNN) to learn shape recognition from 2D renderings of a 3D point cloud, demonstrating that even a single 2D view based prediction could outperform 3D CNNs based on volumetric representation~\cite{wu20153d}. \cite{lawin2017deep} projected the point cloud onto a set of synthetic 2D images which are fed to a 2D CNN for semantic segmentation, and then re-projected this to the point cloud. Benefiting from the abundance of 2D labeled data and a multi-stream fusion of color, depth and surface normals, their method achieved superior performance to comparable baselines. \cite{Boulch2018} proposed to sample multiple 2D image views of a point cloud using random and multi-scale sampling strategies. They employed both RGB and depth-based views for 2D pixel-wise semantic labeling, with labels efficiently back-projected via buffering. \cite{tatarchenko2018tangent} explored ``tangent convolutions'' with an emphasis on leveraging 2D surface information from 3D point clouds, by projecting local surface geometry on a tangent plane around every point to obtain a set of tangent images. Although the methods based on multiple 2D views of 3D data are in general more efficient and scalable than voxel grid-based methods, they may not always be applicable for challenging 3D shape recognition tasks due to loss of information during projection operations~\cite{klokov2017escape}. Alternatives in the form of hybrid representations~\cite{guo2020deep} of 3D point cloud have also been considered. Dai \textit{et al}.~\cite{Dai2018a} proposed an end-to-end trainable 3D CNN to predict per-voxel semantic labels. Their method combines two streams of features: one extracted from per-voxel max pooling of multiple 2D RGB views and the other from 3D geometry, demonstrating a significant performance improvement attributed to this joint 2D-3D learning. \subsubsection{Unstructured Points Based Representations} While volumetric representations present the environment in a structured manner, handling point cloud data as a set of unordered and unstructured points has proven to also be a viable approach. \cite{Qi2017a} presented \textit{PointNet}, a novel deep network that processes points sets without voxelization or rendering and learns both global and local features. Demonstrated to be efficient on tasks like object classification, part segmentation, and scene semantic parsing (dense semantic mapping), PointNet works on an unordered set of points exhibiting permutation-invariance, unlike ordered 2D image data or a 3D volumetric grid, while also being robust to input perturbation and corruption. \cite{Qi2017c} proposed \textit{PointNet++}, a hierarchical NN that applies PointNet recursively on a nested partitioning of the input point set, enabling learning of local features with increasing contextual scales. With the ability to capture local structures induced by the metric space of points, PointNet++ demonstrated improvement on semantic segmentation of single-view 3D point clouds. \cite{Engelmann2018} explored direct semantic segmentation of unordered point clouds by extending PointNet~\cite{Qi2017a}, particularly enlarging its receptive field over a large 3D scene to incorporate larger-scale spatial context at both input and output level. Building on point-level representations, significant research has focused on developing learning algorithms based on characteristics like unordered structure, intra-point interaction and transformation-invariance~\cite{liu2019deep}, for example, by using Point-wise convolutions~\cite{hua2018pointwise, wu2019pointconv}, Recurrent Neural Networks~\cite{ye20183d, huang2018recurrent}, Graph Neural Networks~\cite{te2018rgcnn, wang2019dynamic} and Autoencoders~\cite{yang2018foldingnet,zamorski2018adversarial}. \subsubsection{Graph- and Tree-Based Representations at Scene Level} In order to better capture the structure of 3D point clouds without requiring voxel grids, researchers have explored the use of graph-~\cite{simonovsky2017dynamic, Qi2017} and tree-~\cite{klokov2017escape, zeng20183dcontextnet} based networks. \cite{simonovsky2017dynamic} proposed an Edge-Conditioned Convolution (ECC) to learn from the local neighborhood of the point cloud represented as a graph, where filter weights were dynamically generated for each specific input sample. \cite{Qi2017} designed a 3D Graph neural network that builds a k-nearest neighbor graph on top of 3D point clouds, where each node in the graph corresponds to a set of points represented by appearance features extracted by a unary CNN from 2D images. This approach consequently was able to leverage both 2D appearance and 3D geometric relationships. The method is capable of extracting long range dependencies within images -- typically difficult to model in traditional techniques. Inspired from superpixels~\cite{achanta2012slic}, \cite{landrieu2018large} introduced SuperPoint Graphs (SPG) where nodes represent simple shapes, and edges encode contextual relationships between object parts, enabling semantic segmentation of large-scale point clouds. \cite{klokov2017escape} proposed Kd-Net for parsing 3D point clouds, using a kd-tree structure~\cite{bentley1975multidimensional} to form the computational graph, and hierarchical representations where the root node is recursively computed from representations of its children. Addressing the lack of overlapping receptive fields in Kd-Net, \cite{li2018so} presented SO-Net based on the Self-Organizing Map (SOM)~\cite{kohonen1990self}, where the receptive field overlap is controlled by performing point-to-node k-nearest neighbor (kNN) search on the SOM, enabling a better representation of the underlying spatial distribution of point clouds. The increasing ubiquity of 3D sensing~\cite{bell2014capturing, Wolf2015, Boulch2018}, maturity of visual SLAM~\cite{mur2017orb, rosinol2020kimera} and SfM techniques~\cite{schonberger2016structure, kong2019deep, vijayanarasimhan2017sfm}, and the evolution of deep learning have together facilitated extensive research on 3D point clouds. This has led to numerous novel approaches, for example, ShapeNet~\cite{wu20153d}, VoxNet~\cite{maturana2015voxnet}, OctNet~\cite{Riegler2017}, PointNet~\cite{Qi2017a}, tangent convolutions~\cite{tatarchenko2018tangent}, SSCN~\cite{graham20183d} and Kd-Net~\cite{klokov2017escape}, which have pushed the boundaries of 3D scene understanding. Although capable of processing information at an environment level -- beyond what can be achieved through a single image, these methods do not typically consider \textit{incremental} scene understanding. In the near future, bridging the advances in 3D point cloud processing and 3D reconstruction capabilities of modern SLAM techniques will significantly benefit robots in semantic scene understanding. \subsection{Perception \textit{of} Interaction} \subsubsection{Actions and Activities} When interacting with the world, especially with the humans that occupy it, an understanding of actions and activities is essential. In its most basic form, activity recognition can be simply treated as a supervised machine learning problem---present the machine with a short video clip and classify the entire clip into one (or more) of $k$ different categories learned from a large corpus of labeled examples~\cite{Simonyan:NIPS2014, Laptev:CVPR2008, Rodriguez:CVPR2008,Soomro:arxiv2012,Carreira:CVPR2017}. Moving beyond just classification, localization of specific activities within a long video sequence involves identifying both the temporal and spatial location of each activity, often in so-called ``action tubes''~\cite{Gkioxari:CVPR2015}. This approach to activity recognition and detection is typified by the various tasks in the annual ActivityNet Challenge and its associated dataset of human activities~\cite{Caba:CVPR2015}. Many of the works in this area consider activity recognition from the perspective of a third-person observer (a notable exception being the EPIC-Kitchens egocentric activity classification dataset~\cite{Damen:ECCV2018}) and learn black-box models that segment and label activities. In some cases the temporal aspect of an action is modeled through dense trajectory features~\cite{Wang:CVPR2011}, which track the movement of keypoints through time. A sequence of atomic action units or ``Actoms''~\cite{gaidon2011actom} can also be used to represent a semantically-consistent action sequence as opposed to learning its discriminative parts. \cite{gaidon2014activity} show that a complex activity composed of several short actions is better represented and compared using a hierarchy of motion decomposition. The two-streams approach~\cite{Simonyan:NIPS2014} separates appearance and motion (optical flow). A rank-pooling method developed by Fernando and colleagues~\cite{Fernando:PAMI2016, Fernando:ICML2016, Fernando:CVPR2016} encodes frame order as a function of the frame's appearance. An efficient first-order approximation of rank-pooling, known as Dynamic Images~\cite{Bilen:CVPR2016}, has been applied successfully in many deep learning approaches for activity classification. However, even Carreira and Zisserman~\cite{Carreira:CVPR2017}, who ask the question ``\emph{Quo Vadis}, Action Recognition?''\footnote{Where are you going action recognition?}, do not fully consider a more fine-grained understanding of human actions (e.g. different types of swimming) likely necessary for robotic applications. Robots are likely to require not just classification of the activity being performed, but also localization of both the person performing the activity and the object being interacted with (if any). One of the most important pieces of semantic information for understanding activities is the pose of the human performing the activity and how that pose changes over time. Ramanan and Forsyth~\cite{Ramanan:NIPS2003}'s work is an early example of research proposing to use human pose and motion to classify activities. In their model body parts are tracked over time, with sequences annotated using a hidden Markov model. In more recent work, Wang \textit{et al}.~\cite{Wang:action:CVPR2013} improve the estimation of human pose by first building dictionaries of spatial and temporal part sets and then using a kernel SVM to classify actions. Luvizon \textit{et al}.~\cite{Luvizon:CVPR2018} solve human pose estimation and activity recognition jointly and train a single deep learning model to perform both tasks, with pose and appearance features combining to predict actions. In the context of robotic vision, Ramirez-Amaro \textit{et al}.~\cite{Ramirez-Amaro2019} present a recent survey of the most representative approaches using semantic descriptions for recognition of human activities, with the intention of subsequent execution by robots. In such a context it is advantageous to characterize human movement through multiple levels of abstraction (in this particular case four) from high-level processes and tasks to low-level activities and primitive actions. Given this hierarchy and a ``semantic'' representation of a human demonstrated task, the ultimate goal is for a robot to replicate the task, or assist the human in achieving the intended outcome. Similar to the work of Ramanan and Forsyth~\cite{Ramanan:NIPS2003}, Park and Aggarwal~\cite{Park2004} propose to recognize human actions and interactions in video by modeling the evolution of human pose over time. Their framework uses a three-level abstraction where the pose of individual body parts (e.g. head and torso) are identified and linked at the lowest level using a Bayesian network; actions of a single person are modeled at the mid-level using a dynamic Bayesian network; and alignment of multiple dynamic Bayesian networks in time allows inference of interactions at the highest level. The result is a representation that can be translated into a meaningful semantic description in terms of subject, verb and object. Reducing the reliance on large quantities of annotated training data, Cheng \textit{et al}.~\cite{Cheng2013a} developed a zero-shot learning framework that also considers a three-level hierarchy that takes into account low level features, mid-level semantic attributes and high-level activities mapped through a temporal sequence. The result is a model that can recognize previously unseen human activities. Cheng and his colleagues extended this work by proposing a two-layer active learning algorithm for activity recognition for unseen activities, using a semantic attributes-based representation. In this case an attribute is a human-readable term describing an inherent characteristic of an activity~\cite{Cheng2013}. \subsubsection{Hands and Arms} Within the broader topic of general activity recognition, hands and arms play a key role in activities where humans are involved. \cite{Ramirez-Amaro2014} proposed forming a semantic representation of human activities by extracting semantic rules based on three hand motions: move, not move, and tool use, and two object properties: ObjectActedOn and ObjectInHand. Their system is adaptable to new activities which can be learned on-demand. \cite{Ramirez-Amaro2015b} extended the work in~\cite{Ramirez-Amaro2014} and explored the use of virtual reality-based additional 3D information to understand and execute the demonstrated activities. They integrated their method on an iCub humanoid robot. \cite{Ramirez-Amaro2015a} also developed a method to infer human-coordinated activities (like use of two hands), that was invariant to observation from different execution styles of the same activity (e.g. left-handed vs right-handed). They used a three-level approach: extract \textit{relevant} information from observations, infer the observed activity, and trigger the motion primitives to execute the task. \cite{Ramirez-Amaro2015} explored an unsupervised learning method based on Independent Subspace Analysis (ISA) to extract invariant spatio-temporal features directly from unlabeled video data. A second stage automatically generated semantic rules, enabling high-level reasoning about human activities that resulted in improved performance. \cite{Ramirez-Amaro2017} proposed semantic representations of human activity, where semantic rules based on relationships between human motions and object properties are first learned for basic and complex activities, and then used to infer the activity. They used Web Ontology Language (OWL) and KnowRob for incorporating knowledge/ontology. \cite{Ramirez-Amaro2017a} extended the semantic reasoning method from~\cite{Ramirez-Amaro2014} by including gaze data (in addition to the third person view) to segment and infer human behaviors. They demonstrated the complementary nature of first- and third-person view (using egocentric and external cameras respectively), enabling the system to deal with occlusions. Finally, \cite{Ramirez-Amaro2019a} presented a novel learning-by-demonstration method that enables non-expert operators to program new tasks on industrial robots. The proposed semantic representations were found to be invariant to different demonstration styles of the same activity. \cite{Yoon2018} presented a new representation for 3D reconstructed trajectories of human interactions, referred to as ``3D Semantic Map'' - a probability distribution over semantic labels observed from multiple views. They use semantics of body parts, for example the head, torso, legs and arms, and other objects in the vicinity, such as a dog or a ball. Spatio-temporal semantic labels are inferred by graph-cut formulation based on multiple 2D labels. The authors claim ``This paper takes the first bold step towards establishing a computational basis for understanding 3D semantics (of human interaction) at fine scale.'' Chang \textit{et al}.~\cite{Chang2016,Chang2018} took a complementary approach by finding structural correspondences of objects that have similar topologies or motions. For example, their method is able to match corresponding body parts (including arms and hands) of a humanoid robot with that of a human from a video sequence without any prior knowledge of the body structures. \cite{Wang2018} discussed the availability of large amounts of visual data from wearable devices and existing methods used to characterize everyday activities for visual life-logging, for example, semantic annotations of visual concepts and recognition and visualization of activities. Motivations in this area of research include its use for behavioral analysis and in assistive living scenarios. \subsection{Perception \textit{for} Interaction} \subsubsection{Object Affordances} The term ``affordances'' was coined by the psychologist Gibson~\cite{gibson2014ecological} to explain how inherent values of things in the environment can be perceived and how this information can be linked to the potential actions of an agent. In one of the early applications of the concept in robotics, \cite{fitzpatrick2003learning} presents a robot that learns the roll-ability of four different objects by ``playing'' with them and observing the changes in the environment; however the generalization of this affordance to novel objects and affordances is not studied. In order to formalize the concept of affordances in the context of autonomous robotics, \cite{csahin2007afford} reviews the usage of affordances in other fields, and proposes a framework based on relation instances of the form \texttt{(effect, (entity, behavior))} which are acquired through the interaction of the agent with its environment. \cite{dogar2007primitive} implements this framework for a mobile robot, enabling goal-oriented navigation by learning the affordances of its environment through the effects of primitive behaviours such as ``traverse'' or ``approach''. Performing complex manipulation actions requires the encoding of temporal dependencies in addition to an understanding of affordances. Closely related to the formalization of affordances above, the Object-Action Complexes (OACs) concept \cite{kruger2011object} attaches the performed actions to the objects as attributes and provides grounded abstractions for sensory–motor processes. By defining affordances as state transition functions, OACs allow for forward prediction and planning. Several researchers have studied deriving such attributes from visual information \cite{Aksoy2011,Aein2013,Aksoy2015a,yang2015robot}. The Semantic Event Chain (SEC) framework developed by \cite{Aksoy2011} analyzes the sequence of changes of the spatial relations between the objects that are being manipulated by a human or a robot. This approach generates a transition matrix which encodes topological variations in a sequence graph of image segments during the manipulation event, allowing transfer of manipulation actions from human demonstration to a robotic arm. \cite{Aein2013} designed an architecture for generic definition of a robot's human-like manipulation actions. Manipulations are defined using 3 levels: a top level, which abstractly defines objects and their relations and actions; a mid level, which defines chaining of action primitives via SEC; and a bottom level that defines sensory data collection and communication with the robot control system. Using these representations, a number of approaches have been presented for autonomously learning affordances in the context of manipulation. \cite{Aksoy2015a} proposes online incremental learning of an archetypal Semantic Event Chain model for each manipulation action by observation, without requiring any prior knowledge about actions or objects. Similarly, \cite{yang2015robot} leverages information from the cloud, by learning manipulation action plans from cooking, fetched from the web. Lower-level perception modules, grasping type recognition and object recognition is combined with a probabilistic manipulation action model at the higher level. \cite{kappler2012templates} studies pre-grasp sliding actions to facilitate grasping, for instance sliding a book to the table edge so that it could be grasped. In this work, objects are divided into categories, such as box or cylinder, based on sub-symbolic object features including shape and weight. A sliding action is simulated before actual execution, conditioned on the object class. Afrob~\cite{varadarajan2012afrob} provides a database for affordances, targeted at domestic robot scenarios, consisting of 200 object categories and structural, material and grasp affordances. The following subsections discuss more concrete applications of affordance and semantics to robotic tasks, ranging from low-level, e.g. item ``graspability'', to high level concepts such as understanding language and social behaviour. \subsubsection{Grasping and Manipulation} Robotic grasping is concerned with the problem of planning stable grasps for an object using a robotic gripper. Early approaches to this problem were largely analytical, focusing on providing a theoretical framework based on mathematical and physical models of contact points between the manipulator and object, used to quantify the stability and robustness of grasps~\cite{roa2015grasp, bicchi2000robotic}. However, the reliance of such methods on precise physical and geometrical models makes them brittle in the presence of noise or uncertainty found in robotic systems. As such, many modern approaches to robotic grasping are data-driven, using generalizable models and experience-based approaches to improve calculation times, robustness to errors and enable generalisation to novel objects \cite{bohg2013data}. A common approach in data-driven grasp synthesis is to use semantic information to transfer grasping knowledge to ``known'' or ``familiar'' objects. A number of works rely on precise object recognition and pose estimation to apply pre-computed grasps from a known object model to an instance of that model in reality \cite{detry2011learning, detry2010refining, zeng2017ew, morales2006integrated, tremblay2018dope, papazov2012rigid, collet2011moped}. More general methods work with familiar objects; those which are semantically or geometrically similar to objects previously seen, and are able to generalise grasps across instances of an object's class (for example mugs) \cite{Dang2012, hillenbrand2012transferring} or object parts \cite{detry2012generalizing, detry2013learning} (for example handles)~\cite{ten2016localizing}. Song \textit{et al.} \cite{song2015learning} present a hybrid grasp detection pipeline for familiar objects that fuses local grasp estimates based on depth data with global information from a continuous category-level pose estimation process, which is able to overcome the limitations of both approaches individually. Rather than rely on object models, Manuelli \textit{et al.}~\cite{manuelli2019kpam} define grasping and manipulation actions by learning semantic 3D keypoints from visual inputs that generalise across novel instances of an object class, making them more robust to intra-category shape variation. More recently, data-driven approaches backed by deep learning have proven very effective at predicting robotic grasps on arbitrary objects from visual information~\cite{morrison2018closing, morrison2019learning, mahler2017dex, mahler2019learning, ten2017grasp}, seemingly removing the immediate need for semantic information in the grasping pipeline, at least in terms of grasping alone. However, in many robotics applications, the ability to grasp and transport arbitrary objects in a stable manner is not enough in itself, but rather a prerequisite for higher-level manipulation tasks where the choice of grasp is dependent on the goal~\cite{billard2019trends}. The representation of semantics in robotic grasping may take many different forms and is largely informed by the task to be completed. In the simplest case, the semantics of a manipulation task may be defined at an object recognition level, where a grasp detection algorithm is combined with an object detection or semantic segmentation system (Section~\ref{secn:semanticsfundamental}). This is a common choice in pick-and-place style tasks, such as warehouse fulfilment, where the requirement for semantics is limited to object identification. A common successful approach in the Amazon Robotics Challenge was to use an object-agnostic grasp detection algorithm in parallel with a standalone semantic segmentation system~\cite{morrison2018cartman,zeng2018robotic,schwarz2018fast}. Rather than use two separate streams, other approaches use joint representations of object-specific grasp detection. Guo \textit{et al.}~\cite{guo2016object} train a CNN to recognise the most exposed object in a cluttered scene while simultaneously regressing the best grasp pose for the detected object. This joint model outperformed a system comprising two models trained individually on object and grasp detection. \cite{Jang2017} improve this idea by using a two-stream attention-based network that learns object detection, classification, and grasp planning end-to-end. The two streams, ventral and dorsal, perform object recognition and geometric-relationship interpretation respectively, and outperform a single-stream model on the same task. To grasp an object, humans rely not only on spatial information, but also knowledge about the objects, such as its expected mass and rigidity, and the constraints of the task to be performed~\cite{verhagen2012cortical}, for example, grasping a knife by the handle correctly to perform a cut, or not blocking the opening of a mug to pour water. In the same way, to perform higher level tasks robots must also understand the possible function (``affordances'') of objects and how they relate to the constraints of tasks to be performed. To this end, a number of research works focus on encoding semantic constraints within a robotic grasping pipeline. Affordance prediction can also be performed as a standalone task as a precursor to a separate grasp planning pipeline, relying largely on visual cues. Myers \textit{et al.}~\cite{myers2015affordance} present an approach inferring the affordances of objects based on geometric information and visual cues. By combining hand-coded features with traditional machine learning methods they were able to predict object part affordances such as \textit{cut}, \textit{contain}, \textit{pound} and \textit{grasp} in RGB-D images of common kitchen and workshop tools. Nguyen \textit{et al.} \cite{nguyen2016detecting} extended this approach by using a CNN to predict pixel-wise affordances, removing the need for hand-designed features. Kokic \textit{et al.}~\cite{kokic2017affordance} use a CNN to detect affordances on arbitrary 3D objects based on geometric rules, for example, that thin, flat sections of objects afford (provide) \textit{support}. The affordance detection is combined with a separate object classification and orientation stream to plan task-specific grasps. Song \textit{et al.}~\cite{song2011multivariate, song2015task} present a probabilistic framework for encoding the relationships between features for task-specific grasping using Bayesian networks. Their model jointly encodes features of the target object, such as category and shape, task constraints and grasp parameters, hence modelling the dependencies between relevant features. However, the approach also relies on hand-crafted features for representing objects and task constraints, making it difficult to scale to extra tasks and objects. Hjelm \textit{et al.}~\cite{hjelm2015learning} use metric learning to automatically learn the relevant visual features for a given task from human demonstration. Along the same lines, Dang and Allen~\cite{Dang2012} present ``semantic affordance maps'' that link local object features (a depth image) along with tactile and kinematic data to semantic task constraints for an object. Given an object of a known class and a task, the optimal grasp approach vector is computed from the semantic affordance map, followed by a grasp planning step along the computed approach vector. The above methods all employ some level of category-specific encoding, meaning that they won't generalise to new object classes. In contrast, Ard\'on \textit{et al.}~\cite{Ard2018} proposed employing semantic information from the surrounding environment of a target object to improve inference of affordances. They used a weighted graph-based knowledge base to model attributes based on shape, texture and environment, such as locations or scenarios in which the object is likely to appear. Their method does not require a-priori knowledge of the shape or the grasping points. Detry \textit{et al.}~\cite{Detry2017} present another approach to grasping previously-unseen objects in a way that is compatible with a given task. They use CNN-based semantics to classify image regions that are compatible and incompatible with a task in combination with a geometric grasp model. For training on tasks like ``pouring'', task constraints like ``grasp away from opening'' are used to define the \textit{suitable} and \textit{unsuitable} labels for vertices of object mesh models. The ``semantic success'' of a task is assessed based on whether the grasp is compatible with the task and ``mechanical success'', by having the robot attempt to lift the object off the table. Combining semantic information with robotic grasping is likely a crucial step towards equipping robots with the ability to autonomously carry out tasks in unstructured and dynamic environments. While the above approaches all achieve impressive results, the largest outstanding questions still revolve around accurately and efficiently transferring semantic knowledge to new objects and tasks. The following section looks at approaches that go beyond grasping and make use of semantic information for higher-level task completion. \subsubsection{Higher-level Goals and Decision Making} Semantic maps and information can be exploited to facilitate higher-level goal definitions and planning, for humanoids \cite{Kaiser2015,Zeng2018} and domestic robots \cite{blodow2011autonomous, cosgun2018context, Zeng2018, galindo2013inferring}. These approaches often use RGB-D data to extract semantic information. For humanoids, \cite{Kaiser2015} used RGB-D data to build representations of the environment from geometric primitives like planes, cylinders and spheres. This information is used to extract the affordances of objects, such as their ``pushability'' and ``liftability'', as well as full-body capabilities such as support, lean, grasp and hold. \cite{Grotz2017} extends the work in \cite{Kaiser2015} with semantic object information, such as chair or window, and uses spatio-temporal fusion of multiple geometric primitives (using a spatial scene graph representation) to identify higher level semantic structures in the scene. For object manipulation, \cite{Zeng2018} parses a given goal scene as an axiomatic scene graph composed of object poses and inter-object relations. A novel method is proposed for scene perception to infer the initial and goal states of the world. \cite{blodow2011autonomous} utilizes various segmentation methods for generating initial hypotheses for furniture drawers and doors, which are later validated with physical interaction. Given a task, this approach is able to answer queries such as ``Which horizontal surfaces are likely to be counters?'' by processing knowledge built during mapping. \cite{cosgun2018context} present an interactive labeling system, where human users can manually label semantic features, such as walls and tables, and static objects, such as door signs. These labels can then be used to define navigation goals such as ``go to the kitchen'', or for specialized behaviour such as for passing doors. \cite{galindo2013inferring} presents a goal-inferring approach that detects deviations from operational norms using semantic knowledge. For instance, if the robot ``knows'' that perishable items must be kept in a refrigerator, and observes a bottle of milk on a table, the robot will generate the goal to bring that bottle into a refrigerator. Robotic tool use for manipulation brings the topics of object affordances, grasping and task-level decision making together. \cite{mar2017can} studies tool affordances through self-exploration based on their geometry - how the tool is grasped. In particular, they study the dragging action, parameterized by the angle of the drag, with the effect measured as the object displacement. In more recent work, Fang \textit{et al.}~\cite{fang2020learning} address task-oriented grasping from the point of view of tool usage, where a robot must grasp an object in a way which allows it to complete a task. For example, the best way to grasp a pair of scissors differs depending on the task: transporting the scissors may require a different, safer grasp to using them to cut a piece of paper. Their approach uses self-supervised learning in simulation to jointly learn grasping and manipulation policies that are then transferred to novel tools in the real world. \subsubsection{Semantics for Human-Robot and Robot-Robot Interaction} Semantics play a crucial rule in human-robot interaction, in particular for collaborative task execution which goes beyond the human-command-robot-execute model. This is achieved using inverse semantics, introduced by Tellex \textit{et al.}~\cite{Tellex2015}, to enable the robot to generate help requests (for an assembly task) for robots in natural language, by emulating the ability of humans to interpret requests. Inverse semantics involved using a Generalized Grounding Graph ($G^3$) framework~\cite{tellex2011understanding} for the task and using models based on both the environment and the listener. Gong and Zhang~\cite{Gong2018} proposed temporal spatial inverse semantics to enable a robot to communicate with humans by extending the natural language sentence structure that can refer to previous states of the environment, for example, ``Please pick up the cup beside the oven that was on the dining table''. They used the G3 framework for mapping between natural language and groundings in an environment, and evaluated their method through randomly generated scenarios in simulation. Semantics have also been used to program a robot to perform a task using natural language sentences. Pomarlan \textit{et al.}~\cite{Pomarlan2018} developed a system that converts a linguistic semantic specification (like an instruction to a robot: ``set a table (re-arranging four cups)'') into an executable robot program, using interpretation rules. The resultant robot program or plan can be run in simulation and enables further inference about the plan. Savage \textit{et al.}~\cite{Savage2019} developed a semantic reasoning module for a service robot that interprets natural language by extracting semantic role structures from the input sentence and matching them with known interpretation patterns. Another venue for semantics in Human-Robot interaction is interactive robot learning from demonstration. Niekum \textit{et al.}~\cite{niekum2013incremental} proposed an approach to using demonstrations for learning different behaviors and discovering semantically grounded primitives and incrementally building a finite-state representation of a task. Recently, semantics, powered by deep learning, was used to enable a robot to understand salient events in a human-provided demonstration~\cite{sermanet2016unsupervised} or perform unsupervised learning of the robot's user type from joint-action demonstrations, in order to predict human actions and execute anticipatory actions~\cite{8520627}. Mapping with Human-in-the-loop is another example where semantics and semantic mapping find application. Hemachandra~\textit{et al.}~\cite{Hemachandra2014} presented a semantic mapping algorithm, Semantic Graph (a factor graph approach), that fuses information from natural language descriptions with low-level metric and appearance data, forming a hybrid map (metric, topological, and semantic). \cite{Yang2018} proposed a mapless navigation system based on semantic priors, using reinforcement learning on joint embeddings created from image features, word embeddings, and a spatial and knowledge graph (using a graph convolutional network) to predict the actions. In the context of autonomous navigation and motion planning, one of the desired capabilities of a robot is to actively understand its environment and act accordingly. Beyond the use of active SLAM techniques~\cite{stachniss2004exploration, carlone2010application, carlone2014active} to accurately explore a partially-known environment, a robot also needs to adhere to human-like ``social behavior'' for an enhanced human-robot interaction experience. Semantic reasoning potentially enables robot social awareness when planning motion around humans~\cite{lemaignan2017artificial,sisbot2007human}, expressing socially competent navigation in shared public places. This is typically achieved through crowd flow modeling in different social scenarios and contexts~\cite{kidokoro2015simulation}. Robot interaction can occur not only with humans but also with other robots. Schulz \textit{et al.}~\cite{schulz2011lingodroids} developed a system that enables a pair of robots to interact by autonomously developing a sophisticated language to negotiate spatial tasks. This is achieved through language games that enable the robots to develop a shared lexicon to refer to places, distances, and directions based on their cognitive maps, and was demonstrated on real robots. Another example of robot-robot interaction is the computational model of perspective-taking introduced by Fischer and Demiris~\cite{fischer2019computational}. There, one robot assumes the viewpoint of another robot to understand what that other robot can perceive from this point of view. Such a perspective-taking ability has previously been shown to be of advantage in human-robot interactions~\cite{Fischer2016,breazeal2006using}. \subsubsection{Vision-and-Language Navigation} Vision-and-language navigation (VLN) is a task where an agent attempts to navigate to a goal location in a 3D simulator when given detailed natural language instructions. Anderson \textit{et al.} presented the first VLN task and dataset in \cite{r2r}. Numerous methods have been proposed to address the VLN problem. Most of them employ the CNN-LSTM architecture, with an attention mechanism to first encode instructions and then decode the embedding to a series of actions. Together with the proposing of the VLN task, Anderson \textit{et al.}~\cite{r2r} developed the teacher-forcing and student-forcing training strategy. The former equips the network with a basic ability for navigating using ground truth action at each step, while the latter mimics the test scenarios, where the agent may predict wrong actions, by sampling actions instead of using ground truth actions. The trend of deep learning based methods benefiting from more training data is also true in vision-and-language navigation. To generate more training data, Fried \textit{et al.} \cite{sf} developed a speaker model to synthesize new instructions for randomly selected robot trajectories. Other methods of increasing the training data available have also been proposed: Tan \textit{et al.}~\cite{envdrop} augment the training data by removing objects from the original training data to generate new \textit{unseen} environments. To further enhance the generalization ability, they also train the model using both imitation learning and reinforcement learning, so as to take advantage of both off-policy and on-policy optimization. Predicting future actions is a key component of many approaches, but not all chunks of an instruction are useful for predicting this next action. Ma \textit{et al.} \cite{selfMonitor} use a progress monitor to locate the completed sub-instructions and to focus on those which have the most utility in predicting the next action. Another way to improve navigation success is to equip the agent with backtracking. In \cite{regret}, Ma \textit{et al.} propose treating the navigation process as a graph search problem and predict whether to move forward or roll back to a previous viewpoint. In \cite{fast}, each passed viewpoint is viewed as a goal candidate, and the final decision is the viewpoint with the highest local and global matching score. Most recently, Qi \textit{et al.} \cite{qi2019rerere} presented a dataset of varied and complex robot tasks, described in natural language, in terms of objects visible in a large set of real images. Given an instruction, success requires navigating through a previously-unseen environment to identify an object. This represents a practical challenge, but one that closely reflects one of the core visual problems in robotics. \subsection{Applications} A number of robotics and autonomous platforms employing some degree of semantics can be seen in use today, with a much larger number in use at the research or proof of concept stage. Robotics and autonomous platforms span a wide range of application scenarios including domestic services: house cleaning (iRobot Roomba~\cite{roomba}), lawn mowing (Robomow RS~\cite{robomaw}), pool maintenance (Zodiac VX65 iQ~\cite{poolCleaner}); scientific exploration: underwater in deep sea (AUV Sentry~\cite{auvSentry, kaiser2016design}), planetary rovers (Curiosity~\cite{curiosity, manning2014mars}); hospitals: intelligent transportation (Flexbed~\cite{wang2014intelligent}), socializing with patients~\cite{alves2015social}, surgical procedures (Da Vinci~\cite{davinci, byrn2007three}), and providing care~\cite{hanheide2017and,fattal2019sam}; social interaction (Nao~\cite{Nao}, Pepper~\cite{pepper}, Vector~\cite{vector}); telepresence (Beam~\cite{beam}); hospitality \cite{pinillos2016long}; shopping centers and retail~\cite{kejriwal2015product, kanda2010communication, gross2009toomas}; office environment~\cite{kumar2014tea}; logistics and fulfillment~\cite{huang2015robotics}; last mile delivery (Starship~\cite{starship}); and many others~\cite{roboList}. In the following sections, we discuss the major application areas from the perspective of different autonomous platform types (UAVs, Service Robots, Static Platforms) as well as covering particular application domains (Autonomous Driving, Augmented Reality and Civilian Applications). \subsubsection{Drones and Unmanned Aerial Vehicles (UAVs)} Drones and UAVs represent one of the most resource-constrained robotic platforms, where balancing factors like flight time, payload capacity, cost, power, real-time operation and sensor choice requires careful consideration. As the application and operating scenarios can vary significantly, but are generally more constrained compared to say autonomous vehicles, research with regards to the use of visual semantics on drones is still relatively preliminary. Numerous benchmark datasets have focused on UGVs, leading to significant advancements in research for enabling semantic scene understanding~\cite{geiger2012we, Cordts2016, geyer2020a2d2}. However, the same is not true for UAVs. \cite{du2018unmanned} recently presented a UAV object detection and tracking benchmark that particularly highlights the contrast between the challenges of vision research for UAVs versus UGVs. The primary differences occur due to variations in object density per frame, relative sizes of observed objects, viewpoint, motion and real-time requirements. To further the research efforts in this domain, \cite{zhu2018vision} released a benchmark challenge \textit{VisDrone2018} for object detection and tracking with 2.5 million annotated instances of objects within 180K video frames. \cite{vosselmanuavid} presented UAVid, an urban street scene segmentation dataset, particularly aimed at high-resolution slanted views from low-altitude flights, in contrast to the more common top view-based datasets~\cite{rottensteiner2014results, campos2016processing, debes2014hyperspectral, demir2018deepglobe}. In a similar vein, \cite{nigam2018ensemble} released \textit{AeroScapes}, an aerial-view dataset of 3269 images with dense semantic annotation, captured using a fleet of drones. The scarcity of labeled data has also motivated researchers to explore alternative ways to utilize the existing data and approaches to semantic scene understanding. The authors in~\cite{nigam2018ensemble} used an ensemble approach to semantic segmentation of aerial drone imagery, based on knowledge transfer via progressive fine-tuning through different source domains. Similarly, \cite{benjdira2019unsupervised} explored the use of GANs~\cite{goodfellow2014generative} for unsupervised domain adaptation to improve cross-domain semantic segmentation in aerial imagery. With the availability of better benchmark datasets and tools, there's the potential for advances in semantic scene understanding for UAV applications mirroring those made for road-based vehicles. Currently, UAVs are used in a diverse range of application scenarios that differ in operating environments as well as the end task. \cite{leira2015automatic} demonstrated a Search And Rescue (SAR) system to detect and track objects on ocean surfaces where accessibility by other means is typically impractical. Similarly, natural environments that are prone to disasters like volcanic eruptions, forest fires or landslides can be better accessed by UAVs, which can aid in detecting and assessing such situations~\cite{zheng2017bi}. Nature conservation and wildlife management are also key areas where UAVs can offer a significant practical advantage over other platforms. \cite{van2014nature} presented a nature conservation drone that detects, tracks and counts various animals in the wild. Extending this idea to the use of multiple devices, \cite{rivas2018detection} developed a software platform that enables the use of different multirotors for cattle detection and management, mitigating the need to attach GPS devices to animals. \cite{bondi2018spot} developed Systematic POacher deTector (SPOT) based on drones to spot poachers at night time. Beyond natural environments, UAVs have also been employed in the construction industry for site management and control~\cite{huang2018construction}. Another distinct application area for UAVs is last mile delivery, which is already well on its way from research to commercial deployment~\cite{wing}. As both the end-task and operating environment vary widely, the use of multiple sensors beyond just RGB cameras to achieve the objective is common, for example, the use of thermal cameras~\cite{leira2015automatic, bondi2018spot} and LiDAR~\cite{kellner2019new}. Autonomous UAV navigation will also benefit from advances in semantic understanding of the world. Driven in significant part by advances in the field of deep learning, autonomous navigation is a topic of active exploration in the context of drones and UAVs, especially enabling end-to-end autonomous navigation. \cite{sadeghi2016cad2rl} proposed Collision Avoidance via Deep Reinforcement Learning (CAD$^2$RL) where training is done only using simulated 3D CAD models, demonstrating generalization to real indoor flights. \cite{loquercio2018dronet} developed DroNet that takes as an input a monocular image and outputs the steering angle along with a collision probability. Distinct from~\cite{sadeghi2016cad2rl} and other methods that use synthetic data for training, \cite{loquercio2018dronet} explored the use of ground vehicle driving data from city streets and demonstrated generalization to variations in viewpoint (from high altitude flights) and types of environment (parking lots and corridors). This study in particular shows that there are underlying meaningful semantic concepts that are not specific to a robotic platform or operational domain. Besides using data from simulation or a different application domain for learning, a somewhat uncommon paradigm for learning has been explored in~\cite{gandhi2017learning}, based on real crash flights. The authors sample naive trajectories and crash into random objects (11500 times) to form a crash dataset, which is then used to learn a UAV navigation policy, demonstrating a drone's ability to navigate in an extremely cluttered and dynamic environment. Apart from a completely end-to-end pipeline, modular approaches have also been explored where perception and control are handled separately~\cite{devin2017learning, clavera2017policy, muller2018driving}. Similarly, \cite{loquercio2019deep} demonstrated autonomous navigation for a racing drone via sim-to-real transfer of its CNN training for predicting goal direction using data generated from domain randomization. More recent work in the field of drone navigation includes learning to fly from a single demonstration~\cite{kaufmann2019beauty}, deploying navigation capability on mW-scale nano-UAVs~\cite{palossi201964}, and motion planning based on an opponent's reactions~\cite{spica2020real}. Autonomous UAV navigation requires a high-level understanding of the environment, which can either be learnt via end-to-end training techniques or via modular methods that help to semantically reason about the surroundings. Towards the goal of semantic navigation, \cite{mandel2020towards} employed the Observe-Orient-Decide-Act-loop (OODA-loop) decision-making theory~\cite{boyd1987discourse, boyd2018discourse}, and incorporated semantic information from the environment into the decision making process of a UAV to dynamically adjust its trajectory. A semantic reasoning capability can potentially enhance the performance in the end task of a practical application by adding situational awareness. In this vein, \cite{cavaliere2016towards} proposed to improve object detection and tracking by integrating ontological statements-based semantics in their tracking method for improved awareness of drones in critical situations~\cite{cavaliere2017semantically}. With a similar goal, \cite{jeon2019relationship} leveraged the relationships between objects and defined an ontology to describe the objects surrounding a UAV to better detect a threat situation. Further advances in navigation and scene understanding for UAVs, particularly those based on semantic reasoning, will play a critical role in improving UAV autonomy and broadening the range of applications where deploying drones is feasible. \subsubsection{Service Robots} Much robotics research has been driven by a motivation to develop robots that can provide a range of services to humans. Within each of the application areas, there are several aspects of service robotics that need to be taken into account. Recent review and survey articles have discussed the uses, scope, opportunities, challenges, limitations and future of service robots in various contexts: human-centric approaches~\cite{he2017survey}, navigating alongside humans~\cite{cheng2018autonomous}, cultural influences~\cite{cheng2018autonomous}, needs in healthcare~\cite{vanni2017need}, acceptance in a shopping mall~\cite{niemela2017monitoring}, consumer responses to hotel service robots~\cite{tussyadiah2018consumer}, requirements of the elderly with cognitive impairment~\cite{korchut2017challenges}, uncertainty in natural language instructions~\cite{muthugala2018review}, roles in the hospitality industry~\cite{rosete2020service}, mechanical design~\cite{bakri2019review}, hospitals~\cite{mettler2017service}, social acceptance in different occupational fields~\cite{savela2018social}, welfare services~\cite{aaen2018robots}, restaurant services~\cite{tuomi2019service}, service perception and responsibility attribution~\cite{gracia2020robots}, and planning and reasoning in general-purpose service robots~\cite{walker2019desiderata}. These studies highlight the aspects of service robotics which are not necessarily technical but highly relevant to their effective deployment. A commercially-viable service robot typically requires a hardware design that improves its utility in a range of application scenarios. For example, the modular design of Care-o-bot~\cite{careobot} enables application-specific modifications like replacing one of the arms by a serving tray, or using just its mobile platform for serving, beyond its prescribed use cases in grocery stores, museums or as a butler. Similarly, PR2~\cite{pr2} is capable of performing house chores like cleaning a table and folding a towel, as well as fetching objects. Both these robots are equipped with a sensor suite that enables them to perform autonomous navigation, grasping and manipulation. These competencies are an active area of research which drives continuous improvement in the robotic solutions available. The underlying software platform for PR2 and many other robots is supported by the open-sourced Robot Operating System (ROS)~\cite{ros}, making research studies easier and systematic~\cite{do2018accurate, berenson2012robot}. Beyond ROS, specialized software development kits are typically available for robots to control or access their sensor data as is the case with Spot~\cite{spot}, a new commercially available service robot that can move through trotting in both indoor and outdoor environments, while being capable of climbing stairs, opening doors and fetching a drink. Apart from the hardware designs and underlying operating kernels, in order to complete a task and provide a service, a robot requires advanced perception and control abilities. This is typically achieved by using multiple sensors and performing tasks in a modular fashion. \cite{bellotto2008multisensor} proposed a multi-sensor based human detection and tracking system and demonstrated its portability on different robotic platforms using a Pioneer and Scitos robot. \cite{kumar2014tea} presented a tea-serving application using P3DX robot in an office environment, where an overall environment awareness was achieved by developing individual competencies in isolation like line following, obstacle avoidance, empty tray detection, approaching-hand detection and person following. Recently, aiming for precision agriculture, \cite{kim2020an} presented an intelligent pesticide spraying robot that semantically segments the fruit trees that require spraying. Using semantic reasoning, perception, control and interaction abilities can be further improved. \cite{Wei2012} demonstrated smart wheelchair navigation using semantic maps, emphasizing enhanced safety, comfort, and obedience due to the use of semantics. \cite{niekum2013incremental} presented a semantically-grounded learning-from-demonstration approach for a furniture assembly task using a PR2. \cite{Savage2019} developed a semantic-reasoning based method for interpretation of voice commands for improved interaction between a service robot and humans. \cite{Ramirez-Amaro2015b, Ramirez-Amaro2017, Ramirez-Amaro2019a} demonstrated the use of semantic representations for human/robot activity understanding using humanoid and industrial robots. More recently, \cite{zeng2020semantic} proposed Semantic Linking Maps (SLiM) that exploit common spatial relations between objects to actively search for an object based on probabilistic semantic reasoning. Many service robots that work for or alongside humans require the ability to extract, represent and share semantic knowledge with their users or co-workers to perform these services intelligently and sometimes jointly. Semantic knowledge representation in the form of semantic maps enriches the metric and/or topological spatial representation that these robots traditionally carry. Similarly, semantically reasoning about the service task will close the gap between the way humans and robots understand their environment, which then facilitates more natural robot-user communication. \subsubsection{Static Platforms} \label{sec:disc-staticPlatforms} Other than robotic platforms, a number of practical applications also involve static platforms based on perception sensors. We briefly cover these platforms here because it's likely that in future many robotic systems will operate in a ``shared perception'' environment where their onboard sensing is extended by static sensing systems. Many of the capabilities initially developed in a surveillance context, especially sophisticated scene understanding driven by semantics, are also likely to be relevant as these capabilities are ported into robotic platforms. Visual surveillance is one such example. Video surveillance via Closed-Circuit TeleVision (CCTV) has long been used around the world, with millions of cameras installed. Recent surveys have highlighted the diverse use-cases of visual surveillance and its research advances~\cite{sharma2019visual, jones2017visual, bouwmans2019natural, bouchrika2018survey, kumaran2019anomaly, olatunji2019video, singh2018applications, tripathi2018suspicious}. The application areas for visual surveillance are vast and pose unique challenges depending on the task at hand, many of which are relevant to robotics. \cite{bouwmans2019natural} highlighted the use of visual surveillance in natural environments, for example, studying social behavior of insects in a group~\cite{knauer12005application}, analyzing climate impact based on interactions between natural beings~\cite{dickinson2010automated}, behavior adaptability under tough environmental conditions~\cite{spampinato2014texton} and inspiring robots to mimic locomotion of certain animal species~\cite{iwatani2016position}. The authors also discussed the methods and challenges of background subtraction, often the first step in the process, particularly when tracking a moving object under challenging conditions like those posed by a marine environment. \cite{bouwmans2019human} presented the applications and challenges of visual surveillance of human activities. The authors covered a wide range of uncontrolled environment scenarios: traffic flow monitoring~\cite{sarkar2020microscopic}, detecting traffic incidents~\cite{monteiro2008robust} and anomalies~\cite{kumaran2019anomaly}, vehicle parking management~\cite{cho2016automatic}, safety operations at public places like train stations~\cite{tarrit2018vanishing} and airports~\cite{bouchrika2016towards}, maritime administration~\cite{hu2019single} and retail store monitoring~\cite{rashmi2018rule}. As with the natural environments, monitoring human activities in man-made environments also poses similar challenges including background subtraction when tracking a moving object. Furthermore, as human activities can be unpredictable and have more serious implications for false negatives (not being able to detect an incident), visual surveillance in this particular context demands particularly robust and high performance techniques. Irrespective of the operating environment, the key enablers of a visual surveillance system are the fundamental abilities to holistically and continuously understand the visual observations. These basic abilities are major areas of research and directly impact the performance of the surveillance system. Research includes gait recognition~\cite{bouchrika2018survey, khan2017gait}, person re-identification~\cite{zheng2016mars, xu2018attention}, face recognition~\cite{rao2017attention, masi2018deep, sharif2017face}, single-object tracking~\cite{kristan2018sixth}, multi-object tracking~\cite{milan2016mot16, gaidon2016virtual, garg2015hierarchical} especially in dense crowded scenes~\cite{dendorfer2020mot20}, human activity recognition~\cite{tripathi2018suspicious}, tracking across non-intersecting cameras~\cite{bouchrika2016towards}, object detection especially in the context of abandonment and removal~\cite{tripathi2019abandoned} and incorporating contextual knowledge~\cite{rashmi2018rule}. Many of these capabilities are also critical to robotic platforms, especially as they operate in human-rich environments. The fundamental abilities required for visual surveillance and the challenges associated with them together dictate the need for better approaches that are based on semantic reasoning. The current solutions tend to address challenges that are often specific to the operating environment and the type of object being tracked. A more generalizable solution would require semantic scene understanding which can either be inferred from the observed scene or through the use of knowledge databases. With semantic reasoning, the fundamental task of detecting and tracking an entity of interest can likely be performed in a more robust and generalized manner. \subsubsection{Autonomous Vehicles} Industry has been largely responsible for increased research activity in the autonomous vehicle space, as evidenced by an increasing number of surveys and reviews dedicated to autonomous driving. Autonomous driving is a great test case for semantics, because it has rapidly become clear that classical robotics techniques, like SLAM, are clearly insufficient \textit{by themselves} for enabling autonomous driving, and that a richer understanding of the environment is almost certainly required. Recently, \cite{feng2020deep} reviewed \textit{multi-modal} object detection and semantic segmentation for autonomous driving, describing various methods, datasets and on-board sensor suites while highlighting associated challenges. \cite{arnold2019survey} surveyed 3D object detection methods for autonomous driving applications. \cite{grigorescu2019survey} presented a survey of deep learning techniques for autonomous driving. \cite{yin2017use} reviewed the available datasets for self-driving cars. \cite{janai2017computer} reviewed problems, datasets and state-of-the-art computer vision methods for autonomous vehicles and \cite{bengler2014three} reviewed driver-assistance systems. The tremendous push for autonomous cars from different companies has led to the availability of enormous labeled datasets captured from fleets of vehicles mounted with many sensors~\cite{caesar2020nuscenes, geyer2020a2d2, sun2020scalability}. Both industrial and academic researchers have invested significant effort in understanding and solving the challenges posed in developing high levels of autonomous driving. Scene understanding based on benchmark datasets has its limitations as it does not account for a number of scenarios which an autonomous robot might encounter in real-world. For example, detecting a ``stop sign'' may not be trivial due to occlusions, weather and lighting conditions, infrastructural variations, special sub-categories and temporary road blocks where humans carry the stop signs~\cite{ytAndrej2020TeslaAI, p1007michael2020}. One of the practical solutions to such object recognition problems is \textit{active learning} where approximate detectors can be used to automatically sample more data for less confident predictions, especially under a map-vision disagreement, to train better classifiers or handle special cases, as adopted by Tesla, Inc.~\cite{ytAndrej2020TeslaAI}. The Tesla talk~\cite{ytAndrej2020TeslaAI} also highlights how general evaluation methods are supplemented by curated unit tests for measuring the scene understanding capability of an autonomous car before deploying an updated solution. Furthermore, semantic scene understanding for autonomous driving is at times limited by differences in road infrastructure and traffic rules across different geographies, for example, left- versus right-lane driving and differences in positioning of traffic lights near intersections. Therefore, learning general trends via deep learning often needs to be complemented by incorporating prior knowledge in the algorithm implementation and sensor specification~\cite{articleBoschAD}. Given the range of challenges in enabling autonomous driving, some focus has shifted to task-specific and highly-engineered solutions. Such approaches include multi-modal object detection (Uber)~\cite{liang2018deep} and semantic segmentation (Bosch)~\cite{feng2020deep}, Pseudo-LiDAR~\cite{wang2019pseudo} based 3D object detection (Huawei)~\cite{vianney2019refinedmpl}, multi-view 3D object detection (Baidu)~\cite{chen2017multi}, sequential fusion (nuTonomy)~\cite{vora2019pointpainting}, monocular 3D object detection~\cite{chen2016monocular}, and learning near-accident driving policies (Toyota)~\cite{cao2020reinforcement} . In particular, application-specific biases or assumptions have proven to be of benefit. \cite{chen2016monocular} proposed 3D object detection from a single monocular image in the context of autonomous driving, leveraging various priors suited to the application, for example, size, shape and location of objects, ground plane context and semantic class selection. \cite{yi2020segvoxelnet} presented SegVoxelNet, which utilizes semantic and depth context for 3D object detection using LiDAR point clouds to better identify ambiguous vehicles on road. Researchers are making good progress towards solving the more specific and narrow problems within the autonomous driving field~\cite{chen2016monocular, chen20153d, ku2018joint, zeng2018rt3d, li20173d, wang2012could}. Autonomous driving and driving-assistance systems need to solve a variety of fundamental and high-level tasks. In order to make sense of raw sensor data, continuous effort is being made to improve semantic scene understanding using various techniques including multi-task fusion~\cite{liang2019multi}, multi-sensor fusion~\cite{liang2018deep, liang2019multi}, panoptic segmentation~\cite{kirillov2019panoptic, xiong2019upsnet} and open-set instance segmentation~\cite{wong2020identifying}. With enhanced semantic reasoning, higher-level tasks for autonomous driving can be better addressed, for example, motion planning~\cite{zeng2019end, sadat2019jointly}, 3D object tracking~\cite{frossard2018end}, multi-object tracking~\cite{dendorfer2020mot20}, pedestrian behaviour prediction~\cite{jain2019discrete}, long-range human trajectory prediction~\cite{mangalam2020not}, turn signal-based driver intention prediction~\cite{frossard2019deepsignals}, predicting a pedestrian's intention to cross~\cite{liu2020spatiotemporal} and intention prediction in the form of trajectory regression and high-level actions~\cite{casas2018intentnet}. Furthermore, for real-time operations, efficient methods are being developed for semantic segmentation~\cite{oh2020segmenting, zhang2018efficient}, 3D object detection~\cite{yang2018pixor, luo2018fast}, online multi-sensor calibration~\cite{zhuo2020nline}, semantic stereo matching~\cite{Dovesi2019} and object tracking~\cite{luo2018fast}. As the current systems rely on high-definition maps for localization and detecting road infrastructure and fixed objects, compressing such maps for efficient operations is also being explored~\cite{wei2019learning, barsan2018learning}. Semantic mapping, particularly suited to autonomous driving on roads, is being explored at deeper levels involving lane detection in complex scenarios~\cite{bai2018deep}, road centerline detection~\cite{mattyus2018matching, wang2016torontocity}, lane boundary estimation~\cite{homayounfar2018hierarchical}, complex lane topology estimation~\cite{homayounfar2019dagmapper}, drivable road boundary extraction~\cite{liang2019convolutional}, crosswalk drawing~\cite{liang2018end}, and aerial view-based road network estimation~\cite{mattyus2017deeproadmapper}. Recent research has also demonstrated that using semantic maps can improve performance at tasks like object detection~\cite{yang2018hdnet} and localization~\cite{ma2019exploiting}. Autonomous driving is a challenging task and one that is likely to rely heavily on vehicles having a deep and accurate understanding of how the world around them functions. As research in this field continues it will be interesting to see how far progress is made adopting a road-driving-specific focus, versus a broader understanding of the world, and how many of the insights gained are then relevant to other robotic domains like service robotics and drones. Will semantic advances for autonomous vehicles provide the final piece of the puzzle to safely and widely deployable highly autonomous on-road vehicles? And will these advances be of high relevance to other robotic domains, or will there be domain-specific aspects of how semantics are learnt and used? \subsubsection{Civilian applications} A number of vision and robotics based solutions have been developed with primary applications in civilian society. This includes visual surveillance, robotic search and rescue operations, social interactions, and disaster management. Beyond static surveillance, discussed in the Subsection~\ref{sec:disc-staticPlatforms}, visual surveillance based on moving cameras is also becoming more common~\cite{yazdi2018new}. This not only increases the scope of surveillance applications but is also now more feasible due to the availability of better hardware and software technologies. This includes body-worn cameras of police or defence personnel~\cite{stoughton2017police} and crowd monitoring using drones or ground robots. The advanced sensing capability and maneuverability along with low cost and size makes UAVs a great choice for a standalone surveillance system~\cite{saeed2017argus}, although their effect on privacy and civil liberty remains an active topic of discussion~\cite{bracken2016domestic}. Visual surveillance using UAVs has been explored in various contexts including change detection~\cite{mesquita2019fully}, scene classification for disaster detection~\cite{zheng2017bi}, construction site management~\cite{huang2018construction}, and border patrol~\cite{minaeian2016effective}. Similarly, ground robots (UGVs) have also been used for indoor~\cite{saad2016room} and outdoor surveillance~\cite{meghana2017design}. \cite{yazdi2018new} highlighted some of the key challenges of visual surveillance based on moving cameras, including dealing with abrupt motion variations, occlusions, power and compute time constraints and increased background complexity. Apart from surveillance, another important class of civilian applications is in disaster and crisis management. \cite{kostavelis2017robots} reviewed the use of robots in this context. A recent example is the last mile delivery operations run by Starship Technologies~\cite{starship} during the COVID-19 pandemic. Similarly, airborne deliveries by Wing~\cite{wing} and other such platforms can help in providing critical supplies during floods, landslides or bushfires, where ground accessibility is poor or non-existent. For operation in disaster situations, remote teleoperation is still a primary control mechanism - thus mitigating its corresponding challenges is also important. In this vein, \cite{fuchida2018arbitrary} explored the use of arbitrary viewpoints to mitigate blind spots for improved teleoperation of a mobile robot. Beyond vision-based sensing, \cite{asokan2016armatron} used ARMatron, a wearable glove as a gesture recognition and control device to better communicate with a remote robot. Furthermore, disaster management scenarios also require better communication protocols for robots to avoid system failure. For example, a robot-drone-fog device team may communicate by creating an ad-hoc network in a search and rescue mission~\cite{dey2017semantic}. Finally, sensor fusion is also a critical requirement for many such tasks, as demonstrated by~\cite{lee2016drone} for robot-assisted victim search. The end goals for most robotic applications require both \textit{detection} and \textit{action} processes to work in tandem. Robots need to have robust means of understanding their environment, and that understanding has to be consistently verified as the robot acts. As also discussed previously, situational awareness can be attained by semantic reasoning~\cite{cavaliere2017semantically, jeon2019relationship}. Furthermore, semantic understanding of the robot's surroundings also enhances the possibilities for interacting with those surroundings, including with humans. \subsubsection{Augmented Reality} Over the past decade, Augmented Reality (AR) applications have become a relatively common phenomenon. Augmented reality is also highly relevant to robotics and covered here because many of the capabilities - such as localization - are shared across both areas, and both rely on an enhanced understanding of the environment that moves beyond simple geometry. \cite{billinghurst2015survey} recently reviewed AR in depth, covering its various components ranging from tracking and display technologies to design, interaction, and evaluation methods, while also highlighting future research directions. Other recent surveys and reviews include a summary of major milestones in \textit{mobile} AR since 1968~\cite{arth2015history}; opportunities and challenges facing AR~\cite{azuma2016most, van2010survey}; AR trends in education~\cite{bacca2014augmented} and browsing~\cite{grubert2011augmented}; AR in the medical area including developments and challenges~\cite{chen2017recent}, radiotherapy~\cite{cosentino2014overview}, image-guided surgery~\cite{kersten2013state}, neurosurgery~\cite{meola2017augmented}, endoscopic sugery~\cite{wang2016visualization}, laproscopic surgery~\cite{bernhardt2017status}, and health education~\cite{monkman2015see, zhu2014augmented}; and general trends in AR research spanning from 2008 to 2018~\cite{kim2018revisiting}, following a previous decade-span survey~\cite{zhou2008trends} and other older surveys~\cite{azuma2001recent, azuma1997survey}. As noted in~\cite{billinghurst2015survey}, earlier attempts at developing an AR prototype date back to 1968~\cite{sutherland1968head} and the current widespread use can be be witnessed in games, education and the marketing industry. While some of the initial work in the field of AR had been primarily based on sensors like gyroscopes, GPS, and magnetic compasses~\cite{azuma1999motion, feiner1997touring, baillot2001authoring, hollerer1999exploring, piekarski2001tinmith, thomas1998wearable, satoh2001townwear}, vision-based localization has gradually become one of the key areas of research focus, in order to achieve high accuracy and a more immersive experience~\cite{behringer1999registration, ribo2002hybrid, vacchetti2004combining, klein2003robust, klein2004sensor, reitmayr2006going}. With visual SLAM and high-level scene understanding strongly tied to AR, the latter has long been a part of the research motivation for the vision and robotics research community. Real-time dense visual SLAM methods, for example, KinectFusion~\cite{newcombe11kinectfusion, izadi2011kinectfusion} paved the way for accurate surface-based reconstruction, enabling more immersive AR experiences in real-time. Doing away with non-parametric representations~\cite{newcombe11kinectfusion} by instead using semantics in the form of known 3D object models, SLAM++~\cite{Salas-Moreno2013} demonstrated a context-aware AR application using an object-based SLAM pipeline, where virtual characters completed the task of path finding, obstacle avoidance, and sitting on real-world chairs. In subsequent work~\cite{salas2014dense}, the authors developed a real-time dense planar SLAM system and demonstrated its use in augmenting planar surfaces, for example, replacing carpets and styles on the floor and overlaying a Facebook ``wall'' web page on a real wall. Further to that work, \cite{whelan2016elasticfusion} proposed ElasticFusion: a surfels-based map-centric approach to real-time dense visual SLAM and light source detection, leading to a more realistic augmented reality rendering. The application areas of AR are vast, for example, in education: teaching electromagnetism~\cite{ibanez2014experimenting}; in e-commerce: \textit{Webcam Social Shopper}~\cite{webcamSocialShopper}, a virtual dressing room software and IKEA's virtual placement AR system~\cite{ikea}; in retail stores: \textit{Magic Mirror}~\cite{magicMirror} by Charlotte Tilbury; in games: PokemonGo's popular pokemon interaction~\cite{pokemongo}; in navigation: \textit{Live View} by Google Maps~\cite{googleLiveView}; and in medical: VeinViewer, a subsurface structure visualizer~\cite{zeman2011projection}, TRAVEE, an augmented feedback system for neuromotor rehabilitation~\cite{caraiman2015architectural}, PalpSim, a needle insertion training system~\cite{coles2011integrating}, training for planning tumour resection~\cite{abhari2014training} and 3D intraoperative imaging and instrument navigation~\cite{elmi2016surgical}. Image/3D registration is one of the critical components for enabling an accurate AR application. In medical procedures, this task is difficult due to a limited field-of-view vision, rapid motion, organ deformation, lack of sufficient texture, occlusion, clutter, and the inability to add artificial markers. Visual SLAM techniques which are primarily aimed at autonomous navigation for mobile robots typically make assumptions that limit their transferability to other domains, leaving significant research to be done in medical applications~\cite{marmol2019dense, chen2018slam, chen2017real}. In an attempt to further advance this technology, a number of software platforms like ARToolKit~\cite{kato1999marker, artoolkitx}, Vuforia~\cite{vuforia}, ARCore~\cite{arcore} and EasyAR~\cite{easyar} have been developed that help in rapidly enabling mobile AR applications. Head-mounted display devices, for example, optical see-through devices like Google Glass~\cite{googleGlass} and HoloLens~\cite{hololens} are relatively mature AR devices in terms of a combined hardware and software solution. Such technology typically demands robust, accurate and real-time semantic scene understanding. Like autonomous vehicles, much progress has been made by making environment-specific scope assumptions. \subsection{Critical Upcoming Enhancers} Current capabilities in areas like scene understanding are in part due to advances that have occurred in parallel to research developments, for example, better hardware that led to the use of GPUs and the availability of large-scale datasets. Similarly, further progress in semantic mapping and representations will rely on some of the upcoming enablers and enhancers that will facilitate the development of systems capable of high-level semantic reasoning. These enablers include better computational resources and architectures at both hardware and software level; effective and more common usage of knowledge databases and the ability to better leverage the diverse range of existing sensor data; advances in the field of online, networked and cloud robotics and Internet of Things (IoT); and novel mechanisms for enabling human-robot interaction involving uncommon sensing and engaging capabilities. These aforementioned technologies are active areas of research and in the following sections, we highlight how they have been incorporated or potentially could be integrated in robotics to enable semantic reasoning, ultimately leading to more scalable, sophisticated and robust robotic operations. \subsubsection{Computational Resources and Architectures} The growing computational needs of deep learning-based techniques, including those developed for semantic scene understanding, have led to rapid development of improved hardware and computational resources. Notably, GPUs continue to advance, with recent hardware changes being increasingly focused on facilitating deep learning and related techniques, rather than just catering to the traditional consumer gaming, media production and modelling users. Key performance properties relevant to deep learning include memory bandwidth, total memory capacity, clock frequency, and architectural considerations that improve typical operations like inference. All these properties continue to advance rapidly from year to year. \cite{davison2018futuremapping} highlighted the gap between the performance requirements of embodied devices and their practical constraints, indicating the need for co-design of algorithms, processors and sensors. The high compute requirements of visual SLAM and 3D reconstruction algorithms often make extensive evaluation difficult, especially for typical university research labs, so evaluation is often limited to qualitative visualizations and accuracy estimation on a few datasets. This trend deters the uncovering of design choices at algorithm level that could potentially lead to better trade-offs between accuracy, compute time, power consumption and the quality of output. Hence, better design space exploration strategies are continuously being explored that involve both hardware and software, particularly taking into account the latter's low-level design~\cite{zia2016comparative, bodin2016integrating, nardi2017algorithmic, saeedi2018navigating, nardi2019practical}. When optimizing for computational and power performance, data communication overheads (sensor to processor and processor-memory) play a major role by adding latency. \cite{dudek2005general} introduced a processor-per-pixel arrangement-based vision chip~\cite{moini1999vision} for low-level image processing tasks which are inherently pixel-parallel in nature. Such vision chips ensure that data is processed adjacent to the sensor, thus reducing data transfer costs. These vision chips belong to the class of Focal-Plane Sensor-Processor (FPSP) chips~\cite{zarandy2011focal}. For example, the SCAMP-5 vision chip~\cite{carey2013low} operates on image-wide register arrays enabling data (full image) transfer from sensor to processor array in one clock cycle (100 ns), delivering 655 GOPS at 1.2 W power consumption~\cite{martel2016vision}. Recently, \cite{wong2018analog} demonstrated the use of this chip with a novel energy-efficient CNN, resulting in significant gains in compute time (85\%) and energy (84\%) efficiency, while achieving high accuracy (90\%) at a very high frame rate (3000 fps) for a handwritten digit recognition task. Besides designing FPSP chips, neuroscience-driven vision chips~\cite{mead1990neuromorphic, aizawa1999computational} and the use of Field Programmable Gate Arrays (FPGAs) is increasingly becoming popular as a means to accelerate deep learning-based applications, as has been reviewed recently~\cite{ruiz2019field, mittal2020survey, blaiech2019survey, wang2018survey, shawahna2018fpga, venieris2018toolflows}. Neuromorphic vision chips have been discussed in detail in ~\cite{koch1996neuromorphic} and more recently in ~\cite{wu2018neuromorphic}, where the latter discussed both frame-driven and event-driven vision chips. \cite{schuman2017survey} comprehensively reviewed the neuromorphic computers, devices and model architectures that at some level model neuroscience to solve challenging machine learning problems. Neuromorphic computing provides opportunities to implement neural networks-based applications, particularly those based on Spiking Neural Networks (SNNs), directly in the hardware, thus offering significant advantages in terms of power, compute time and storage footprint. This hardware is typically implemented as FPGAs~\cite{tapiador2018event} or an Application-Specific Integrated Circuit (ASIC)~\cite{cruz2012energy}. Robotic applications, especially those requiring autonomous navigation competencies, have been explored with the use of spiking neural networks~\cite{tang2019spiking, huang2019flyintel, beyeler2015gpu, stewart2016serendipitous}. Furthermore, existing CNNs can be converted into SNNs and mapped to spike-based hardware architectures while retaining their original accuracy levels, as demonstrated on the object recognition task in~\cite{sengupta2019going, xing2019homeostasis, cao2015spiking}. This opens up opportunities to better leverage advances in these hardware platforms while also motivating researchers to bridge the gap between the state of the art in learning using ANNs and SNNs. \subsubsection{Knowledge Repositories and Databases} The availability of knowledge repositories, datasets and benchmarks has always proven to be an accelerator of research in both the computer vision and robotics community. While knowledge databases help in providing contextual information and designing semantically-informed systems, sensor data in the form of images, videos, depth and inertia help in developing data-driven learning-based systems. With deep learning as such an integral component of most semantics-related research, it has become even more important to obtain both accurate and large-scale labeled data to enable \textit{deep} and \textit{supervised} learning, for example, in the case of object detection and semantic segmentation. The recent focus has also been on creating equivalent benchmark datasets for 3D semantic scene understanding. In Table~\ref{tab:datasets}, we list a sampling of datasets that are targeted at enabling semantic understanding by solving diverse tasks, for example, object detection in 2D~\cite{Song2015, neuhold2017mapillary} and 3D~\cite{Hua2016, geyer2020a2d2}, semantic segmentation in 2D~\cite{Cordts2016} and 3D~\cite{Silberman2012, chang2017matterport3d}, semantic place categorization~\cite{Zhou2018}, robotic manipulation~\cite{Aksoy2015a}, road semantics~\cite{wang2016torontocity}, multi-spectral semantics~\cite{Valada2017}, UAV-view semantics~\cite{nigam2018ensemble}, 3D object shapes~\cite{wu20153d}, multi-object tracking~\cite{gaidon2016virtual}, pedestrian intention prediction~\cite{liu2020spatiotemporal}, pedestrian locomotion forecasting~\cite{mangalam2020disentangling}, collision-free space detection (drivable vs non-drivable)~\cite{fan2020sne}, Near-InfraRed segmentation~\cite{pandey2020unsupervised}, and semantic mapping~\cite{Ruiz-Sarmiento2017}. This list of datasets is by no means comprehensive, and more details can be found in recent dataset review articles~\cite{feng2020deep, lateef2019survey, yu2018methods, yin2017use} and online~\cite{awesomeSemanticSegmentation}, although any single source does not provide a complete list, emphasizing the disconnect between the use of semantics for different tasks and applications. Table~\ref{tab:datasets} mainly highlights the diversity in semantic understanding tasks, which are typically related to each other but often evaluated in isolation. It suggests that any future general semantic capability for robots might also require a more unified approach to the development and use of these datasets~\cite{wang2016torontocity}. \begin{table*} \centering \caption{Diversity in Datasets with Semantic Annotations} \begin{tabular}{lp{0.3\textwidth}p{0.3\textwidth}} \toprule \textbf{Name} & \textbf{Annotation Type} & \textbf{Additional Information}\\ \midrule NYUv2 (2012)~\cite{Silberman2012} & Dense RGB-D and object instance-wise & 1449 aligned RGB-D pairs from 464 indoor scene sequences \\ RueMonge (2014)~\cite{Riemenschneider2014} & Pixel-wise labels along with a 3D Mesh & 1 million 3D points outdoor forming several Haussmanian-style facades and 8 semantic classes. \\ MANIAC (2015)~\cite{Aksoy2015a} & Semantic annotations of manipulation activities & 8 unique activities, manipulating 30 objects \\ SUN RGB-D (2015)~\cite{Song2015} & Polygons and bounding boxes with object orientations (RGB-D) and scene category & 10,000 indoor RGB-D images with 146,617 2D polygons and 58,657 3D bounding boxes. \\ SUNCG (2016)~\cite{Song2016} & Volumetric and object-level labels for synthetic indoor scenes & 45,000 scenes with realistic room and furniture layouts. \\ SceneNN (2016)~\cite{Hua2016} & Scene meshes labeled per-vertex and per-pixel with object poses and bounding boxes & 100 indoor scenes \\ Cityscapes (2016)~\cite{Cordts2016} & Pixel- and instance-wise labels & 5,000 fine and 20,000 coarse annotations for 30 semantic classes from outdoor scenes across 50 cities. \\ ScanNet (2017)~\cite{Dai2017} & 3D camera poses and dense and object instance-level labeled surface reconstructions (RGB-D) & 2.5M views in 1513 indoor scene sequences \\ SEMANTIC3D.NET (2017)~\cite{Hackel2017} & Labeled 3D point clouds & 4 billion manually labeled points and 8 semantic classes from urban outdoor scenes. \\ Freiburg Forest (2017)~\cite{Valada2017} & Multispectral and multimodal pixel-level labels & Multiple 4.7 km traverses with 6 outdoor semantic classes \\ Stanford 2D-3D-Semantics (2017)~\cite{Armeni2017} & Pixel- and instance-level labels with 3D meshes and point clouds (RGB-D) & Approximately 70,000 images and 695 million points from large-scale indoor spaces (6,000 m$^2$) \\ Places (2017)~\cite{Zhou2018} & Place-level labels & 10 million images with 400+ semantic place categories. \\ Robot@Home (2017)~\cite{Ruiz-Sarmiento2017} & Room-, object- and point-level labels of 3D indoor reconstructions (RGB-D) & 36 rooms (8 categories) and 1900 objects (57 categories) observed in 69,000 images captured from traverses of a mobile robot at home. \\ PrOD (2020)~\cite{hall2020probabilistic} & Pixel- and object-level labels and bounding boxes for synthetic images & Indoor image sequences captured from multiple robots in a domestic environment.\\ A2D2 (2020)~\cite{geyer2020a2d2} & Pixel- and object-level labels and 3D bounding boxes (RGB-D) & 41,280 frames with 38 semantic classes captured from multiple outdoor traverses.\\ \bottomrule \end{tabular} \label{tab:datasets} \end{table*} Semantic-based approaches typically rely on pre-learnt material from carefully curated datasets. As the range, size and variety of these datasets improves, so likely will the outcomes. An alternative means of incorporating prior information is to make use of a pre-defined ontology and common knowledge with the help of knowledge graphs~\cite{wang2017knowledge, paulheim2017knowledge} and ontology languages~\cite{mcguinness2004owl, martin2004owl, janowicz2019sosa}. In the context of robotics, several researchers have explored different ways of encoding the relevant knowledge and proposed a corresponding ontology. As highlighted in~\cite{prestes2013towards}, these ontologies have been applied in different ways: path planning and navigation~\cite{schlenoff2003using, habib1993map, balakirsky2004knowledge}, describing an environment~\cite{chella2002modeling}, task analysis for autonomous vehicles~\cite{barbera2004task}, task-oriented conceptualization~\cite{wood2004representation}, as meta-knowledge for learning from heuristics of a system~\cite{epstein2004metaknowledge}, policies to govern behavior~\cite{jung2004ontology}, describing robots and their capabilities~\cite{schlenoff2005robot}, control architecture concepts~\cite{dhouib2011control}, and characterizing sub-domains within robotics~\cite{hallam2006ontology}. Furthermore, given the ways of representing knowledge~\cite{davis1993knowledge, wood2012review, fischer2018dac}, its management~\cite{lemaignan2010oro} and processing~\cite{tenorth2009knowrob} frameworks have also been explored. Recently, \cite{gayathri2018ontology} reviewed ontology-based knowledge representations for robotic path planning. The use of knowledge representation and ontology has been explored in semantic mapping for robots. \cite{galindo2005multi} proposed an ``anchoring'' process to link the spatial and semantic information hierarchies for a semantic map representation. For representing knowledge, authors used the NeoClassic~\cite{patel1996neoclassic} system to encode the semantic (conceptual) information hierarchy. \cite{zender2008conceptual} presented a hierarchical map representation where the highest level of abstraction forms the conceptual layer, representing knowledge in the form of abstract concepts (TBox with terminological knowledge) and instances of such concepts (ABox with assertion knowledge). Using the OWL-DL ontology of an indoor office environment, the conceptual map is defined using taxonomies of room types and objects found therein in the form of \textit{is-a} and \textit{has-a} relations. Beyond considering just the objects in the space, \cite{nuchter2008towards} implemented a constrained network solver using Prolog to encode the environment and in particular, the relationships between different planes (walls, floor, ceiling) as being parallel or orthogonal. Using the knowledge processing system, KnowRob~\cite{tenorth2009knowrob}, \cite{tenorth2010knowrob} presented a semantic mapping system, KnowRob-Map, that links objects and spatial information with two sources of knowledge: \textit{encyclopedic} knowledge, inspired by OpenCyc~\cite{lenat1995cyc}, comprising object classes and their inter-relation hierarchies and \textit{common-sense} knowledge, based on Open Mind Indoor Common Sense (OMICS)~\cite{gupta2004common}, comprising action-related knowledge about everyday objects. Riazuelo \textit{et al}.~\cite{Riazuelo2015} demonstrated the benefits of combining SLAM and knowledge-based reasoning through RoboEarth~\cite{mohanarajah2014rapyuta}, a semantic mapping system. In the proposed system, the RoboEarth knowledge base stores ``action recipes'' (hardware- and environment-agnostic abstract descriptions of a task), sets of object models, and robots' models in Semantic Robot Description Language (SRDL)~\cite{kunze2011towards}. For a requested action recipe (e.g. exploration), based on the robot's capabilities, an execution plan tailored to the robot is generated on the cloud. For plan execution, the robot downloads a set of object models expected in its environment for building a semantic map, which can be uploaded to RoboEarth for future use by other robots. Using the proposed system, the authors demonstrated two tasks: semantic mapping of a new environment and novel object searching based on semantic reasoning. Addressing the gap between the use of a pre-defined knowledge database and the ability to gain new knowledge, \cite{ruiz2017building} presented the concept of a ``multiversal'' semantic map based on probabilistic symbol grounding. This approach enables reasoning through multiple ontological interpretations of a robot's workspace. \cite{kulvicius2013semantic} used additional linguistic cues for text-based image retrieval, showcasing the potential of using knowledge databases to improve retrieval accuracy. Beyond entity-level knowledge graphs, \cite{alemu2020healthaid} proposed HealthAidKB, a knowledge base with 71000 task frames structured hierarchically and categorically, mainly focused on procedural knowledge for queries that require a step-by-step solution to a problem at hand. Using Probabilistic Action Templates (PATs)~\cite{leidner2012things, younes2004ppddl1}, \cite{bauer2020probabilistic} developed a probabilistic effect prediction method based on semantic knowledge and physical simulation to predict a robot's action success. \cite{kulvicius2013semantic, Riazuelo2015} and a body of similar work~\cite{tenorth2011web, beetz2011robotic, tamosiunaite2011generalizing} attempt to achieve generalization and solve the open-set problem that persists especially in visual perception systems. Using prior knowledge and learning from various new knowledge sources is likely to be key to further advances in the semantic reasoning capability of robots. \subsubsection{Online and the Cloud} Cloud robotics~\cite{kuffner2010cloud} or online~\cite{goldberg2002beyond} and networked~\cite{goldberg1995desktop, mckee2008networked} robotics mainly refers to the use of internet or local communication networks to share resources and computation between multiple robots or applications. It is also closely related to the concept of Internet-of-Things (IoT)~\cite{davidson2004open, ashton2009internet, atzori2010internet}. Goldberg and Kehoe~\cite{goldberg2013cloud} reviewed five different ways in which cloud robotics and automation can be put to use: shared access to annotated sensor data, on-demand massively-parallel computational support, sharing of trial outcomes for collective learning, provision of open-source and open-access code, data, and hardware design, and on-demand human guidance for task support - all areas of relevance to semantics. Furthermore, \cite{kehoe2015survey} presented a concept of Robotics and Automation as a Service (RAaaS) that combines the ideas of Infrastructure as a Service (IaaS), Software as a Service (Saas) and Platform as a Service (PaaS). Wan \textit{et al}.~\cite{wan2016cloud} reviewed the development process of cloud robotics and its potential value in different applications: SLAM, navigation and grasping. \cite{hu2012cloud} designed a cloud robotics architecture comprised of two sub-systems: a communication framework (machine-to-machine and machine-to-cloud) and an elastic computing architecture. The latter is defined using three different models: peer-based, proxy-based and clone-based, where their suitability to a particular robotic application is based on key characteristics like robustness in network connections, interoperability and flexibility for mobility within the network. The authors also highlight the key challenges for such a cloud system in terms of computation, communication, optimization and security. Under the constraints of limited communication, \cite{carlone2010rao} presented a multi-robot SLAM system based on Rao-Blackwellized Particle Filters~\cite{doucet2000rao} that required only a small amount of data to be exchanged across robots. A number of recent articles have reviewed the current trends in cloud robotics~\cite{chowdhury2020approach, saha2018comprehensive, chen2018study, koubaa2019service, chinchali2019network, fosch2019cloud, botta2019cloud}. Saha \textit{et al}.~\cite{saha2018comprehensive} highlighted the increasing range of applications for cloud robotics in various areas: manufacturing, social, agriculture, medical and disaster management. Visual SLAM approaches can benefit significantly from an online and cloud based system. The Parallel Tracking and Mapping (PTAM) framework~\cite{klein2007parallel} developed by Klein and Murray has been one of the landmark works in the modern history of visual SLAM. It demonstrated the advantages of alternation and parallel computing (of tracking and mapping), leading to a robust real-time system with accuracy comparable to offline reconstruction. A number of present state-of-the-art visual SLAM and 3D reconstruction systems use similar principles~\cite{mur-atal15, bloesch2018codeslam, newcombe2011dtam, newcombe11kinectfusion}. However, the scale at which such a framework can be used is directly related to the compute resources and storage available on the embodied device, as well as the possibility of robot collaboration. Hence, online and cloud-based alternatives have been explored in the literature aimed at widely expanding the scope of using robots for various tasks. In~\cite{riazuelo2014c2tam}, the authors developed a Cloud framework for Cooperative Tracking and Mapping (C$^2$TAM) as an extension to PTAM~\cite{klein2007parallel}. In this framework place recognition and non-linear map optimization is performed on the cloud, while tracking and re-localization is handled by the robot client. A cloud-based framework not only provides computational benefits but also the opportunity to share work tasks and knowledge, for example, in multi-robot exploration and mapping~\cite{zhang2018cloud, choudhary2016multi, kim2010multiple, fox2006distributed}. Some recent advances in the context of cloud computing and its use in robotics include reinforcement learning based resource allocation~\cite{liu2018reinforcement}, real-time object tracking over the internet using UAVs~\cite{koubaa2018dronetrack, koubaa2019dronemap}, FastSLAM 2.0~\cite{montemerlo2003fastslam} as a cloud service~\cite{ali2018fastslam} and cloud-based real-time multi-robot SLAM~\cite{zhang2018cloud}. One of the critical enablers of cloud robotics is network offloading where a number of challenges still remain to be solved~\cite{chinchali2019network}. In the context of robotic tasks based on semantic scene understanding, researchers have explored a number of ways to use a cloud-based paradigm. \cite{wu2019cloud} demonstrated the use of semantic databases and sub-databases on the the CloudStack~\cite{cloudstack}), comprised of text-based sub-database selection (tableware versus electric appliances) and vision-based representations of various objects. A semantic map of the environment is then constructed using ``belonging-annotation'' positional relationships between objects. In an industrial automation application, \cite{martin2017decentralized} proposed a decentralized robot-cloud communication architecture for autonomous transportation within a factory, particularly highlighting the benefits of their approach under communication and hardware failure conditions. More recently, \cite{ballotta2020sensor} presented an analytical optimization of the trade-off between communication and computational delay in a network of homogeneous sensors. The knowledge repositories and relevant datasets discussed previously also lead to the use of online cloud services in order to improve knowledge sharing and enabling learning from other similar resources. The use of cloud services also means that a lot of heavy-lifting tasks can be done on the cloud including incremental learning~\cite{roy2020tree, zhang2020class}, large-scale retrieval~\cite{garg2020fast, chang2020pre}, intensive data association~\cite{ye2020efficient, chen2020graph} and non-convex optimization~\cite{yang2020one, yang2020graduated}. Furthermore, cloud infrastructure brings robots within the IoT and also enables effective collaborative task solving that involves multiple robots meaningfully interacting with each other and other machines or humans. This approach may, eventually, lead to solving literally city-scale complexity problems, like building and administering a smart city~\cite{kapitonov2019robotic, kim2017smart}. \subsubsection{Human-robot interaction} One of the key aims of equipping robots with rich semantic representations of the world is to enhance and naturalize human-robot interaction. The literature points towards the use of semantics to build expressive robots~\cite{breazeal2009role} that can use effective modalities to coordinate their verbal and non-verbal interaction with humans. This includes human-like motion of robotic arms~\cite{Fang2019}, semantic reasoning-based natural language understanding for service robots~\cite{Savage2019}, human-robot dancing~\cite{or2009towards,Jochum2019TonightWI}, expression of emotions (both facial and full body~\cite{miwa2004effective,Lai2018EmotionPreservingRL,giambattista2016expression}), and the ability to build and navigate in human-centric semantic spatial representations~\cite{zender2008conceptual,talbot2020robot}. More recently, \cite{moon2020object} proposed object-oriented semantic graphs based on a graph convolutional network to generate natural questions from the observed scene. Linked with inverse semantics~\cite{Tellex2015}, such systems enable a robot to ask the right questions in order to better communicate, ask for help and solve the task accordingly. \section{DISCUSSION AND CONCLUSION} \label{secn:conclusion} Robotic perception, world modelling, and decision making have evolved beyond their early limited focus on geometry and appearance. As we have discussed, modern approaches increasingly incorporate semantic information, which enables a higher-level and richer understanding of the world. In return, a variety of new robotic applications have already emerged, with new applications on the horizon. Still, many exciting directions for research remain. One open questions is about explicit or implicit representation of semantics: should we as researchers and algorithm designers \emph{enforce} semantic information being explicitly represented, or do we enable an algorithm to \emph{implicitly} learn task-relevant semantic concepts? Do we understand which semantic concepts are relevant for a particular robotic task, and is there a direct mapping between robot-relevant and human-relevant semantic concepts? In an age where explainability and the ``trustworthiness'' of autonomous systems is becoming increasingly important, how could we understand and interpret robot-learnt semantic concepts that bear no direct correspondence to any semantic concepts we are familiar with as humans? While it would be ``neat" if the concepts are the same across robots and humans, if optimal robot performance involves semantic learning and representations that aren't directly interpretable by humans, this is likely to be an ongoing area of research focus. At the moment, most semantic representations assume a \emph{flat} structure. However, many semantic concepts can be naturally organised in a \emph{hierarchical} structure (or even into a more general, graph-like structure). This is maybe most obvious for object class labels (\texttt{object} $\rightarrow$ \texttt{indoor object} $\rightarrow$ \texttt{furniture} $\rightarrow$ \texttt{chair}), but might also be a useful representation for affordances, room or place categories, and other semantic domains. This hierarchical structure also extends spatially, where semantic concepts might be expressed on the scale of object parts, objects, functional ensembles of objects, rooms, buildings and city blocks. Hierarchical semantic knowledge is likely not to be a ``clean'' representation, but rather to involve levels where the distinction between levels can be quite fuzzy; take for example a barista's coffee machine, which is both a single, complex object and an ensemble of objects. Understanding the different aspects of a semantic hierarchy can be important for robotic applications, especially when faced with imperfect perception or incomplete knowledge. This discussion soon leads to more principled questions about the very nature of semantic concepts and how they can be represented to be accessible by robotic algorithms. Unless one follows the promises of pure and all-encompassing end-to-end learning, prior knowledge about semantic concepts needs to be modeled and represented in some form. This has already been investigated extensively in classical AI knowledge representation and reasoning research. An interesting middle ground is to try and incorporate hand-crafted semantics as priors into learning-based systems that can expand, continue to learn, or even re-learn semantics in a task-informed way. Given the wide range of potential applications of robotics with varying levels of complexity and operating requirements (especially around safety and reliability), a spectrum of approaches may be needed, informed by context; from pure end-to-end to hybrid, to entirely hand-crafted. As noted in the survey's coverage of datasets relating to semantics research, there can be significant disconnects between different research subfields that touch on semantics. To achieve sufficient progress in application-focused areas like autonomous vehicles, much of the work in semantics has focused on domain-specific implementations, leading to higher performance levels but at the possible cost of generality for all of robotics. It will be interesting to see to what extent the insights gained from targeted semantics research in an area like autonomous driving will benefit the robotics field more broadly, just as it will be interesting to see whether it is possible to make enough progress by focusing on providing robots - or in this case autonomous vehicles - with only a targeted, constrained understanding of the world around them. Like many other topics, progress in semantics-related research suffers to some extent from a disconnect across disciplinary boundaries, especially between robotics and computer vision. A related issue is the dominance of dataset-based evaluation, especially for tasks like semantic segmentation. Papers at the leading conferences, arguably predominantly in the computer vision discipline at conferences like CVPR, are dominated by research that achieves new levels of performance on these benchmark datasets. Although there is a promising trend towards evaluation in high fidelity simulation environments, performance on datasets and simulation alone is only one step towards safe and reliable deployment on robotic platforms, as has been revealed in application areas such as autonomous on-road vehicles. Bridging the divide between performance on datasets and performance on robots in closed-loop scenarios is likely to remain a major challenge for the foreseeable future, but also presents a unique opportunity for what we might coin ``active" semantics, where semantic learning and understanding are enhanced by active control of a robotic platform and its sensing modalities. This survey has summarized the state-of-play with respect to semantics research: the fundamentals, and the increasing integration of semantics into systems addressing key robotic capabilities like mapping and interaction with the world. While much progress has been made in the quest to imbue robots with a richer and nuanced understanding of the world around them, there is much still to be done. Future research will benefit from developments in the technologies and datasets underpinning much semantics-based research, as well as from new conceptual approaches, including those discussed here. The use of semantics in robotics will also continue to be informed by humans. Human communication makes rich use of semantic concepts of various kinds; we formulate tasks, give instructions and feedback, and communicate expectations based on the \emph{meaning} of objects, affordances, or the wider spatial and temporal context. Incorporating semantics into robotics, especially by bridging classical approaches with modern, learning-based approaches could have great impact on future robotic applications, especially those where robots work closely with, for or around humans. \section{INTRODUCTION} \import{1-Introduction/}{intro.tex} \section{STATIC AND UN-EMBODIED SCENE UNDERSTANDING} \label{secn:semanticsfundamental} \import{2-Fundamental_computer_vision/}{computervision.tex} \section{DYNAMIC ENVIRONMENT UNDERSTANDING AND MAPPING} \label{secn:mappingSLAM} \import{3-Mapping_and_Navigation/}{mapping.tex} \section{INTERACTING WITH HUMANS AND THE WORLD} \label{secn:interaction} \import{4-Interacting_with_humans_and_the_world/}{interaction.tex} \section{IMPROVING TASK CAPABILITY} \label{secn:improvingTask} \import{3-Mapping_and_Navigation/}{improvingTask.tex} \section{PRACTICAL ASPECTS: APPLICATIONS AND ENHANCERS} \label{secn:discussion} \import{5-Discussion/}{discussion.tex} \bibliographystyle{IEEEtran}
{'timestamp': '2021-01-05T02:16:48', 'yymm': '2101', 'arxiv_id': '2101.00443', 'language': 'en', 'url': 'https://arxiv.org/abs/2101.00443'}
arxiv
\section{Introduction} Recent advances in natural language processing technologies have opened a new space for individuals to digest information. One of these rapidly developing technologies is neural natural language generation. These models, made up of millions, or even billions~\cite{NEURIPS2020_1457c0d6}, of parameters, train on large-scale datasets. While attempts are made to ensure that only ``safe'' data is utilized for training these models, several studies have shown the prevalence of biases produced by these pretrained generation models~\cite{sheng-etal-2019-woman,groenwold-etal-2020-investigating,solaiman2019release}. Of equally alarming concern are the memorization and subsequent generation of factually incorrect data. Conspiracy theories are one particular type of this data that can be especially damaging. While it is not new for researchers to learn that a model may memorize data~\cite{radhakrishnan2019memorization}, we argue that the growing usage of machine learning models in society warrants targeted investigation to deter potential harms from problematic data. In this paper, we address the upsides and pitfalls of memorization in generative language models and its relationship with conspiracy theories. We further describe the difficulty of detecting this memorization for the categories of memorization, generalization, and hallucination. Previous studies investigating memorization of text generation models have done so with access to the model's training data \cite{carlini2019secret,carlini2020extracting}. As models are not always published with their training datasets, we set out to examine the difficult task of eliciting memorized conspiracy theories from a pretrained NLG model through various model settings \textbf{without access to the model's training data}. We focus our study on the pre-trained GPT-2 language model~\cite{radford2019language}. We investigate this model's propensity to generate conspiratorial text, analyze relationships between model settings and conspiracy theory generation, and determine how these settings affect the linguistic aspect of generations. To do so, we create a new conspiracy theory dataset consisting of conspiracy theory topics and machine-generated conspiracy theories. Our contributions include: \begin{itemize} \item[$\bullet$] We propose the topic of conspiracy theory memorization in pretrained generative language models and outline the harms and benefits of different types of generations in these models. \item[$\bullet$] We analyze pretrained language models for the inclusion of conspiracy theories without access to the model's training data. \item[$\bullet$] We evaluate the linguistic differences for generated conspiracy theories across different model settings. \item[$\bullet$] We create a new dataset consisting of conspiracy theory topics from Wikipedia and machine-generated conspiracy theory statements from GPT-2. \end{itemize} \section{Spread of Conspiracy Theories} \subsection{Dangers of conspiracy theories} A conspiracy theory is the belief, contrary to a more probable explanation, that the true account for an event or situation is concealed from the public~\cite{goertzel1994belief}. A variety of conspiracy theories ranging from the science-related moon landing hoax~\cite{bizony2009all} to the racist and pernicious Holocaust denialism\footnote{http://auschwitz.org/en/history/holocaust-denial/} are widely known throughout the world. However, even as existing conspiracy theories continue circulating, new conspiracy theories are consistently spreading. This is especially concerning given that half of Americans believe at least one conspiracy theory~\cite{oliver2014conspiracy}. Widespread belief in conspiracy theories can be highly detrimental to society, driving prejudice \cite{douglas2019understanding}, inciting violence\footnote{https://www.theguardian.com/us-news/2019/aug/01/conspiracy-theories-fbi-qanon-extremism}, and reducing science acceptance~\cite{VANDERLINDEN2015171,lewandowsky2013nasa}. Science denial has real-world consequences, such as resistance to measures for the reduction of carbon footprints~\cite{doi:10.1177/0096340215571908} and outbreaks of preventable illnesses due to reduced vaccination rates~\cite{goertzel2010conspiracy}. Further effects of conspiracy theory exposure can reach the political space and reduce citizens' likelihood of voting in elections due to feelings of powerlessness towards the government~\cite{jolley2014social}. At the time of writing, the COVID-19 pandemic is at its worst. Though COVID-19 vaccines have received approval and started distribution, new conspiracy theories surrounding the COVID-19 vaccine may hinder society in its road to recovery. Discussions of a link between vaccinations and autism have been circulating for years~\cite{jolley2014effects,kata2010postmodern}. However, with the extreme interest throughout the world surrounding the COVID-19 pandemic, new vaccination rumors are arising, such as the vaccine causing DNA alteration and claims of the pandemic acting as a cover plan to implant trackable microchips\footnote{https://www.bbc.com/news/54893437}. The belief in these theories can prevent herd immunity through the lack of vaccinations\footnote{https://www.economist.com/graphic-detail/2020/08/29/conspiracy-theories-about-covid-19-vaccines-may-prevent-herd-immunity}~\footnote{https://www.who.int/news-room/q-a-detail/herd-immunity-lockdowns-and-covid-19}. \subsection{NLG spreading conspiracy theories} As NLG models are being utilized for various tasks such as chatbots and recommendations systems~\cite{gatt2018survey}, cases arise in which these conspiracy theories and other biases can propagate unintentionally~\cite{bender2021dangers}. We present one such scenario in which an NLG model has memorized some conspiracy theories and is being used for story generation~\cite{fan-etal-2018-hierarchical}. An unaware individual may utilize this application and, given a prompt about the Holocaust, may receive a generated story discussing Holocaust denial. The user, now having been exposed to a new conspiracy theory, may choose to ignore this generated text at this stage. However, a potential negative outcome is that the user may become interested in this story and search the statements online out of curiosity. This can lead the user down the ``rabbit hole'' of conspiracy theories online~\cite{o2015down} and alter their original assumptions towards believing this conspiracy theory. \subsection{Why are conspiracy theories difficult to detect?}\label{sec:difficult} Recent years have seen the emergence of several new tasks addressing fairness and safety within natural language processing in topics such as gender bias and hate speech detection. Although detection and mitigation of other biases and harmful content have been thoroughly studied, that pertaining to conspiracy theories is increasingly difficult due to its inconsistent linguistic nature. Many existing tasks can utilize specific keyword lists such as Hatebase\footnote{https://hatebase.org/} for detection in addition to current techniques~\cite{sun2019mitigating}. However, conspiracy theory detection is an increasingly complex problem and cannot be approached in the same way as the previous topics. Conspiracy theories have no unified vocabulary or keyword list that can differentiate them from standard text. Previous studies of conspiracy theories have exhibited their tendency to lean towards issues of hierarchy and abuses of power~\cite{klein2019pathways}. We argue this is not specific enough to define features for their detection. Often, specific keywords and tropes become typical of conspiracy theories regarding a specific topic, such as 9/11 and ``false-flag''~\cite{knight2008outrageous}. However, as the number of topics surrounding conspiracy theories grows, it becomes infeasible to create and maintain these topic-specific vocabularies. To add to this difficulty, while humans can typically detect other types of biases, they cannot easily distinguish conspiracy theories from truthful text by merely reading the statement. Doing so typically requires knowledge of the topic itself or a more in-depth look into the theory narrative through network analysis\footnote{https://theconversation.com/an-ai-tool-can-distinguish-between-a-conspiracy-theory-and-a-true-conspiracy-it-comes-down-to-how-easily-the-story-falls-apart-146282}. To this end, the best way to stop the spread of conspiracy theories is not in late-stage detection but early intervention. \subsection{How can NLG models be misused?} While the generation of conspiracy theories may be an accidental outcome by NLG models, the possibility still exists that adversaries will intentionally utilize these language models to spread these theories and cause harm. In one such case, propagandists may utilize NLG models to reduce their workload when spreading influence~\cite{mcguffie2020radicalization}. By merely providing topic-specific prompts, they can utilize these models to easily and efficiently produce a variety of conspiratorial text for online communities regarding the topics. As a result, these communities will appear to be larger than their actual size and provide the appearance that belief in the issue is high. This may provide real-life members with a sense of belonging and subsequently reinforce belief in the theories or even recruit new members~\cite{douglas2017psychology}. \section{Memorization vs. Generalization vs. Hallucination} The memorization of data in the context of machine learning models has been highlighted in research for many years now. Related work has researched the types of information models memorize~\cite{NEURIPS2020_1e14bfe2}, how to increase generalization~\cite{chatterjee2018learning}, and the ability to extract information from these models~\cite{carlini2020extracting}. While memorization is typically discussed in the space of memorization vs. generalization, we believe this can be broken down even further. In the context of conspiracy theories, we establish three types of generations: \begin{itemize} \item[$\bullet$] Memorized: generated conspiracy theories with exact matches existing within the training data. \item[$\bullet$] Generalized: generations that do not have exact matches in the data but produce text that follows the same ideas as those in the training data. \item[$\bullet$] Hallucinated: generations about topics that are neither factually correct nor follow any of the existing conspiracy theories surrounding the topic. \end{itemize} Studies on memorization tend to focus on either memorization vs. generalization or memorization vs. hallucination~\cite{nie-etal-2019-simple}. In the latter case, it is easy to see how the term ``memorization'' can apply to the first two categories. Ideally, in an NLG model, we would hope for generations to be generalized since direct memorization can have the downsides of generating sensitive information~\cite{carlini2019secret}. There are also cases when hallucinations are ideal, such as in the realm of creative story-telling. Should we be able to distinguish among these categories, we could gain deeper insight into what and how these models learn during training. However, we acknowledge that classifying generations based on these categories is a difficult problem and believe this should be a task for future research in memorization. Our focus in this paper is to evaluate 1) whether a model has memorized conspiracy theories during training and 2) the propensity for the model to generate this information among different model settings (as opposed to generating other memorized or hallucinated information about a topic). Evaluating memorization within a model can be done in two settings: with training data as a reference or without training data. Previous studies have evaluated memorization within machine learning models by utilizing the model's training dataset. However, the reality is that many models nowadays are not published alongside their training data~\cite{45189}. In this case, the evaluation becomes increasingly difficult, as there is nothing to match a model's output to. In order to simulate a real-world environment, we analyze the second setting of investigating memorization without access to training data and instead treat the model as a black box when evaluating its outputs. Due to the difficulty of distinguishing among the three categories of memorization, generalization, and hallucination, we follow previous work and refer to both memorized and generalized generations as memorized samples for the rest of the paper. \section{When is memorization a good thing?} While we focus most of this paper on the downsides of memorization in natural language generation models, it is still important to address the benefits. There are several situations in which memorized information may be utilized, such as in dialogue generation~\cite{gu-etal-2016-incorporating}. When used in the chatbot setting, a model may be asked questions on real-world knowledge. Assuming the model has learned correct factual information, this memorization can prove useful. Furthermore, conspiracy theories are a part of language and culture. It is not inherently bad that a model is aware of the existence or concept of conspiracy theories, particularly in cases where models may be deployed as an intervention in response to human-written conspiratorial text. This only becomes harmful when the model cannot recognize text as a conspiracy theory and generates text from the viewpoint of the conspiracy being true. Though memorization may aid in the described cases, the downside of the learned conspiracy theories (as factual statements) and other information such as societal biases can outweigh these benefits. \begin{table}[t] \centering \begin{tabular}{p{1.6cm}|p{5.4cm}} \toprule & \multicolumn{1}{c}{Conspiracy Theory} \\ \hline Wikipedia & The \textbf{Holocaust} is a lie, and the Jews are not the victims of the Nazis. \\ \hline GPT-2 & The US government is secretly running a secret program to create a super-soldier that can kill and escape from any prison. \\ \bottomrule \end{tabular} \caption{Samples from the Wikipedia dataset consisting of Wikipedia topics and General dataset of GPT-2 generated conspiracy theories without topic prompts. The Wikipedia topic is highlighted in bold and is used as a topic-prompt for text generation in GPT-2. }\label{tab:example} \end{table} \section{Data Collection} While conspiracy theory data may appear in misinformation datasets labeled as ``Fake News'' with other misinformation types, there are few existing datasets with conspiracy theory labeled text. Previous conspiracy theory studies contain datasets that are either small in size~\cite{oliver2014conspiracy}, contain non-English data~\cite{bessi2015science}, or pertain to events occurring after the release of GPT-2~\cite{ahmed2020covid,uscinski2020people}. Therefore, we create a dataset exclusively dedicated to conspiracy theories~\footnote{https://github.com/sharonlevy/Conspiracy-Theory-Memorization}. We obtain our data for our analysis from two different sources: Wikipedia and GPT-2. We show samples from each of our datasets in Table \ref{tab:example}. \subsection{Wikipedia} We first aim to create a set of conspiracy theory topics. To gather this data, we utilize Wikipedia's category page feature. Each item listed in a category page is linked to a corresponding Wikipedia page. We obtain the page headers in the conspiracy theory category page and the following page headers in the Wikipedia conspiracy theory category tree. This process allows us to extract 257 Wikipedia pages regarding conspiracy topics. We further refine this dataset of conspiracy topics through the use of Amazon Mechanical Turk~\cite{buhrmester2016amazon}. Ten workers are assigned to each Wikipedia conspiracy topic, and each worker is asked whether they have heard of a conspiracy theory related to the topic. We remove any topic from our dataset with fewer than six votes to focus our study on the well-known conspiracy theory topics that a model would be more likely to be prompted with. Our final dataset consists of the following seventeen conspiracy theory topics: Death of Marilyn Monroe, Men in black, Sandy Hook school shooting, UFO's, Satanic ritual abuse, Climate change, Area 51, 9/11, Vast right-wing conspiracy, Global warming, Shadow government, Holocaust, Flat Earth, Illuminati, Pearl Harbor, Moon landing, and John F. Kennedy assassination. We refer to this as the Wikipedia dataset for the remainder of the paper. \subsection{GPT-2} We create a second dataset consisting of machine-generated conspiracy theories. To do this, we elicit the conspiracy theories directly from GPT-2 Large with the HuggingFace transformers library~\cite{wolf-etal-2020-transformers}. We prompt GPT-2 with ``The conspiracy theory is that'' at varying temperature levels (0.4, 0.7, 1). We obtain 5000 theories at each temperature level and post-process the text by removing the original prompt and keeping only the first sentence. For the remainder of the paper, we refer to this dataset as the General dataset. \section{Generation of Conspiracy Theories}\label{sec:context_gen} An intriguing question in the scope of conspiracy theory generation is: what can trigger a language model to generate conspiracy theories? We begin by investigating the effects of model parameters and decoding strategies on the generation of conspiracies when prompted with a topic. Of these, we study model temperature and model size. We use our Wikipedia dataset to create a generic prompt as input to GPT-2, such as ``The Holocaust is''. In order to remove any trigger such as “Flat Earth is”, we modify some of our topic titles during prompt creation to make a more neutral prompt. In the case of “Flat Earth”, our prompt is “The Earth is”, so that the model is not intentionally triggered to produce Flat Earth conspiracy text. We perform this action for the rest of our topics as well. For each prompt, we employ the model to create twenty generations with a token length of fifty. When evaluating the generated text, we evaluate whether or not the text affirms the conspiracy theory. In this sense, we count ``The Earth is flat'' as affirming the conspiracy theory and “The Earth is flat is a conspiracy theory” as not affirming the theory. As such, we evaluate whether the model presents the theory as factual belief as opposed to whether it has knowledge of the theory. To determine whether or not the generation affirms a known conspiracy theory, we utilize Amazon Mechanical Turk. Worker pay and instructions are detailed in Appendix \ref{sec:appendix}. We provide each worker with a reference passage describing known conspiracy theories for each topic and ask whether or not the generation affirms or aligns with the reference text. We make sure to state that the reference text contains several conspiracy theories about the topic at the top of each HIT. In this case, if a worker is exposed to new text, they are clearly informed that the text is a conspiracy theory. Should a worker encounter these theories in the future, they may even benefit from the task since they are now armed with the knowledge that these statements are in fact conspiracy theories. Seven workers are assigned to each generated sequence. If the text is voted as a conspiracy, it receives a point; otherwise, it is subtracted a point. We then retrieve those generations with two or more points (indicating a general consensus) and manually evaluate this subset of generations for another round of verification. \subsection{Temperature} \begin{figure}[t] \centering \includegraphics[width=\linewidth]{temp.png} \caption{Percentage of conspiracy theories generated by GPT-2 Large at varying temperatures when prompted on 17 different conspiracy theory topics. Each topic is used to generate 20 sequences for a total of 340 generations.}\label{fig:temp} \end{figure} We first evaluate GPT-2 Large at temperature settings ranging from 0.25 to 1 with sampling, where 1 is the default setting for the model, and with greedy decoding on the Wikipedia dataset prompts. This decoding strategy changes the model's probability distribution for predicting the next word in the sequence. A lower temperature will increase the likelihood of high probability words and decrease the likelihood of low probability words. At each temperature level, we compute the percentage of generated text marked as conspiracy theories out of the total number of generations. We share our results in Figure \ref{fig:temp}. It can be seen that as the temperature decreases, the model follows a general trend of generating more conspiracy theories. There is an exception when temperature $\rightarrow$ 0, which translates to simple greedy decoding. In this case, the proportion of conspiracy theories decreases slightly, indicating that while the model may memorize some theories, other information for specific topics is also memorized and have a higher likelihood of being generated. However, the general result curve shows that existing conspiracy theories are deeply rooted in the model during training for many topics. Given these findings, we believe it is best to add randomization to the decoding procedure, at the risk of quality and coherency, instead of greedy search in order to minimize the risk of generating deeply memorized conspiracy theories. Decreasing the model's temperature allows us to evaluate which topics this deep memorization may be true for, as not every conspiracy topic may be ingrained in the model. We assess which topics the model increases its number of conspiracy theory generations for at a lower temperature. When parsing the previous results for each topic across the different temperature settings, we find this increase in conspiracy theory generations and, therefore, the prominent memorization of conspiracy theories for the topics of UFO's, 9/11, Holocaust, Flat Earth, Illuminati, and Moon landing. \begin{figure}[t] \centering \includegraphics[width=0.96\linewidth]{size.png} \caption{Percentage of conspiracy theories generated by GPT-2 models of size small, medium, and large when prompted on 17 different conspiracy theory topics. Each topic is used to generate 20 sequences for a total of 340 generations.}\label{fig:size} \end{figure} \subsection{Model size} Next, we aim to test a language model's size for its capability to memorize and generate conspiracy theories. Again, we utilize the Wikipedia dataset prompts for generations. We prompt three model sizes with our topics: GPT-2 Small (117M parameters), GPT-2 Medium (345M parameters), and GPT-2 Large (762M parameters). We keep a fixed temperature across the models and set it at the default value of 1. We use the same evaluation technique described above and compute the proportion of generations marked as conspiracy theories out of the total number of generations. These results are shown in Figure \ref{fig:size}. While nearly 10\% of GPT-2 Large's generations are classified as conspiracy theories, GPT-2 Medium reduces this number by almost 50\%. The GPT-2 Small model's conspiracy theory generations are substantially lower than this at a little over 1\%. We can deduce that reducing model size vastly lowers a model's capacity to retain and memorize information after training, even if that information is profoundly prominent within the training data. Not only is this beneficial for mitigating the generation of conspiracy theories, but it can also allow the model to generalize better to other information for topic-specific prompts. \section{Towards Automated Evaluation} As we have shown that varying temperature and model size can individually lead to further elicitation and memorization of conspiracy theories, we now investigate the effects of varying the two together. In our previous experiments, we utilize Mechanical Turk to identify conspiracy theories among the generated text. However, we understand that human evaluation is not feasible for detecting conspiracy theories on a large scale. Instead, we desire to advance towards a more automated evaluation of memorization. As such, we investigate whether we can define a relationship between the memorization of conspiracy theories and perplexity across the different model parameters. Following previous studies on fact-checking \cite{chakrabarty-etal-2018-robust, Wang2010GotYA} and model memorization~\cite{carlini2020extracting}, we evaluate model generations against Google search results. This time, we utilize our General dataset, made up of conspiracy theories generated with the generic prompt ``The conspiracy theory is that''. We query Google with a generated conspiracy theory at each temperature setting and compare this theory to the first page of results. We did not manually use Google search for our generated text and instead created a script to automate this and scrape the text from the first page of results. We provided the minimum amount of information needed for making each search request so that this does not include search history and the more specific location information or cookies. The temperature values of 0.4, 0.7, and 1 are used as lower temperature values start to produce many duplicate generations and lead to small sample sizes for this evaluation. We obtain the text snippet under each search result and evaluate this against the conspiracy theory with the BLEU metric~\cite{papineni-etal-2002-bleu}. The BLEU metric is utilized since many search results do not contain complete sentences and are instead highlighted phrases from the text related to the query and concatenated by ellipses. The perplexity score for a conspiracy theory is then calculated for each model size. The resulting BLEU and perplexity scores are ranked with the highest BLEU and lowest perplexity scores first. We use Spearman's ranking correlation~\cite{hogg2005introduction} to determine the resulting alignment between the two. These results are shown in Figure \ref{fig:tempxsize}. \begin{figure}[t] \centering \includegraphics[width=1.0\linewidth]{sizetemp.png} \caption{Spearman correlation of model perplexity vs. Google search BLEU score for GPT-2 generated conspiracy theories across varying temperature settings. Each generated theory is evaluated against the first page of Google search results with the BLEU metric.}\label{fig:tempxsize} \end{figure} We find a strong relationship between a generated conspiracy theory's perplexity and its appearance in Google search results. This correlation becomes much weaker when the temperature is set to 1, indicating that the default setting's increased randomness may produce more hallucinated generations. However, given these results, we believe this can open the door towards the creation of more automated memorization evaluation techniques. Though our samples are generated through GPT-2 Large, we further test this alignment on the small and medium model sizes. We find that the relationship between Google search results and perplexity decreases as model size decreases for the smaller temperature settings, further confirming that model size does affect memorization. \begin{table}[t] \centering \begin{tabular}{l|*{3}{c}|c} \toprule & \multicolumn{3}{c}{Temperature} \\ \hline Classifier & 0.4 & 0.7 & {1.0} & p-val \\ \toprule dBERT & -0.974 & -0.942 & -0.887 & 0.110 \\ \hline VADER & -0.556 & -0.527 & -0.486 & $<$0.001 \\ \hline TextBlob & -0.112 & -0.033 & 0.017 & $<$0.001 \\ \hline \hline Average & -0.547 & -0.500 & -0.452 \\ \bottomrule \end{tabular} \caption{Comparison of average sentiment scores across GPT-2 Large generated conspiracy theories with the DistilBERT (dBERT), VADER, and TextBlob sentiment classifiers along with the Wilcoxon rank-sum p-values for generation pairs of temperature 0.4 and 1. The conspiracy theories are generated at the temperature values of 0.4, 0.7, and 1.0 and sentiment scores range from -1 to 1. }\label{tab:sentiment} \end{table} \section{Linguistic Analysis} While our previous analysis aims to define a relationship between model parameters and the generation of conspiracy theories, we are also interested in evaluating whether these generations have any interesting linguistic properties. As such, we choose to test the question, are there any linguistic differences among the generated conspiracy theories across different model settings? We proceed by examining two linguistic aspects of our texts: sentiment and diversity. \subsection{Sentiment} When analyzing sentiment, we evaluate our General dataset of generated conspiracy theories at its three temperature levels. We are interested in answering the question: how will the model's temperature affect the sentiment of its generations that are not prompted by real-world stimulus? To proceed, we utilize three sentiment classifiers: DistilBERT~\cite{sanh2019distilbert}, VADER~\cite{gilbert2014vader}, and TextBlob\footnote{https://textblob.readthedocs.io/en/dev/index.html}. For DistilBERT we convert the output range of [0,1] to [-1,1] to match the other two classifier ranges. The average sentiment scores are displayed in Table \ref{tab:sentiment} along with the Wilcoxon rank-sum p-values for each classifier output between temperature settings 0.4 and 1. The results show that decreasing the model's temperature triggers it to generate increasingly negative conspiracy theories. Although we do not achieve similar sentiment scores across the different classifiers, they all exhibit the same downward trend among score and temperature values. Additionally, classifier-temperature value pairs produce negative sentiment scores in all but one case. This follows previous work indicating that conspiracy theories and one's belief in them are emotional rather than analytical and are linked to negative emotions~\cite{van2018belief}. \begin{table}[t] \centering \begin{tabular}{l|*{3}{c}} \toprule & \multicolumn{3}{c}{Temperature} \\ \hline Size & 0.4 & 0.7 & {1.0} \\ \toprule Small & 0.372 & 0.227 & 0.084 \\ \hline Medium & 0.397 & 0.231 & 0.094 \\ \hline Large & 0.421 & 0.255 & 0.120 \\ \hline \hline p-value & $<$0.001 & $<$0.001 & $<$0.001 \\ \bottomrule \end{tabular} \caption{Comparison of average BERTScore values across Wikipedia topic-prompted GPT-2 generations for varying model sizes and temperatures. Generations for each size-temperature pair are evaluated against other generations for their specific topic. Wilcoxon rank-sum p-values for the large-small model pairs at each temperature are listed at the bottom.}\label{tab:diversity} \end{table} \subsection{Diversity} Next, we analyze linguistic diversity across model sizes and model temperature. Utilizing the Wikipedia dataset, we compute the BERTScore~\cite{bert-score} for each generation in reference to the other generations for each topic. This metric is used to measure the variance and contextual diversity across the different model generations for a specific conspiracy topic~\cite{zhu2020understanding}. We do this across temperature values of 0.4, 0.7, and 1 and the different model sizes. These temperature values are utilized as lower temperature values start to produce duplicate generations. The average F1 scores for each setting pair is calculated and shown in Table \ref{tab:diversity} along with the corresponding p-values from a Wilcoxon rank-sum test for the large-small pairs at each temperature. We find that as the temperature decreases, the similarity across generations for each topic increases. This is not surprising, as the outputs become less random at lower temperatures, and the model tends to output more memorized information. When comparing the scores among the different model sizes, the largest model contains the largest values, decreasing with the model size. We can infer that an increase in model size leads to more memorization, which allows the model to generate more contextually aligned outputs for specific topics instead of the diverse sets of outputs in smaller model sizes. \section{Moving Forward} Throughout this paper, we have discussed the risks and benefits of memorization in NLG models and have focused on the dangers of conspiracy theory generation. As we relayed in Section \ref{sec:difficult}, conspiracy theory detection is a challenging problem due to its fuzzy linguistic vocabulary. We believe it is crucial to intervene earlier to mitigate these risks rather than detect them after the model's generation. While reducing memorization of harmful data in models is still an open problem, we discuss various methods to help accomplish this and encourage future research in the area: 1) preventing detrimental data from being introduced into the training set, 2) ensuring the dataset contains a much larger proportion of factually correct data for conspiracy theory topics than the conspiracy theories themselves, and 3) reducing model size. The first solution prevents researchers from relying on these models to filter out harmful noise in large-scale datasets. Current models, such as GPT-2, attempt to filter out offensive and sexually explicit content from their datasets during creation\footnote{https://github.com/openai/gpt-2/blob/master/modelcard.md}. We argue that this is not enough, as shown in the results of our analysis above. One way to proceed is to ensure that data is only collected from reliable sources instead of scraping the internet for large amounts of information. However, we also recognize that this is a tedious task and requires intensive scrutiny when collecting data. As such, the downsides to following this method may lead to smaller datasets and models with lower quality generations. In addition, this requires the additional consideration of deciding what data is ``good'' and what data can be harmful. In the space of conspiracy theories, the creation of a database regarding circulated conspiracy theories and debunking them seems like an appropriate direction to go. While not completely eliminating the possibility of conspiracy theory generation, the second method aims to decrease their likelihood during generation. To accomplish this, researchers can supplement their existing dataset with a second dataset consisting of factually correct samples surrounding conspiracy theory topics. This aims to oversample truthful data for training. While our study is confined to well-known conspiracy theories, the approach we discuss should be performed for all conspiracy-related topics and thus requires the additional task of identifying these subjects. As our experiments in Section \ref{sec:context_gen} have shown, model temperature and size profoundly affect the memorization and generation of conspiracy theories in NLG models. Since a user may set temperature, this setting cannot help prevent the generation of harmful data. However, modifying model size can. Though recent years have seen an increase in model size due to better performance on downstream tasks and the resulting generation of more coherent text~\cite{solaiman2019release}, it comes at the cost of memorization. Therefore, researchers must strive to find a balance between memorization and fluency. When compromising model size, this mitigation strategy may also be complemented by oversampling factual data as specified above for further intervention. \section{Conclusion} In this paper, we highlight the issue of conspiracy theory memorization and generation in pretrained generative language models. We show that the root of the problem stems from the memorization of these theories by NLG models and discuss the dangers that may follow this. This paper further investigates the detection of conspiracy theory memorization in these models in a real-world scenario where one does not have access to the training data. To do so, we create a conspiracy theory dataset consisting of conspiracy theory topics and machine-generated text. Our experiments show that reducing a model's temperature and increasing its size allows us to elicit more conspiracy theories, indicating their memorization without verification against the ground-truth dataset. We hope our findings encourage researchers to take additional steps in testing language models for the generation of harmful content before release. Further, we hope our discussion on memorization can lead to further research in the area and advance the study of conspiracy theories in NLP. \section*{Acknowledgements} We would like to thank Amazon AWS Machine Learning Research Award and Amazon Alexa Knowledge for their generous support. This work was also supported in part by the National Science Foundation Graduate Research Fellowship under Grant No. 1650114. \section*{Ethical Considerations} In this paper, we explore the topic of conspiracy theories in natural language generation. We acknowledge that in order to build a coherent and robust language model, a large-scale dataset must be used. As such, it is difficult to obtain data of this size that is 100\% free of offensive or harmful samples. However, to improve and further progress research in natural language processing, considerations of disadvantages such as the memorization and subsequent generation of conspiracy theories must be taken into account. In the previous sections of the paper, we feature how researchers can evaluate language models for the memorization and generation of conspiracy theory text. While we showcase methods for analyzing the generation of this harmful content, we acknowledge some potential risks: 1) adversaries may adjust their methods for hiding harmful content in language models so that it is not easily extracted or generated through our evaluation methods, and 2) attackers may use the methods discussed and leverage other language models to extract conspiracy text or amplify their generation in natural language applications. However, we believe bringing light to the issue of conspiracy theory memorization in NLG models is essential for research to progress in the direction of safe and fair natural language processing and will enable future research to utilize these studies in model interpretability. While it may be possible for attackers to extract conspiracy theories from language models through more advanced techniques, we attempt to study how the ordinary user may fall prey to this type of information in a standard way. With language models becoming increasingly integrated into everyday natural language processing applications, the risks of unintentionally generating and spreading conspiracy theories rises. Our work can help researchers and engineers of language models thoroughly test these models for the generation of harmful conspiracy theory text using our analysis. We also hope to show researchers that even seemingly ``clean'' datasets may not diminish harmful noise from data and instead reflect or even amplify it after training.
{'timestamp': '2021-06-10T02:00:30', 'yymm': '2101', 'arxiv_id': '2101.00379', 'language': 'en', 'url': 'https://arxiv.org/abs/2101.00379'}
arxiv
\section{Introduction}\label{sec:introduction}} \IEEEPARstart{B}{lockchain} was proposed as a supporting technology for Bitcoin \cite{nakamoto2019bitcoin}, the first decentralized cryptocurrency. After Bitcoin, other decentralized cryptocurrencies (e.g., Litecoin \cite {reed2017litecoin}, Ethereum \cite{wood2014ethereum}) quickly emerged. The blockchains of these cryptocurrencies use the Nakamoto's proof-of-work (PoW) protocol to build consensus among distributed nodes. Blockchain has, by now, become a cutting-edge technology in the fields of FinTech, Internet of Things (IoT), and supply chains \cite{du2019affordances,kshetri2017can,kouhizadeh2018blockchain}, thanks to its ability to enable Byzantine agreement over a permission-less decentralized network \cite{singh2016blockchain}. A weakness of the current blockchains is the low on-chain transaction throughput. For example, the throughput of Bitcoin is around 5 $\sim$ 7 transactions per second (TPS), and that of Ethereum is around 40 TPS \cite{gobel2017increased}. Both are extremely low compared to around 110 TPS of PayPal and 1700 TPS of Visa. Its low transaction throughput hampers the widespread adoption of today's blockchain technology. A straightforward method to increase TPS is to enlarge the block size so that a block can carry more transactions. However, the propagation of large blocks in the network may incur huge delays that compromise the blockchains' security and integrity \cite{gervais2016security}, and thus it is not a good idea to increase the TPS by merely increasing the block size. Consequently, new consensus-building protocols and new specially deployed networking infrastructures have been proposed as solutions to increase the TPS of blockchains (see discussions of these related works in Section \ref{section:relatedWork}). In this work, we put forth a new block propagation protocol to propagate large blocks containing a large number of transactions without increasing the block relay delay. Unlike the existing solution that requires changing the consensus-building protocol or deploying new network infrastructures, we build our block propagation protocol upon the compact-block relaying protocol that is already adopted by the current Bitcoin network \cite{corallo2017compact}. Compact-block relaying reduces the block relay delay by compressing blocks that contain transactions (around 250 Bytes each in Bitcoin) into compact blocks that contain transaction hashes (6 Bytes each). Therefore, compact-block relaying can include more transactions into each compact block while maintaining the same relay delay, thus increasing the TPS without compromising the blockchain's security. In this paper, we further boost TPS by further increasing compact-block size including even more transaction hashes into each compact block. However, simply increasing compact-block size induces extra propagation delays that may compromise blockchain's security. We devise methods to keep the propagation delays at bay while increasing the compact-block size. We adopt a two-pronged approach: 1) we replace the store-and-forward compact-block relaying scheme with a cut-through forwarding scheme; 2) we apply rateless erasure codes to increase the efficiency of block propagation. The contributions of this work are listed as follows. \begin{enumerate} \item We put forth a new block propagation protocol that replaces the store-and-forward compact-block relaying scheme with a cut-through forwarding scheme. Our new cut-through compact-block relaying scheme can propagate large compact blocks without inducing extra relay. The original compact-block relaying \cite{corallo2017compact,ozisik2017graphene} is a store-and-forward scheme in which a whole compact block must be received before it is forwarded. With cut-through forwarding, a node receives small chunks of a compact block while forwarding earlier-received chunks, allowing reception and forwarding of a compact block to progress in parallel. \item We apply rateless erasure codes to compact blocks. Rateless erasure codes allow the recovery of the source symbols using a subset of the encoded symbols. Instead of distributing the original compact block’s source symbols, the compact block's source distributes the compact block’s encoded symbols. Importantly, rateless erasure codes allow a peer to construct source symbols by retrieving the encoded symbols from multiple peers. Our coded design benefits from the peer-to-peer (P2P) network topology of the Bitcoin blockchain by efficiently utilizing the upload bandwidths of all peers \cite{gkantsidis2005network}. \item We perform a theoretical analysis of our protocols assuming a simple linear network. The analysis results confirm that our protocols can obtain significant TPS gain. Moreover, to evaluate our protocols in a practical network, we implemented a Bitcoin network simulator. We simulated propagating huge compact blocks containing a large number of transaction hashes to improve TPS. Our results indicate that our block propagation protocols can increase TPS by 100x while maintaining the same propagation delay as the conventional block propagation protocols. \end{enumerate} Since our design is built upon compact-block relaying that has been implemented into the Bitcoin network, we believe our design can be readily deployed in the existing blockchain networks. The rest of this paper is organized as follows. Section \ref{section:relatedWork} discusses related works. Section \ref{section:background} presents the background of blockchain. Section \ref{section:Uncoded} and Section \ref{section:Coded} introduce our uncoded and coded designs. Section \ref{section:analysis} analyzes the performance of our two-pronged approach. Section \ref{section:simulation} discusses our experimental results, and Section \ref{section:conclusion} concludes this work. \section{Related Work}\label{section:relatedWork} To improve the TPS of the Bitcoin blockchain, \cite{consensus2019, natoli2019deconstructing} changed the Nakamoto's PoW consensus protocol . These clean-slate designs modified data structures and many crypto functional components in the Bitcoin blockchain’s consensus protocol. Consequently, these new consensus protocols are incompatible with the today’s Bitcoin blockchain. By contrast, our work aims to increase TPS by redesigning the networking protocol without changing other key functional components. Furthermore, our work does not require the building of new network infrastructures. There has been little prior work along this line. Ref. \cite{mccorry2020sok} discussed the shortcoming of the networking aspects of the Bitcoin blockchain. To reduce block propagation delay, \cite{corallo2017compact, ozisik2017graphene} devised compact-block relaying that transmits a compressed block consisting of the hashes of transactions in the block; transactions are transmitted (upon feedback from the receiver) only if they are missing at the receiver. Investigation in \cite{decker2013information} preemptively announce a block's availability before the complete reception of the whole block. Exploiting the multicasting capability of network nodes in blockchain, \cite{chawla2019velocity} employs fountain codes \cite{luby2002lt} to enable a full node to obtain a block from multiple peers. However, \cite{chawla2019velocity} still relies on store-and-forwarding rather than cut-through forwarding. Several works advocated building new network infrastructures for speeding up the block propagation of the Bitcoin blockchain. For example, \cite{klarman2018bloxroute} used a blockchain distribution network (BDN) with high throughput servers to speed up the propagation of large blocks. In particular, \cite{klarman2018bloxroute} adopted cut-through forwarding within the BDN, but not at distributed blockchain nodes. The BDN approach requires building a new infrastructure controlled by a central authority, partially offsetting decentralized blockchain systems' many advantages. FIBRE (Fast Internet Bitcoin Relay Engine) in \cite{corallo2017fibre} is a transport-layer protocol that uses UDP with forward error correction to decrease the delays caused by packet loss. It also introduces data compression to reduce the amount of network traffic. Our work, focusing on the blockchain networking protocol \footnote{In the TCP/IP and OSI nomenclature, the blockchain networking protocol resides in the application layer. In this paper, we do not change IP or TCP protocol at all.}, is fully compatible with FIBRE and can be merged with it. The idea of using cut-through forwarding to improve block propagation is also employed by Falcon \cite{falcon}. The differences between Falcon and our work here are as follows: i) Falcon implements cut-through forwarding on specially deployed relay nodes rather than on the existing blockchain nodes; ii) Falcon is a commercial project and there lacks performance analysis on its block propagation; iii) Falcon does not employ rateless erasure codes to increase the efficiency of block propagation. \section{Bitcoin Blockchain Background}\label{section:background} This section reviews the background for the Bitcoin blockchain, including its data structure, PoW consensus protocol, network topology, and block propagation protocols. After that, we present our compact block relaying scheme. \subsection{Data Structure of Blockchain} Blockchain is a decentralized append-only ledger for digital assets. A blockchain is replicated and shared among participants. The transactions in the system are contained in concatenated blocks in the blockchain. A block contains a header and multiple transactions. The state of a blockchain maintained by a participant changes according to the blocks in the blockchain. We can write a block as $B = \left[ {H,{T_1},{T_2}, \cdots ,{T_K}} \right]$ where $H$ denotes the header, $\left\{ {{T_1},{T_2}, \cdots ,{T_K}} \right\}$ denotes the transactions in the block, and $K$ denotes the number of transactions in a block. The header $H$ contains the hash computed from the content of the preceding block, the Merkle root of the transactions in this block, a nonce generated by the PoW consensus protocol and a number indicating the mining target. Each block must refer to its preceding block by placing the hash of its preceding block in its header, and the blocks form a chain of blocks arranged in chronological order. \subsection{PoW Consensus Protocol} A consensus protocol coordinates the blockchain's updates to ensure chronological ordering of the blocks and to ensure the blockchain's integrity and consistency across geographically distributed nodes. Bitcoin \cite{nakamoto2019bitcoin}, as the first implementation of blockchain, introduces the Proof-of-Work (PoW) consensus protocol. Tens of thousands of distributed nodes adopt the PoW consensus protocol to achieve data consistency (i.e., ensuring the blockchains maintained by them are the same). Before adding blocks to the blockchain, a Bitcoin node has to prove that it has performed some work known as PoW. In essence, a node must find a nonce input to a hash function so that the hash value is less than a target number, as expressed by \begin{equation} \label{eqn:mininghash} h\left( {n,p,m} \right) < D \end{equation} where $n$ is the nonce, $p$ is the hash of the preceding block, $m$ is the Merkle root of the transactions in the block, $h\left( \cdot \right)$ is a hash function, and $D$ is the mining target that is small with respect to the whole range of possible hash function outputs. The target $D$ is determined by a difficulty level set by the Bitcoin network. The header $H$ of a block contains $n$, $p$, $m$ and $D$. The difficulty level is dynamically tuned by the Bitcoin protocol, which ensures that the participating nodes, as a whole, produce an average of one block every ten minutes. The process of solving the PoW puzzle is called mining, and the nodes that perform the mining function are known as miners. When other nodes receive a new block broadcasted from the miner, they verify the block locally and independently. The verification of a block can be divided into two parts: 1) the verification of the PoW solution, i.e., verifying whether the nonce $n$ contained in the block header fulfills (\ref{eqn:mininghash}) given the other block header's contents; 2) the verification of the transactions contained in the block body, i.e., verifying the validity of each transaction and verifying whether the Merkle root of all the transactions included in the block body is consistent with the Merkle root contained in the block header. If block passes verification, this block is appended to the local blockchain of the node. \subsection{Blockchain Network Topology} The network of the Bitcoin blockchain is based on an unstructured P2P network. The Bitcoin Core project \cite{bitcoincore} implements the Bitcoin networking protocol. When a node initializes, it attempts to discover a set of peers to establish outgoing or incoming\footnote{Outgoing connections are initiated by the node itself, and incoming connections are initiated by other nodes. When a Bitcoin node boots up, it asks the DNS seed nodes for a list of Bitcoin nodes’ IP addresses. Then, it selects a subset of these addresses and initiates up to 8 outgoing connections. Meanwhile, this node’s IP address will be logged and, going forward, sent to other nodes by the DNS seed nodes. This node will accept up to 117 incoming connections. Super nodes may establish more than 8 outgoing connections.} TCP connections. These connections are used for transaction and block propagation. Each node maintains a list of peers' IP addresses. According to the default protocol in the Bitcoin Core client, a node in the Bitcoin network initiates up to 8 outgoing connections and accepts up to 117 incoming connections. While the Bitcoin infrastructure does not support the discovery of the overall network topology — this is to secure the network from potential network attacks such as Eclipse\cite{heilman2015eclipse}, Sybil\cite{bissias2014sybil} — there have been works that acquire the network topology using the information in the Bitcoin blockchain protocol messages. A Bitcoin P2P Network Sniffer\cite{donet2014bitcoin} can connect to a Bitcoin node and listen to network events such as block broadcast or transaction broadcast. The collected data can be used to infer the size of the Bitcoin P2P network and the geographic distributions of nodes. We use this type of network topology information to model our blockchain network simulator, as discussed in Section \ref{section:simulation}. \subsection{Transaction and Block Dissemination} The network that supports the dissemination of transactions and blocks in the blockchain is a P2P network overlaid over the Internet. Each node keeps a replica of the complete blockchain. There is no central coordinator to ensure the consistency of the replicas across the different nodes. Rather, the nodes use a simple gossip protocol to propagate messages containing transactions and blocks to update and synchronize their ledger replicas. Let us first describe the block propagation protocol of standard relaying (SR) as illustrated in Fig. \ref{fig_1}(a). To avoid unnecessary block forwarding, a peer does not forward blocks to its peer immediately. Instead, an inv \cite{decker2013information} containing a summary of the blocks available—specifically, hashes of the blocks—is sent to a neighbor (node B in Fig. \ref{fig_1}(a)). When a node receives an inv message, it issues a getdata message to the sender, only requesting for blocks that it does not have. The SR protocol, although simple, is inefficient and incurs large propagation delay and has low transaction throughput. Compact-block relaying (CBR) \cite{corallo2017compact}, as illustrated in Fig. \ref{fig_1}(b), is a solution to decrease propagation delay. CBR also announces blocks available at the sender through an inv. However, upon receiving a getdata message, the sender only returns a compact block containing a summary of the transactions included in the entire block (i.e., the hashes of the transactions). The receiver then only requests for the transactions in the block that it does not have (blocktxn in Fig. \ref{fig_1}(b)) rather than the whole block (block in Fig. \ref{fig_1}(a)). Since blocktxn contains only a fraction of all transactions in a block, the bandwidth needed for data propagation is reduced. Although CBR decreases the propagation delay, the sender still needs to have the whole compact block in hand before relaying it. This relaying is called "stored-and-forward". While store-and-forward relaying works well for small compact blocks, if we intend to increase the block size to boost TPS, the compact blocks become large themselves. When relaying compact blocks of large size, the store-and-forward CBR can incur large latency. \begin{figure*}[!t] \centering \includegraphics[width=5in]{Figure1.pdf} \caption{The forwarding of a block over two hops by three different block propagation protocols: (a) the original block propagation protocol; (b) the compact block relaying protocol; (c) the cut-through compact block relaying.} \label{fig_1} \end{figure*} \section{Uncoded Design: Compact-Block Relaying with Cut-through Forwarding}\label{section:Uncoded} This section presents the design of a new CBR protocol. Although the original store-and-forward CBR can increase the TPS to some extent, according to our experiment result (see Section \ref{section:simulation}.2), using the store-and-forward CBR to propagate compact blocks of large size can lead to large propagation delays. As illustrated in Fig. \ref{fig_1}(c), the main essence of our new CBR protocol is to allow parallel relaying of large compact blocks. A node P forwards a compact block to another node Q in small chunks. Node Q then forwards the earlier chunks to node R as later chunks are received. In particular, node Q does not wait for all the chunks of the compact block to be received before forwarding the earlier received chunks. We refer to our block propagation protocol as cut-through compact-block relaying (Cut-through CBR). We elaborate on the details of Cut-through CBR in the following. For a block $B = \left[ {H,{T_1},{T_2}, \cdots ,{T_K}} \right]$, the original CBR constructs the compact block as ${B_c} = \left[ {H,{I_1},{I_2}, \cdots ,{I_K}} \right]$, where $H$ is the header of the block and ${I_k}$ is a the 6-byte short hash of transaction ${T_k}$. When relaying a compact block, instead of sending out the inv message first as in the original CBR, the sender node in our Cut-through CBR immediately broadcasts the block header $H$ to its adjacent peers. In particular, our Cut-through CBR requires the nodes to check whether the block header is valid. Specifically, after receiving the block header, the nodes need to perform the header validation by checking whether the nonce contained in $H$ fulfills (\ref{eqn:mininghash}) to validate the PoW solution. Compared with the full validation\footnote{In the original CBR for Bitcoin, the full validation of a compact block consists of the header validation and the transaction validation. The header validation checks whether the PoW is valid, while the transaction validation check whether the transactions conveyed by the compact block are valid.} of a compact block in the original CBR, this header validation is provisional. As soon as the header $H$ is received, the provisional header validation can begin before the whole compact block is received, consuming much less computation time. This provisional header verification can prevent malicious nodes from generating fake blocks at low cost. Furthermore, to maintain security, if a node in our Cut-through CBR finds an invalid transaction later during the compact block relaying, this node will suspend the compact-block relaying and alert its peers by sending an abort message, as explained in the following. To further elaborate our protocol, as illustrated in Fig. 1(c), we consider a scenario in which a peer P sends out $H$, and peer Q is one of P's neighbors. After peer Q receives $H$ from peer P, peers Q and P execute the following operational steps in order: \begin{enumerate} \item Peer Q first checks whether the received $H$ is in its local pool. If it is, peer Q does nothing and discards $H$. If it is not, peer Q sets peer P as this block's seed peer and goes to the next operation. \item Peer Q performs the provisional header validation of $H$ to verify the PoW solution. If the provisional header validation passes, peer Q puts $H$ into its local pool and broadcasts it to all adjacent peers (except the peer P). Furthermore, peer Q sends a query message to peer P to ask for the transaction hashes in the compact block and then goes to step 4). If the provisional header validation is not fulfilled, peer Q suspends all the operations related to this block. \item After receiving the query message from peer Q, peer P sends peer Q the transaction hashes in chunks. Specifically, every consecutive $M$ transaction hashes are grouped into a hash chunk, and the hash chunks are sent one after another. Peer P keeps sending the hash chunks to peer Q as long as it has any of the hash chunks (either generated from peer P itself if peer P is the miner of this block or received from peer P's seed peers). \item Peer Q receives the hash chunks sent from peer P and performs the chunk validation by validating the transactions indexed by the transaction hashes. In case peer Q lacks some of the transactions on its local storage, it requests the missing transactions from other nodes by sending the getblocktxn message, as in the original CBR \cite{corallo2017compact}. Meanwhile, peer Q also listens for query messages from other peers who treat peer Q as their seed peer of the compact block. As illustrated in Fig. \ref{fig_1}(c), peer Q receives a peer R' query message, peer Q then answers peer R with its validated hash chunks. \item If peer Q finds an invalid transaction during the chunk validation, it will suspend the propagation of this compact block. Furthermore, it will clear all the compact-block related messages related to the compact block from its storage and send an abort message to alert its peers that query for the same compact block. If all transactions pass validation, this block is valid, and peer Q reconstructs the block and appends it to the blockchain. \end{enumerate} Our Cut-through CBR protocol processes the reception and the forwarding of a compact block's small chunks in parallel, in a pipeline manner. It thus speeds up the propagation of a huge compact block. \section{Coded Design: Leveraging Rateless Coding}\label{section:Coded} In Cut-through CBR, a peer can only retrieve the compact block’s chunks from one peer. This section leverages rateless erasure codes to allow a peer to retrieve the chunks from multiple peers. This coded design incorporates fountain codes \cite{luby2002lt} (a kind of rateless erasure codes) into Cut-through CBR to efficiently utilize the upload bandwidths of multiple peers \cite{gkantsidis2005network}. In the coded design, instead of sending $M$ transaction hash chunks $\left\{ {{p_1},{p_2}, \cdots ,{p_M}} \right\}$, the block miner performs fountain coding over the hash chunks to generate the equal-size coded symbols $\{ {x_1},{x_2}, \cdots {x_i}, \cdots \}$ according to the coding scheme proposed in \cite{wang2007network}. Specifically, the coding scheme chooses a set of $M$ coding cofficients ${C_i} = \{ {c_1},{c_2},{c_3} \ldots ,{c_M}\}$ in a finite field. Then we have \begin{equation} \label{eqn:networkCoding} {x_i} = \sum\limits_{j = 1}^M {{c_j}{p_j}} \end{equation} We refer to $\{ {x_1},{x_2} \ldots ,{x_i},...\}$ as the coded hash chunks. Then the miner sends these coded hash chunks (${C_i}$ is also sent out together with ${x_i}$) to the peers querying this compact block. After receiving a coded hash chunk, a peer relays it to some of its peers querying for the same compact block. In this way, each node can be the seed peer of a number of its peers during the compact-block relaying process. Furthermore, fountain code guarantees that the likelihood of decoding a set of coded chunks into the compact-block approaches $1$ when $n = M(1 + \varepsilon)$ coded chunks have been received, where $\varepsilon$ is typically less than $2\%$ \cite{luby2002lt}. We name the rateless-erasure-codes enhanced protocol Coded Cut-through CBR. We describe the operational steps of Coded Cut-thought CBR using an example network topology illustrated in Fig. \ref{fig_2}, where peer P is a miner with two neighbor peers: peer Q and peer S. In particular, peer Q and peer S are also the neighbors of each other. After peer P mines a block, it sends the block header $H$ to peer Q. After peer Q receives $H$, peers Q and P execute the following operational steps in order (these operational steps are illustrated in Fig. \ref{fig_3}): \begin{enumerate} \item Peer Q first checks whether it has the block using in $H$. If it has the block, peer Q does nothing. If it does not have the block, peer Q sets peer P as this block’s seed peer and goes to step 2. \item Peer Q performs the provisional header validation over $H$ to validate the PoW. If the PoW is valid, peer Q puts $H$ into its local pool and relays $H$ to its neighbor peer (in this case, its neighbor peer is peer S). After that, peer Q sends a query message to peer P querying the transaction hashes. If the PoW is not valid, peer Q aborts and does not relay this compact block. \item After receiving the query message from peer Q, peer P sends peer Q the coded hash chunks generated by fountain coding. Specifically, peer P keeps generating and sending the coded hash chunks ${x_i},i = 1,2, \cdots$ to peer Q until peer Q sends back an ACK message announcing that it receives sufficient coded hash chunks to decode the fountain code. In Fig. 3, peer P sends a total of $n$ coded hash chunks to peer Q. \item When receiving coded hash chunks ${x_i},1 \le i \le n$ from peer P, peer Q also relays its received coded hash chunks to peer S that queries the chunks after receiving $H$ from peer Q. \item After receiving the ACK, peer P stops sending its coded hash chunks to peer Q. Peer P then sends $H$ to peer S seeking to be a potential seed peer of peer S. Once receiving the query message sent from peer S, peer P starts generating and sending coded hash chunk ${x_i},i \ge n + 1$ to peer S. \item At this time, peer S has two seed peers of this compact block, namely, peer P and peer Q. Peer S keeps receiving the coded hash chunks sent from either peer P or peer Q. Once it gets sufficient coded hash chunks for decoding the compact block, peer S sends the ACK to peer P and peer Q one after another. In Fig. \ref{fig_3}, peer S receives $j,j \le n$ coded hash chunks from peer Q and $k,k \le n^{'}$ coded hash chunks from peer P. Here, for peer S, we have $j + k = n^{'}$, $n^{'}$ is the number of coded hash chunks required to decode the compact block. \end{enumerate} After receiving sufficient coded chunks, peer Q and peer S decode the fountain-code and validate all transactions. If all transactions pass validation, each peer reconstructs this block and appends it to the blockchain. \begin{figure}[!t] \centering \includegraphics[width=3.5in]{Figure2.pdf} \caption{The network topology of three nodes (peer P, peer Q, and peer S) relaying one compact block using Coded Cut-through CBR. Node P is the miner of the compact block in this example.} \label{fig_2} \end{figure} In Fig. \ref{fig_3}, if the peer Q’s upload bandwidth is much lower than that of other peers, then we have $j \ll n$. In this case, if using standard relaying (SR) (see Section 3.4) and Cut-through CBR, peer S can do nothing except receiving the information sent from peer Q. In Coded Cut-through CBR, however, the available upload bandwidth of other nodes (in this case, the available upload bandwidth of peer P) can be further used to relay the compact block to peer S. Hence, Coded Cut-through CBR leverages the P2P network topology to use the upload bandwidths of all peers efficiently. Thus, it can speed up the information propagation in the Bitcoin blockchain. We theoretically analyze our Cut-through CBR and Coded Cut-through CBR protocols to validate their potential gains in the next section. \begin{figure}[!t] \centering \includegraphics[width=3.5in]{Figure3.pdf} \caption{The illustration for Coded Cut-through CBR.} \label{fig_3} \end{figure} \section{Performance Analysis} This section presents the effect of the block propagation delay on the Bitcoin blockchain's TPS and the analysis of the block propagation latencies of the four propagation protocols (SR, CBR, Cut-through CBR and Coded Cut-through CBR). \label{section:analysis} \subsection{The effect of the block propagation delay on TPS} We first calculate the TPS of the Bitcoin blockchain. We denote the block size by ${S_{block}}$, the average transaction size by ${S_{transaction}}$, and the inter-block generation time by ${T_B}$. The TPS of the blockchain is calculated as \begin{equation} \label{eqn:TPSCal} TPS = \frac{{{S_{block}}}}{{{S_{transaction}}{T_B}}} \end{equation} In Bitcoin, we have ${S_{block}} = 1$ MB, ${S_{transaction}} = 380.04$ B and ${T_B} = 600$ s, and thus the TPS of Bitcoin is $TP{S_{Bitcoin}} = \frac{{1048576}}{{380.04*600}} \approx 4.6$. According to (\ref{eqn:TPSCal}), a simple way to increase the TPS is to increase ${S_{block}}$ or to decrease ${T_B}$. However, merely increasing ${S_{block}}$ or decreasing ${T_B}$ cannot increase the TPS, as explained below. It takes a certain time to propagate a block over the p2p network of the blockchain. Let $L$ denote the time latency of propagating a block from the miner to almost all nodes in the whole network (e.g., $90\%$ of the nodes in the network). First, the increase of ${S_{block}}$ leads to an increase of $L$, which, in turn, may compromise the security of the blockchain \cite{gervais2016security}. In particular, $L$ should be sufficiently smaller than ${T_B}$. The closer $L$ gets to ${T_B}$, the more forks, more orphan blocks, and more chain re-organizations there will be. According to \cite{klarman2018bloxroute}, the probability for a fork to occur at another miner is approximately \begin{equation} \label{eqn:forkCal} P(fork|{T_B} = 600) = 1 - {e^{\frac{{ - L}}{{{T_B}}}}} \end{equation} In the extreme case, the system will be exposed to security vulnerabilities such as double-spend attacks\cite{gervais2016security}. Motivated by (\ref{eqn:forkCal}), this paper uses a performance metric, propagation divergence factor, to quantify the effect of block propagation latency. \\ \textsl{ \textbf{Propagation Divergence Factor}}: The propagation divergence factor is defined as \begin{equation} \label{eqn:PDF} \Delta = \frac{L}{{{T_B}}} \end{equation} where $\Delta \ge 0$ since $L \ge 0$. The larger $\Delta $, the larger the divergence (e.g., asynchronies and discrepancies) is among the different local replicas of the blockchain maintained by different nodes. In the extreme case where $L = 0$, we have $\Delta = 0$ meaning that the blockchains of all the nodes in the network become instantaneously synchronized. The main purpose of our protocols is to suppress the increase of $L$ when we increase ${S_{block}}$. In this way, we can boost the TPS of the Bitcoin blockchain while maintaining the security of the blockchain. According to (\ref{eqn:TPSCal}), increasing ${S_{block}}$ by 100x can increase the TPS by 100x, yielding $TP{S_{Bitcoin}} \approx 460$. In the next subsection, we analyze the block propagation latency $L$ caused by different block propagation protocols. \begin{figure}[!t] \centering \includegraphics[width=3.5in]{Figure4.pdf} \caption{A simple linear network with $n+1$ nodes.} \label{fig_4} \end{figure} \subsection{The comparison of the block propagation latency using different protocols} We next analyze the block propagation latencies of the four propagation protocols (SR, CBR, Cut-through CBR and Coded Cut-through CBR). For simple illustration, we consider a network with a linear topology consisting of $n + 1$ nodes as shown in Fig. \ref{fig_4}. We assume the communication bandwidth of each node is $B$. We calculate the block propagation latency of propagating a block from node $0$ to node $n$ in this linear network. Let ${S_{ip}}$ be the IP packet's payload size and ${S_h}$ be the IP packet header size. When using SR to propagate blocks, with IP packet fragmentation, a block needs to be cut into $\frac{{{S_{block}}}}{{{S_{ip}}}}$ IP packets. The block propagation latency from node $0$ to node $n$ caused under the SR protocol is given by \begin{equation} \label{eqn:L_SR} {L_{SR}} = \frac{{n({S_{block}} + {O_b})}}{B} + n{V_b} \end{equation} where ${O_b} = \frac{{{S_{block}}}}{{{S_{ip}}}}{S_h}$ is the overhead caused by the IP packet fragmentation when relaying a block over one hop between two neighbor nodes, and ${V_b}$ is the time incurred by a full-block validation process. Let ${N_t}$ be the number of transactions in a block. The size of a compact block is given by \begin{equation} \label{eqn:Size_CBR} {S_{cb}} = {N_t}{S_I} + {S_{h\_cb}} \end{equation} where ${S_I}$ is the size of a short transaction hash and ${S_{h\_cb}}$ is the size of the compact-block header. When using CBR, a compact block needs to be cut into $\frac{{{S_{cb}}}}{{{S_{ip}}}}$ IP packets. Recall that in Bitcoin, nodes have 10 min (${T_B} = 10$ min) to propagate their collected transactions to all other nodes before the transactions are announced in the latest block. For the sake of simplicity, we assume that all transactions within the block are already available at the nodes given the long duration of 10 min, and there is no need to go and fetch the transactions. In fact, \cite{corallo2017compact} found that in the Bitcoin network, before a new block is found, transactions obtained by all nodes are almost synchronized. Then, the block propagation latency from node $0$ to node $n$ under CBR is given by \begin{equation} \label{eqn:L_CBR} {L_{CBR}} = \frac{{n({S_{cb}} + {O_{cb}})}}{B} + n{V_b} \end{equation} where ${O_{cb}} = \frac{{{S_{cb}}}}{{{S_{ip}}}}{S_h}$ is the overhead caused by the IP packet fragment when relaying a compact block over one hop. From (\ref{eqn:L_SR}) and (\ref{eqn:L_CBR}), we can see that CBR speeds up the block propagation significantly, since ${S_{cb}} \ll {S_b}$. In particular, if ${V_b}$ is negligible, CBR can reduce the block propagation latency by $\frac{{{S_{block}}}}{{{S_{cb}}}}$ times compared with SR. However, ${L_{CBR}}$ is still proportional to $n{S_{cb}}$. Consequently, the increase of ${S_{cb}}$ can lead a significant increase of ${L_{CBR}}$, making it impossible to increase TPS by inserting more transaction hashes into each compact block. We next analyze the propagation latency of the cut-through forwarding scheme used in both Cut-through CBR and Coded Cut-through CBR. Let $k \ge 1$ be the number of chunks per compact block and ${S_{ch}}$ be the chunk size. We thus have ${S_{cb}} = k{S_{ch}}$. Let ${V_{ch}} = \frac{{{V_b}}}{k}$ be the time needed to validate the transactions in a chunk and ${O_{ch}}$ be the overhead of IP packet fragmentation when relaying a chunk over one hop. The block propagation latency from node $0$ to node $n$ under Cut-through CBR is given by \begin{equation} \label{eqn:L_CT} {L_{CT - CBR}} = k(\frac{{{S_{ch}} + {O_{ch}}}}{B} + {V_{ch}}) + (n - 1)(\frac{{{S_{ch}} + {O_{ch}}}}{B} + {V_{ch}}) \end{equation} The first term of (\ref{eqn:L_CT}) is the block propagation latency in the first hop (from node $0$ to node $n$) and the second term of (\ref{eqn:L_CT}) is the block propagation latency over the rest of the hops (from node $0$ to node $n$). We further investigate the effect of $k$ when using the cut-through forwarding scheme in the following two cases: If $1 \le k \le \frac{{{S_{cb}}}}{{{S_{ip}}}}$, then we have $\frac{{{S_{cb}}}}{k} = {S_{ch}} \ge {S_{ip}}$, which means that we need to perform IP packet fragmentation over each chunk. Specifically, a chunk needs to be cut into $\frac{{{S_{ch}}}}{{{S_{ip}}}}$ IP packets and ${O_{ch}} = \frac{{{S_{ch}}}}{{{S_{ip}}}}{S_h} = \frac{{{O_{cb}}}}{k}$. From (\ref{eqn:L_CT}), we then have \begin{equation} \label{eqn:L_CT-1} {L_{CT - CBR}} = (\frac{{{S_{cb}} + {O_{cb}}}}{B} + {V_b}) + \frac{{(n - 1)}}{k}(\frac{{{S_{cb}} + {O_{cb}}}}{B} + {V_b}) \end{equation} Compared with (\ref{eqn:L_CBR}), the increase of $k$ in (\ref{eqn:L_CT-1}) will significantly reduce the block propagation latency. We denote the gain obtained from the cut-through forwarding scheme over the original CBR by ${g_{CT - CBR}} = {L_{CBR}} - {L_{CT - CBR}}$. The gain ${g_{CT - CBR}}$ can be computed as \begin{equation} \label{eqn:g_CT-1} \begin{array}{l} {g_{CT - CBR}} = \frac{{n({S_{cb}} + {O_{cb}})}}{B} + n{V_b} - (k + n - 1)(\frac{{{S_{ch}} + {O_{ch}}}}{B} + {V_{ch}})\\ = \frac{{n({S_{cb}} + {O_{cb}}) - (k + n - 1)(\frac{{{S_{cb}}}}{k} + \frac{{{O_{cb}}}}{k})}}{B} + n{V_b} - (k + n - 1)\frac{{{V_b}}}{k}\\ = (1 - \frac{1}{k})(n - 1)(\frac{{({S_{cb}} + {O_{cb}})}}{B} + {V_b}) \end{array} \end{equation} Note that since $k \ge 1$ and $1 - \frac{1}{k} > 0$, we have ${g_{CT - CBR}} > 0$. That is, the cut-through forwarding scheme outperforms the traditional CBR when $1 \le k \le \frac{{{S_{cb}}}}{{{S_{ip}}}}$. Eqn. (\ref{eqn:L_CBR}) and Eqn. (\ref{eqn:g_CT-1}) lead to several conclusions: \begin{enumerate} \item When $k = 1$ or $n = 1$, both Cut-through CBR and Coded Cut-through CB downgrade to CBR. \item When $k$ is fixed, the gain obtained from the cut-through forwarding scheme becomes larger with the increase of ${S_{cb}}$. The cut-through forwarding scheme hence is expected to perform well even if ${S_{cb}}$ is very large. \item When ${S_{cb}}$ is fixed, ${L_{CT - CBR}}$ is a decreasing function of $k$. The increase of $k$ achieves lower propagation latency. \end{enumerate} If $k > \frac{{{S_{cb}}}}{{{S_{ip}}}}$, then we have $\frac{{{S_{cb}}}}{k} = {S_{ch}} < {S_{ip}}$. In this case, we use one IP packet to transmit one chunk with the IP packet size smaller than the maximum IP packet size. Hence ${O_{ch}} = {S_h}$ and the gain ${g_{CT - CBR}}$ is given by \begin{equation} \label{eqn:g_CT-2} \begin{array}{l} {g_{CT - CBR}} = \frac{{n({S_{cb}} + {O_{cb}})}}{B} + n{V_b} - (k + n - 1)(\frac{{{S_{ch}} + {O_{ch}}}}{B} + {V_{ch}})\\ = \frac{{n({S_{cb}} + {O_{cb}}) - (k + n - 1)(\frac{{{S_{cb}}}}{k} + {S_h})}}{B} + n{V_b} - (k + n - 1)\frac{{{V_b}}}{k} \end{array} \end{equation} From (\ref{eqn:g_CT-2}), we can see that ${L_{CT - CBR}}$ is no more a decreasing function of $k$. To find the optimal k that maximizes the gain expressed in (\ref{eqn:g_CT-2}), we can set the derivative of ${L_{CT - CBR}}$ with respect to $k$ to zero: $\frac{{d{g_{CT - CBR}}}}{{dk}} = 0$, and solve the equation. The optimal k is given by \begin{equation} \label{eqn:choice_k} {k^*} = \sqrt {\frac{{B(n - 1)({V_b} + {S_{cb}})}}{{{S_h}}}} \end{equation} where the gain ${L_{CT - CBR}}$ achieves its maximum. The above analysis for a linear network shows the potential gain brought by our Cut-through CBR protocol. In the next section, we will investigate the performances of our Cut-through CBR and Coded Cut-through CBR protocols under a practical network setup. \section{Simulation Results} \label{section:simulation} This section presents simulation results comparing the performance of the four block-propagation protocols: SR, CBR, Cut-through CBR, and Coded Cut-through CBR. Specifically, using the network simulator 3 (NS3) \cite{henderson2008network}, we investigate the block-propagation latencies of these four propagation protocols in a simulated Bitcoin network. \subsection{Simulation Setup} Our investigation is performed on a simulator extended from the Bitcoin simulator implemented by \cite{gervais2016security}. The Bitcoin simulator, written in NS3, is designed to simulate Bitcoin nodes' behavior in the Bitcoin network. The Bitcoin simulator can simulate a Bitcoin network with thousands of nodes. The Bitcoin simulator retrieved the current geographical node distribution from bitnodes.21.co and adopted the distribution to define its simulated nodes' locations. In the simulated Bitcoin network, the connection between two nodes is established as a point-to-point (P2P) link. Each P2P link has a random bandwidth and transmission delay (according to the geographical location) following a statistical distribution from Verizon \cite{verizon} and testmy.net \cite{testmy}. The parameters in Table I presents the parameters used in the Bitcoin simulator \cite{gervais2016security}. \begin{table}[] \caption{PARAMETERS OF THE BITCOIN SIMULATOR} \label{tab:my-table} \centering \begin{tabular}{|l|l|} \hline Parameter & Bitcoin Simulator \\ \hline \# of the nodes & 6000 \\ \hline Block interval & 10 min \\ \hline \# of the connection & \begin{tabular}[c]{@{}l@{}}Distribution according to\\ Miller et al. \cite{miller2015discovering}\end{tabular} \\ \hline Geographical distribution & \begin{tabular}[c]{@{}l@{}}Distribution according to \\ actual blockchains\end{tabular} \\ \hline Bandwidth propagation delay & \begin{tabular}[c]{@{}l@{}}6 regional bandwidth and \\propagation delay\end{tabular} \\ \hline \end{tabular} \end{table} The original Bitcoin simulator already included the SR protocol. We implemented CBR, Cut-through CBR and Coded Cut-through CBR in the simulator. The extended simulator allows us to set parameters such as the block size and the chunks per block for Cut-through CBR and Coded Cut-through CBR. We performed simulations to investigate the effect of block size on the network block propagation latency and the propagation divergence factor defined in (\ref{eqn:PDF}) under different block propagation protocols. Our overall simulation experiment consists of several simulation runs. We fixed a block size for each run and then ran separate simulations to evaluate SR, CBR, Cut-through CBR, and Coded Cut-through CBR. Each simulation run, for a specific relay protocol, monitored the statistics of up to $10\,000$ blocks created during the simulation to smooth the experimental results. \begin{figure}[!t] \centering \includegraphics[width=3.5in]{Figure5.png} \caption{Median block propagation latency versus block size for different block propagation protocols.} \label{fig_5} \end{figure} \begin{figure} \begin{subfigure}{.5\textwidth} \centering \includegraphics[width=.8\linewidth]{Figure-CDF1M.png} \caption{BLOCK SIZE: 1 MB} \end{subfigure} \begin{subfigure}{.5\textwidth} \centering \includegraphics[width=.8\linewidth]{Figure-CDF25M.png} \caption{BLOCK SIZE: 25 MB} \end{subfigure} \begin{subfigure}{.5\textwidth} \centering \includegraphics[width=.8\linewidth]{Figure-CDF50M.png} \caption{BLOCK SIZE: 50 MB} \end{subfigure} \begin{subfigure}{.5\textwidth} \centering \includegraphics[width=.8\linewidth]{Figure-CDF100M.png}\caption{BLOCK SIZE: 100 MB} \end{subfigure} \caption{CDF of block propagation latency for different block propagation protocols.} \label{fig_6} \end{figure} \subsection{Experimental Results} Fig. \ref{fig_5} and Fig. \ref{fig_6} show the median and the CDF of the block propagation latency, respectively. We have the following observations: \begin{enumerate} \item When relaying a large block, cut-through forwarding can significantly speed up block propagation with respect to SR and CBR. For example, Fig. 5 and Fig. 6 show that when relaying a block larger than $25$ MB, Cut-through CBR and Coded Cut-through CBR reduce both the median and the tail of block propagation latency by up to three times compared with CBR and by up to more than one hundred times compared with SR. \item Coded Cut-thought CBR can further speed up the block propagation compared to Cut-through CBR. For example, Fig. 5 and Fig. 6 show that the median and the tail of block propagation latency of Coded Cut-through CBR are both up to two times smaller than that of cut-through CBR for different $k$. \end{enumerate} Fig. \ref{fig_7} shows the stale-block rate versus the propagation divergence factor $\Delta $. We can see that large $\Delta $ increases stale-block rate significantly. The reason is that when the block propagation divergence factor is large, a miner cannot receive the latest announced block (mined by others) in time and may still announce its mined block with the same block height, leading to a large stale-block rate. Fig. 8 shows the propagation divergence factor $\Delta $ of different protocols when different block sizes are used. From Fig. \ref{fig_8}, we can see that the propagation divergence factors $\Delta $ of SR and CBR increase significantly when the block size is large, leading to a large stale-block rate. For example, increasing block size from 1 MB to 100 MB (100x) increases the propagation divergence factor $\Delta $ by 30x and increases the stale-block rate by around 30x for CBR. However, Cut-through CBR and Coded Cut-through CBR can suppress the increase of $\Delta $ with the increase of block size. In particular, the $\Delta $ of Coded Cut-through CBR with the optimal $k$ (the optimal $k$ is obtained through experiments), when the block size is 100 MB, is roughly equal to the $\Delta $ of SR when the block size is 1MB. \begin{figure}[!t] \centering \includegraphics[width=3.5in]{Figure7.png} \caption{Stale-block size versus propagation divergence factor derived using (\ref{eqn:forkCal}).} \label{fig_7} \end{figure} \begin{figure}[!t] \centering \includegraphics[width=3.5in]{Figure8.png} \caption{Propagation divergence factor versus block size for different block propagation protocols.} \label{fig_8} \end{figure} In summary, Cut-through CBR and Coded Cut-through CBR can be used for propagating 100 MB blocks while maintaining the propagation latency to the level of the traditional block propagation protocol that propagates 1 MB blocks, hence increasing the TPS capacity by 100x. \section{Conclusion} \label{section:conclusion} We proposed a new blockchain networking protocol to increase the TPS of the Bitcoin blockchain. When a large block size is used in the Bitcoin blockchain, original block propagation protocols, such as SR and CBR, suffer from large block propagation delays to large stale-block rate, compromising the blockchain's security. In this work, we put forth a two-pronged approach to increase the block size without inducing extra propagation latency. First, we design a Cut-through CBR that enables parallel reception and forwarding of compact blocks at relay nodes. Second, we design a Coded Cut-through CBR that incorporates rateless erasure codes into Cut-through CBR to further increase efficiency. Our simulation results demonstrate that our protocols can significantly reduce the block propagation latency and suppress the stale-block rate. Specifically, our protocols can increase the TPS of the Bitcoin blockchain by 100x without compromising the blockchain's security. More importantly, our approach only needs to rework the communication and networking architecture of the current Bitcoin blockchain without changing the data structures and crypto-functional components in them. Therefore, our protocols can be seamlessly incorporated into the existing Bitcoin blockchain. The implementation of our protocols in Bitcoin-like blockchains may allow the blockchains to be used in many use cases not possible currently. \ifCLASSOPTIONcaptionsoff \newpage \fi \bibliographystyle{IEEEtran}
{'timestamp': '2021-01-05T02:13:52', 'yymm': '2101', 'arxiv_id': '2101.00378', 'language': 'en', 'url': 'https://arxiv.org/abs/2101.00378'}
arxiv